Merge mozilla-central to mozilla-inbound
authorDorel Luca <dluca@mozilla.com>
Fri, 03 May 2019 16:12:49 +0300
changeset 531392 d12dfc397c08c0d8f7bf6ff2ca7596b1d4916893
parent 531391 4352d1f0da341b26f79de16ca5b966ba17caa5da (current diff)
parent 531275 c68ff92fe54c75338c3a937bc6c4e615d9b1d45a (diff)
child 531393 a64a71ccebf79139da2288edca29186292c5a257
push id11265
push userffxbld-merge
push dateMon, 13 May 2019 10:53:39 +0000
treeherdermozilla-beta@77e0fe8dbdd3 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone68.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Merge mozilla-central to mozilla-inbound
dom/quota/ActorsParent.cpp
--- a/browser/branding/aurora/pref/firefox-branding.js
+++ b/browser/branding/aurora/pref/firefox-branding.js
@@ -1,15 +1,14 @@
 
 
 /* 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/. */
 
-pref("startup.homepage_override_url", "https://www.mozilla.org/%LOCALE%/firefox/%VERSION%a2/whatsnew/");
 pref("startup.homepage_welcome_url", "https://www.mozilla.org/%LOCALE%/firefox/%VERSION%a2/firstrun/");
 pref("startup.homepage_welcome_url.additional", "");
 // The time interval between checks for a new version (in seconds)
 pref("app.update.interval", 28800); // 8 hours
 // Give the user x seconds to react before showing the big UI. default=192 hours
 pref("app.update.promptWaitTime", 691200);
 // URL user can browse to manually if for some reason all update installation
 // attempts fail.
--- a/browser/config/whats_new_page.yml
+++ b/browser/config/whats_new_page.yml
@@ -104,8 +104,61 @@
           - sl
           - sq
           - sv-SE
           - tr
           - uk
           - vi
           - zh-CN
           - zh-TW
+- type: show-url
+  # yamllint disable-line rule:line-length
+  url: "https://www.mozilla.org/%LOCALE%/{product}/{version.major_number}.0a2/whatsnew/?oldversion=%OLD_VERSION%"
+  conditions:
+      blob-types: [wnp]
+      release-types: [beta]
+      products: [firefox]
+      update-channel: aurora
+      # e.g.: ["<61.0"]. {version.major_number} reflects the current version.
+      # This is done by taskgraph.
+      versions: ["<{version.major_number}.0"]
+      locales:
+          - be
+          - cak
+          - cs
+          - cy
+          - da
+          - de
+          - dsb
+          - en-CA
+          - en-GB
+          - en-US
+          - es-AR
+          - es-CL
+          - es-ES
+          - es-MX
+          - fr
+          - fy-NL
+          - gn
+          - hsb
+          - hu
+          - ia
+          - id
+          - it
+          - ka
+          - lij
+          - nl
+          - nn-NO
+          - pl
+          - pt-BR
+          - pt-PT
+          - rm
+          - ro
+          - ru
+          - sk
+          - sl
+          - sq
+          - sv-SE
+          - tr
+          - uk
+          - vi
+          - zh-CN
+          - zh-TW
--- a/devtools/client/aboutdebugging-new/src/base.css
+++ b/devtools/client/aboutdebugging-new/src/base.css
@@ -24,19 +24,21 @@
 
   --link-color: #0a8dff;
   --link-color-active: #003eaa;
   --link-color-hover: #0060df;
 
   /* Colors from Photon */
   --success-background: #30e60b;
   --warning-background: #fffbd6; /* from the Web Console */
+  --warning-border: rgba(164, 127, 0, 0.27); /* yellow-70(#a47f00) at 27% */
   --warning-icon: var(--yellow-65); /* from the Web Console */
   --warning-text: var(--yellow-80); /* from the Web Console */
   --error-background: #fdf2f5; /* from the Web Console */
+  --error-border: rgba(90, 0, 2, 0.16); /*  red-80(#5a0002) at 16% */
   --error-icon: var(--red-60); /* from the Web Console */
   --error-text: var(--red-70); /* from the Web Console */
   --highlight-50: #0a84ff;
   --grey-20: #ededf0; /* for ui, no special semantic */
   --grey-30: #d7d7db; /* for ui, no special semantic */
   --grey-50: #737373; /* for ui, no special semantic */
   --grey-90: #0c0c0d; /* for ui, no special semantic */
   --grey-90-a10: rgba(12, 12, 13, 0.1);
--- a/devtools/client/aboutdebugging-new/src/components/shared/Message.css
+++ b/devtools/client/aboutdebugging-new/src/components/shared/Message.css
@@ -1,41 +1,45 @@
 /* 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/. */
 
 .message--level-error {
+  --message-background-color: var(--error-background);
+  --message-border-color: var(--error-border);
   --message-color: var(--error-text);
-  --message-background-color: var(--error-background);
   --message-icon-color: var(--error-icon);
 }
 
 .message--level-info {
+  --message-background-color: var(--grey-20);
+  --message-border-color: transparent;
   --message-color: var(--grey-90);
-  --message-background-color: var(--grey-20);
   --message-icon-color: var(--grey-90);
 }
 
 .message--level-warning {
+  --message-background-color: var(--warning-background);
+  --message-border-color: var(--warning-border);
   --message-color: var(--warning-text);
-  --message-background-color: var(--warning-background);
   --message-icon-color: var(--warning-icon);
 }
 
 /*
  * Layout of the message
  *
  *  +--------+-----------------+----------+
  *  | Icon   | Message content | closing  |
  *  |        | (several lines) | button   |
  *  |        | (     ...     ) |(optional)|
  *  +--------+-----------------+----------+
  */
 .message {
   background-color: var(--message-background-color);
+  border: 1px solid var(--message-border-color);
   border-radius: var(--base-unit);
   color: var(--message-color);
   display: grid;
   grid-column-gap: var(--base-unit);
   grid-template-columns: calc(var(--base-unit) * 6) 1fr auto;
   grid-template-areas:
     "icon body button";
   margin: calc(var(--base-unit) * 2) 0;
@@ -45,19 +49,21 @@
 
 .message__icon {
   margin: var(--base-unit);
   fill: var(--message-icon-color);
   grid-area: icon;
 }
 
 .message__body {
+  align-self: center;
   font-size: var(--message-font-size);
   font-weight: 400;
   grid-area: body;
+  line-height: 1.6;
 }
 
 .message__button {
   grid-area: button;
   fill: var(--message-icon-color);
 }
 
 .message__button:hover {
--- a/devtools/client/aboutdebugging-new/src/components/sidebar/SidebarItem.css
+++ b/devtools/client/aboutdebugging-new/src/components/sidebar/SidebarItem.css
@@ -43,11 +43,11 @@
   background-color: var(--sidebar-background-hover);
 }
 
 .sidebar-item--selected {
   color: var(--sidebar-selected-color);
 }
 
 .sidebar-item--breathe {
-  margin-block-start: calc(2 * var(--base-unit));
+  margin-block-start: calc(6 * var(--base-unit));
   margin-block-end: calc(2 * var(--base-unit));
 }
--- a/devtools/client/aboutdebugging-new/src/components/sidebar/SidebarRuntimeItem.css
+++ b/devtools/client/aboutdebugging-new/src/components/sidebar/SidebarRuntimeItem.css
@@ -28,13 +28,14 @@
 
 .sidebar-runtime-item__runtime {
   line-height: 1;
 }
 
 .sidebar-runtime-item__runtime__details {
   font-size: var(--caption-10-font-size);
   font-weight: var(--caption-10-font-weight);
+  line-height: 1.2;
 }
 
 .sidebar-runtime-item__message:first-of-type {
   margin-block-start: calc(var(--base-unit) * -1);
 }
--- a/devtools/client/accessibility/accessibility.css
+++ b/devtools/client/accessibility/accessibility.css
@@ -7,42 +7,41 @@
   --accessibility-toolbar-height: 24px;
   --accessibility-toolbar-height-tall: 35px;
   --accessibility-toolbar-focus: var(--blue-50);
   --accessibility-toolbar-focus-alpha30: rgba(10, 132, 255, 0.3);
   --accessibility-full-length-minus-splitter: calc(100% - 1px);
   --accessibility-horizontal-padding: 5px;
   --accessibility-horizontal-indent: 20px;
   --accessibility-properties-item-width: calc(100% - var(--accessibility-horizontal-indent));
+  --accessibility-tree-height: calc(100vh - var(--accessibility-toolbar-height) * 2 - 1px);
   --accessibility-arrow-horizontal-padding: 4px;
   --accessibility-tree-row-height: 21px;
   --accessibility-unfocused-tree-focused-node-background: var(--grey-20);
   --accessibility-unfocused-tree-focused-node-twisty-fill: var(--theme-icon-dimmed-color);
   --accessibility-link-color: var(--blue-60);
   --accessibility-link-color-active: var(--blue-70);
   --badge-active-background-color: var(--blue-50);
   --badge-active-border-color: #FFFFFFB3;
   --badge-interactive-background-color: var(--grey-20);
-  --badge-interactive-color: var(--grey-90);
   --accessible-label-background-color: white;
   --accessible-label-border-color: #CACAD1;
   --accessible-label-color: var(--grey-60);
   /* Similarly to webconsole, add more padding before the toolbar group. */
   --separator-inline-margin: 5px;
 }
 
 :root.theme-dark {
   --accessibility-unfocused-tree-focused-node-background: var(--grey-70);
   --accessibility-unfocused-tree-focused-node-twisty-fill: var(--theme-selection-color);
   --accessibility-link-color: var(--theme-highlight-blue);
   --accessibility-link-color-active: var(--blue-40);
   --badge-active-background-color: var(--blue-60);
   --badge-active-border-color: #FFF6;
   --badge-interactive-background-color: var(--grey-70);
-  --badge-interactive-color: var(--grey-30);
   --accessible-label-background-color: var(--grey-80);
   --accessible-label-border-color: var(--grey-50);
   --accessible-label-color: var(--grey-40);
 }
 
 /* General */
 html,
 body {
@@ -66,37 +65,39 @@ body {
   width: var(--accessibility-horizontal-indent);
 }
 
 .accessible .tree .node.focused .theme-twisty,
 .treeTable .treeRow.selected .theme-twisty {
   fill: var(--theme-selection-color);
 }
 
-.mainFrame .main-panel {
-  flex: 1 1 auto;
-  overflow: auto;
-}
-
 .mainFrame {
   height: 100%;
   color: var(--theme-toolbar-color);
 }
 
+.main-panel {
+  /* To compenstate for 1px splitter between the tree and sidebar. */
+  width: var(--accessibility-full-length-minus-splitter);
+}
+
 .devtools-button,
 .toggle-button {
   cursor: pointer;
 }
 
 .mainFrame .devtools-button.devtools-throbber::before,
 .mainFrame .toggle-button.devtools-throbber::before {
   /* Default for .devtools-throbber is set to 1em which is too big for the
      devtools toolbar. */
-  height: 9px;
-  width: 9px;
+  height: 8px;
+  width: 8px;
+  margin-block-end: 1px;
+  margin-inline-end: 2px;
 }
 
 .split-box.horz {
   height: calc(100vh - var(--accessibility-toolbar-height));
 }
 
 .mainFrame .devtools-button,
 .description .devtools-button {
@@ -161,16 +162,25 @@ body {
   -moz-outline-radius: 2px;
 }
 
 .devtools-toolbar .help:focus > .btn-content {
   outline: none;
   box-shadow: none;
 }
 
+.devtools-toolbar .accessibility-tree-filters {
+  display: flex;
+  flex-wrap: nowrap;
+  flex-direction: row;
+  align-items: center;
+  white-space: nowrap;
+  margin-inline-end: 5px;
+}
+
 /* Description */
 .description {
   color: var(--theme-toolbar-color);
   font: message-box;
   font-size: calc(var(--accessibility-font-size) + 1px);
   margin: auto;
   padding-top: 15vh;
   width: 50vw;
@@ -220,34 +230,40 @@ body {
 }
 
 .description .link:active {
   color: var(--accessibility-link-color-active);
   text-decoration: underline;
 }
 
 /* TreeView Customization */
-.split-box:not(.horz) .main-panel {
-  height: calc(100vh - var(--accessibility-toolbar-height));
+.treeTable thead, .treeTable tbody {
+  display: block;
+}
+
+.treeTable tr {
+  width: 100%;
+  display: table;
 }
 
-.treeTable > thead {
-  position: sticky;
-  top: 0;
-  /* Bug 1466806 - fix expander arrow for expanding treeview rows rendering over the
-     thead */
-  z-index: 1;
+.treeTable tbody {
+  overflow-y: auto;
+}
+
+.split-box:not(.horz) .treeTable tbody {
+  height: var(--accessibility-tree-height);
 }
 
-.split-box:not(.horz) .treeTable {
-  /* To compenstate for 1px splitter between the tree and sidebar. */
-  width: var(--accessibility-full-length-minus-splitter);
+.split-box.horz .treeTable tbody {
+  /* Accessibility tree height depends on the height of the controlled panel
+     (sidebar) when in horz mode and also has an additional separator. */
+  height: calc(var(--accessibility-tree-height) - var(--split-box-controlled-panel-size) - 1px);
 }
 
-.split-box.horz .treeTable {
+.treeTable {
   width: 100%;
 }
 
 .treeTable .treeRow.highlighted:not(.selected) {
   background-color: var(--theme-selection-background-hover);
 }
 
 .treeTable.filtered .treeRow .treeLabelCell {
@@ -313,64 +329,61 @@ body {
 
 .mainFrame .treeTable .treeHeaderRow > .treeHeaderCell:first-child > .treeHeaderCellBox,
 .mainFrame .treeTable .treeHeaderRow > .treeHeaderCell > .treeHeaderCellBox {
   padding: 0;
   padding-inline-start: var(--accessibility-arrow-horizontal-padding);
 }
 
 .mainFrame .treeTable .treeHeaderCell {
+  width: 50%;
   border-bottom: 1px solid var(--theme-splitter-color);
   background: var(--theme-toolbar-background);
   font: message-box;
   font-size: var(--accessibility-font-size);
   height: var(--accessibility-toolbar-height);
   color: var(--theme-toolbar-color);
 }
 
-.badge.toggle-button,
-.mainFrame .treeTable .treeRow .badges .badge {
-  background-color: var(--badge-interactive-background-color);
-  color: var(--badge-interactive-color);
+.badge {
+  font: message-box;
   border-radius: 3px;
   padding: 0px 2px;
   margin-inline-start: 5px;
+  color: var(--accessible-label-color);
+  background-color: var(--accessible-label-background-color);
+  border: 1px solid var(--accessible-label-border-color);
 }
 
 .badge.toggle-button {
-  border: 1px solid transparent;
   color: var(--theme-body-color);
+  background-color: var(--badge-interactive-background-color);
+  border-color: transparent;
 }
 
 .devtools-toolbar .badge.toggle-button:focus {
   outline: 2px solid var(--accessibility-toolbar-focus);
   outline-offset: -2px;
   box-shadow: 0 0 0 2px var(--accessibility-toolbar-focus-alpha30);
   -moz-outline-radius: 2px;
 }
 
-.mainFrame .treeTable .treeRow .badges .badge {
-  border: 1px solid var(--accessible-label-border-color);
-}
-
-.mainFrame .treeTable:focus .treeRow.selected .badges .badge {
-  background-color: var(--badge-interactive-background-color);
-  border: 1px solid var(--accessible-label-border-color);
-  color: var(--badge-interactive-color);
-}
-
-.badge.toggle-button.checked,
-.mainFrame .treeTable:focus .treeRow.selected .badges .badge.checked,
-.mainFrame .treeTable .treeRow .badges .badge.checked {
+.treeTable:focus .treeRow.selected .badges .badge {
   background-color: var(--badge-active-background-color);
+  border-color: var(--accessible-active-border-color);
   color: var(--theme-selection-color);
 }
 
-.mainFrame .treeTable .treeRow .badges .badge.checked {
-  border: 1px solid var(--badge-active-border-color);
+.treeTable:not(:focus):not(:focus-within) .treeRow.selected .badges .badge {
+  color: var(--accessible-label-color);
+}
+
+.badge.toggle-button.checked {
+  background-color: var(--badge-active-background-color);
+  color: var(--theme-selection-color);
 }
 
 /* Avoid having a default dotted border on keyboard focus since we provide focus
    styling*/
 .badge.toggle-button::-moz-focus-inner {
   border: none;
 }
 
--- a/devtools/client/accessibility/components/AccessibilityRow.js
+++ b/devtools/client/accessibility/components/AccessibilityRow.js
@@ -25,16 +25,18 @@ const { VALUE_FLASHING_DURATION, VALUE_H
 const { updateDetails } = require("../actions/details");
 const { unhighlight } = require("../actions/accessibles");
 
 const { L10N } = require("../utils/l10n");
 
 loader.lazyRequireGetter(this, "Menu", "devtools/client/framework/menu");
 loader.lazyRequireGetter(this, "MenuItem", "devtools/client/framework/menu-item");
 
+const { scrollIntoView } = require("devtools/client/shared/scroll");
+
 const JSON_URL_PREFIX = "data:application/json;charset=UTF-8,";
 
 const TELEMETRY_ACCESSIBLE_CONTEXT_MENU_OPENED =
   "devtools.accessibility.accessible_context_menu_opened";
 const TELEMETRY_ACCESSIBLE_CONTEXT_MENU_ITEM_ACTIVATED =
   "devtools.accessibility.accessible_context_menu_item_activated";
 
 class HighlightableTreeRowClass extends TreeRow {
@@ -66,17 +68,17 @@ class AccessibilityRow extends Component
       walker: PropTypes.object,
     };
   }
 
   componentDidMount() {
     const { selected, object } = this.props.member;
     if (selected) {
       this.unhighlight();
-      this.updateAndScrollIntoViewIfNeeded();
+      this.update();
       this.highlight(object, { duration: VALUE_HIGHLIGHT_DURATION });
     }
 
     if (this.props.highlighted) {
       this.scrollIntoView();
     }
   }
 
@@ -84,17 +86,17 @@ class AccessibilityRow extends Component
    * Update accessible object details that are going to be rendered inside the
    * accessible panel sidebar.
    */
   componentDidUpdate(prevProps) {
     const { selected, object } = this.props.member;
     // If row is selected, update corresponding accessible details.
     if (!prevProps.member.selected && selected) {
       this.unhighlight();
-      this.updateAndScrollIntoViewIfNeeded();
+      this.update();
       this.highlight(object, { duration: VALUE_HIGHLIGHT_DURATION });
     }
 
     if (this.props.highlighted) {
       this.scrollIntoView();
     }
 
     if (!selected && prevProps.member.value !== this.props.member.value) {
@@ -105,27 +107,26 @@ class AccessibilityRow extends Component
   scrollIntoView() {
     const row = findDOMNode(this);
     // Row might not be rendered in the DOM tree if it is filtered out during
     // audit.
     if (!row) {
       return;
     }
 
-    row.scrollIntoView({ block: "center" });
+    scrollIntoView(row);
   }
 
-  updateAndScrollIntoViewIfNeeded() {
+  update() {
     const { dispatch, member: { object }, supports } = this.props;
     if (!gToolbox || !object.actorID) {
       return;
     }
 
     dispatch(updateDetails(gToolbox.walker, object, supports));
-    this.scrollIntoView();
     window.emit(EVENTS.NEW_ACCESSIBLE_FRONT_SELECTED, object);
   }
 
   flashValue() {
     const row = findDOMNode(this);
     // Row might not be rendered in the DOM tree if it is filtered out during
     // audit.
     if (!row) {
--- a/devtools/client/accessibility/components/AccessibilityRowValue.js
+++ b/devtools/client/accessibility/components/AccessibilityRowValue.js
@@ -19,35 +19,34 @@ const Rep = createFactory(REPS.Rep);
 
 class AccessibilityRowValue extends Component {
   static get propTypes() {
     return {
       member: PropTypes.shape({
         object: PropTypes.object,
       }).isRequired,
       supports: PropTypes.object.isRequired,
-      walker: PropTypes.object.isRequired,
     };
   }
 
   render() {
-    const { member, supports: { audit }, walker } = this.props;
+    const { member, supports: { audit } } = this.props;
 
     return span({
       role: "presentation",
     },
       Rep({
         ...this.props,
         defaultRep: Grip,
         cropLimit: 50,
       }),
       audit && AuditController({
         accessible: member.object,
       },
-        Badges({ walker })),
+        Badges()),
     );
   }
 }
 
 const mapStateToProps = ({ ui: { supports } }) => {
   return { supports };
 };
 
--- a/devtools/client/accessibility/components/AccessibilityTree.js
+++ b/devtools/client/accessibility/components/AccessibilityTree.js
@@ -17,16 +17,18 @@ const { MODE } = require("devtools/clien
 const { fetchChildren } = require("../actions/accessibles");
 
 const { L10N } = require("../utils/l10n");
 const { isFiltered } = require("../utils/audit");
 const AccessibilityRow = createFactory(require("./AccessibilityRow"));
 const AccessibilityRowValue = createFactory(require("./AccessibilityRowValue"));
 const { Provider } = require("../provider");
 
+const { scrollIntoView } = require("devtools/client/shared/scroll");
+
 /**
  * Renders Accessibility panel tree.
  */
 class AccessibilityTree extends Component {
   static get propTypes() {
     return {
       walker: PropTypes.object,
       dispatch: PropTypes.func.isRequired,
@@ -55,17 +57,26 @@ class AccessibilityTree extends Componen
   componentWillMount() {
     const { walker } = this.props;
     walker.on("reorder", this.onReorder);
     walker.on("name-change", this.onNameChange);
     walker.on("text-change", this.onTextChange);
     return null;
   }
 
-  componentDidUpdate() {
+  componentDidUpdate(prevProps) {
+    // When filtering is toggled, make sure that the selected row remains in
+    // view.
+    if (this.props.filtered !== prevProps.filtered) {
+      const selected = document.querySelector(".treeTable .treeRow.selected");
+      if (selected) {
+        scrollIntoView(selected);
+      }
+    }
+
     window.emit(EVENTS.ACCESSIBILITY_INSPECTOR_UPDATED);
   }
 
   /**
    * Remove accessible walker front event listeners.
    */
   componentWillUnmount() {
     const { walker } = this.props;
@@ -118,22 +129,17 @@ class AccessibilityTree extends Componen
   onTextChange(accessible) {
     const { accessibles, dispatch } = this.props;
     if (accessibles.has(accessible.actorID)) {
       dispatch(fetchChildren(accessible));
     }
   }
 
   renderValue(props) {
-    const { walker } = this.props;
-
-    return AccessibilityRowValue({
-      ...props,
-      walker,
-    });
+    return AccessibilityRowValue(props);
   }
 
   /**
    * Render Accessibility panel content
    */
   render() {
     const columns = [{
       "id": "default",
@@ -186,17 +192,20 @@ class AccessibilityTree extends Componen
         label: L10N.getStr("accessibility.treeName"),
         header: true,
         expandedNodes: expanded,
         selected,
         onClickRow(nodePath, event) {
           if (event.target.classList.contains("theme-twisty")) {
             this.toggle(nodePath);
           }
-          this.selectRow(event.currentTarget);
+
+          this.selectRow(
+            this.rows.find(row => row.props.member.path === nodePath),
+            { preventAutoScroll: true });
         },
         onContextMenuTree: hasContextMenu && function(e) {
           // If context menu event is triggered on (or bubbled to) the TreeView, it was
           // done via keyboard. Open context menu for currently selected row.
           let row = this.getSelectedRow();
           if (!row) {
             return;
           }
--- a/devtools/client/accessibility/components/AccessibilityTreeFilter.js
+++ b/devtools/client/accessibility/components/AccessibilityTreeFilter.js
@@ -74,16 +74,17 @@ class AccessibilityTreeFilter extends Co
         label: L10N.getStr(FILTER_LABELS[filterKey]),
         onClick: this.onClick.bind(this, filterKey),
         onKeyDown: this.onKeyDown.bind(this, filterKey),
         busy: auditing === filterKey,
       }));
 
     return div({
       role: "toolbar",
+      className: "accessibility-tree-filters",
     },
       L10N.getStr("accessibility.tree.filters"),
       ...filterButtons);
   }
 }
 
 const mapStateToProps = ({ audit: { filters, auditing } }) => {
   return { filters, auditing };
--- a/devtools/client/accessibility/components/Badge.js
+++ b/devtools/client/accessibility/components/Badge.js
@@ -1,98 +1,31 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 "use strict";
 
 // React
-const { Component, createFactory } = require("devtools/client/shared/vendor/react");
+const { Component } = require("devtools/client/shared/vendor/react");
+const { span } = require("devtools/client/shared/vendor/react-dom-factories");
 const PropTypes = require("devtools/client/shared/vendor/react-prop-types");
-const { connect } = require("devtools/client/shared/vendor/react-redux");
-
-const ToggleButton = createFactory(require("./Button").ToggleButton);
-
-const { audit, auditing, filterToggle } = require("../actions/audit");
-const { preventDefaultAndStopPropagation } = require("devtools/client/shared/events");
 
 class Badge extends Component {
   static get propTypes() {
     return {
-      active: PropTypes.bool.isRequired,
-      filterKey: PropTypes.string.isRequired,
-      dispatch: PropTypes.func.isRequired,
       label: PropTypes.string.isRequired,
       tooltip: PropTypes.string,
-      walker: PropTypes.object.isRequired,
     };
   }
 
-  constructor(props) {
-    super(props);
-
-    this.toggleFilter = this.toggleFilter.bind(this);
-    this.onClick = this.onClick.bind(this);
-    this.onKeyDown = this.onKeyDown.bind(this);
-  }
-
-  shouldComponentUpdate(nextProps) {
-    return nextProps.active !== this.props.active;
-  }
-
-  async toggleFilter() {
-    const { dispatch, filterKey, walker, active } = this.props;
-    if (!active) {
-      dispatch(auditing(filterKey));
-      await dispatch(audit(walker, filterKey));
-    }
-
-    // We wait to dispatch filter toggle until the tree is ready to be filtered
-    // right after the audit. This is to make sure that we render an empty tree
-    // (filtered) while the audit is running.
-    dispatch(filterToggle(filterKey));
-  }
+  render() {
+    const { label, tooltip } = this.props;
 
-  onClick(e) {
-    preventDefaultAndStopPropagation(e);
-    const { mozInputSource, MOZ_SOURCE_KEYBOARD } = e.nativeEvent;
-    if (e.isTrusted && mozInputSource === MOZ_SOURCE_KEYBOARD) {
-      // Already handled by key down handler on user input.
-      return;
-    }
-
-    this.toggleFilter();
-  }
-
-  onKeyDown(e) {
-    // We explicitely handle "click" and "keydown" events this way here because
-    // there seem to be a difference in the sequence of keyboard/click events
-    // fired when Space/Enter is pressed. When Space is pressed the sequence of
-    // events is keydown->keyup->click but when Enter is pressed the sequence is
-    // keydown->click->keyup. This results in an unwanted badge click (when
-    // pressing Space) within the accessibility tree row when activating it
-    // because it gets focused before the click event is dispatched.
-    if (![" ", "Enter"].includes(e.key)) {
-      return;
-    }
-
-    preventDefaultAndStopPropagation(e);
-    this.toggleFilter();
-  }
-
-  render() {
-    const { active, label, tooltip } = this.props;
-
-    return ToggleButton({
+    return span({
       className: "audit-badge badge",
-      label,
-      active,
-      tooltip,
-      onClick: this.onClick,
-      onKeyDown: this.onKeyDown,
-    });
+      title: tooltip,
+      "aria-label": label,
+    },
+      label);
   }
 }
 
-const mapStateToProps = ({ audit: { filters } }, { filterKey }) => ({
-  active: filters[filterKey],
-});
-
-module.exports = connect(mapStateToProps)(Badge);
+module.exports = Badge;
--- a/devtools/client/accessibility/components/Badges.js
+++ b/devtools/client/accessibility/components/Badges.js
@@ -22,34 +22,30 @@ function getComponentForAuditType(type) 
 
   return auditTypeToComponentMap[type];
 }
 
 class Badges extends Component {
   static get propTypes() {
     return {
       checks: PropTypes.object,
-      walker: PropTypes.object.isRequired,
     };
   }
 
   render() {
-    const { checks, walker } = this.props;
+    const { checks } = this.props;
     if (!checks) {
       return null;
     }
 
     const items = [];
     for (const type in checks) {
       const component = getComponentForAuditType(type);
       if (checks[type] && component) {
-        items.push(component({
-          ...checks[type],
-          walker,
-        }));
+        items.push(component(checks[type]));
       }
     }
 
     if (items.length === 0) {
       return null;
     }
 
     return (
--- a/devtools/client/accessibility/components/ContrastBadge.js
+++ b/devtools/client/accessibility/components/ContrastBadge.js
@@ -8,45 +8,39 @@ const { Component, createFactory } = req
 const PropTypes = require("devtools/client/shared/vendor/react-prop-types");
 
 const { L10N } = require("../utils/l10n");
 
 const { accessibility: { SCORES } } = require("devtools/shared/constants");
 
 loader.lazyGetter(this, "Badge", () => createFactory(require("./Badge")));
 
-const { FILTERS } = require("../constants");
-
 /**
 * Component for rendering a badge for contrast accessibliity check
 * failures association with a given accessibility object in the accessibility
 * tree.
 */
-
 class ContrastBadge extends Component {
   static get propTypes() {
     return {
       error: PropTypes.string,
       score: PropTypes.string,
-      walker: PropTypes.object.isRequired,
     };
   }
 
   render() {
-    const { error, score, walker } = this.props;
+    const { error, score } = this.props;
     if (error) {
       return null;
     }
 
     if (score !== SCORES.FAIL) {
       return null;
     }
 
     return Badge({
       label: L10N.getStr("accessibility.badge.contrast"),
       tooltip: L10N.getStr("accessibility.badge.contrast.tooltip"),
-      filterKey: FILTERS.CONTRAST,
-      walker,
     });
   }
 }
 
 module.exports = ContrastBadge;
--- a/devtools/client/accessibility/test/browser/browser.ini
+++ b/devtools/client/accessibility/test/browser/browser.ini
@@ -19,14 +19,15 @@ skip-if = (os == 'win' && processor == '
 skip-if = (os == 'win' && processor == 'aarch64') # bug 1533534
 [browser_accessibility_panel_highlighter.js]
 [browser_accessibility_panel_highlighter_multi_tab.js]
 skip-if = (os == 'linux' && debug && bits == 64) # Bug 1511247
 [browser_accessibility_relation_navigation.js]
 [browser_accessibility_reload.js]
 [browser_accessibility_sidebar_checks.js]
 [browser_accessibility_sidebar.js]
+[browser_accessibility_tree_audit_long.js]
 [browser_accessibility_tree_audit_reset.js]
 [browser_accessibility_tree_audit_toolbar.js]
 [browser_accessibility_tree_audit.js]
 [browser_accessibility_tree_contrast.js]
 [browser_accessibility_tree_nagivation.js]
 [browser_accessibility_tree.js]
--- a/devtools/client/accessibility/test/browser/browser_accessibility_tree_audit.js
+++ b/devtools/client/accessibility/test/browser/browser_accessibility_tree_audit.js
@@ -1,14 +1,14 @@
 /* Any copyright is dedicated to the Public Domain.
  * http://creativecommons.org/publicdomain/zero/1.0/ */
 
 "use strict";
 
-/* global toggleRow, toggleBadge */
+/* global toggleRow, toggleFilter */
 
 const TEST_URI = `<html>
   <head>
     <meta charset="utf-8"/>
     <title>Accessibility Panel Test</title>
   </head>
   <body>
     <h1 style="color:rgba(255,0,0,0.1); background-color:rgba(255,255,255,1);">
@@ -47,35 +47,36 @@ const tests = [{
       name: `"Top level header "contrast`,
       badges: [ "contrast" ],
     }, {
       role: "heading",
       name: `"Second level header"`,
     }],
   },
 }, {
-  desc: "Click on the badge.",
+  desc: "Click on the contrast filter.",
   setup: async ({ doc }) => {
-    await toggleBadge(doc, 2, 0);
+    await toggleFilter(doc, 0);
   },
   expected: {
     tree: [{
       role: "text leaf",
       name: `"Top level header "contrast`,
       badges: [ "contrast" ],
     }, {
       role: "text leaf",
       name: `"Second level header "contrast`,
       badges: [ "contrast" ],
+      selected: true,
     }],
   },
 }, {
-  desc: "Click on the badge again.",
+  desc: "Click on the contrast filter again.",
   setup: async ({ doc }) => {
-    await toggleBadge(doc, 0, 0);
+    await toggleFilter(doc, 0);
   },
   expected: {
     tree: [{
       role: "document",
       name: `"Accessibility Panel Test"`,
     }, {
       role: "heading",
       name: `"Top level header"`,
@@ -85,18 +86,20 @@ const tests = [{
       badges: [ "contrast" ],
     }, {
       role: "heading",
       name: `"Second level header"`,
     }, {
       role: "text leaf",
       name: `"Second level header "contrast`,
       badges: [ "contrast" ],
+      selected: true,
     }],
   },
 }];
 
 /**
  * Simple test that checks content of the Accessibility panel tree when one of
- * the tree rows has a "contrast" badge and auditing is activated via badge.
+ * the tree rows has a "contrast" badge and auditing is activated via toolbar
+ * filter.
  */
 addA11yPanelTestsTask(tests, TEST_URI,
-  "Test Accessibility panel tree with contrast badge audit activation.");
+  "Test Accessibility panel tree with contrast badge present.");
new file mode 100644
--- /dev/null
+++ b/devtools/client/accessibility/test/browser/browser_accessibility_tree_audit_long.js
@@ -0,0 +1,95 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/* global toggleFilter */
+
+const header = "<h1 style=\"color:rgba(255,0,0,0.1); " +
+               "background-color:rgba(255,255,255,1);\">header</h1>";
+
+const TEST_URI = `<html>
+  <head>
+    <meta charset="utf-8"/>
+    <title>Accessibility Panel Test</title>
+  </head>
+  <body>
+    ${header.repeat(20)}
+  </body>
+</html>`;
+
+const docRow = {
+  role: "document",
+  name: `"Accessibility Panel Test"`,
+};
+const headingRow = {
+  role: "heading",
+  name: `"header"`,
+};
+const textLeafRow = {
+  role: "text leaf",
+  name: `"header"contrast`,
+  badges: [ "contrast" ],
+};
+const audit = new Array(20).fill(textLeafRow);
+
+const auditInitial = audit.map(check => ({ ...check }));
+auditInitial[0].selected = true;
+
+const auditSecondLastSelected = audit.map(check => ({ ...check }));
+auditSecondLastSelected[19].selected = true;
+
+const resetAfterAudit = [docRow];
+for (let i = 0; i < 20; i++) {
+  resetAfterAudit.push(headingRow);
+  resetAfterAudit.push({ ...textLeafRow, selected: i === 19 });
+}
+
+/**
+* Test data has the format of:
+* {
+*   desc     {String}    description for better logging
+*   setup    {Function}  An optional setup that needs to be performed before
+*                        the state of the tree and the sidebar can be checked.
+*   expected {JSON}      An expected states for the tree and the sidebar.
+* }
+*/
+const tests = [{
+  desc: "Check initial state.",
+  expected: {
+    tree: [{ ...docRow, selected: true }],
+  },
+}, {
+  desc: "Run an audit from a11y panel toolbar by activating a filter.",
+  setup: async ({ doc }) => {
+    await toggleFilter(doc, 0);
+  },
+  expected: {
+    tree: auditInitial,
+  },
+}, {
+  desc: "Select a row that is guaranteed to have to be scrolled into view.",
+  setup: async ({ doc }) => {
+    selectRow(doc, 0);
+    EventUtils.synthesizeKey("VK_END", {}, doc.defaultView);
+  },
+  expected: {
+    tree: auditSecondLastSelected,
+  },
+}, {
+  desc: "Click on the filter again.",
+  setup: async ({ doc }) => {
+    await toggleFilter(doc, 0);
+  },
+  expected: {
+    tree: resetAfterAudit,
+  },
+}];
+
+/**
+* Simple test that checks content of the Accessibility panel tree when the
+* audit is activated via the panel's toolbar and the selection persists when
+* the filter is toggled off.
+*/
+addA11yPanelTestsTask(tests, TEST_URI,
+  "Test Accessibility panel tree with persistent selected row.");
--- a/devtools/client/accessibility/test/browser/browser_accessibility_tree_audit_reset.js
+++ b/devtools/client/accessibility/test/browser/browser_accessibility_tree_audit_reset.js
@@ -30,43 +30,46 @@ const TEST_URI = `<html>
 * }
 */
 const tests = [{
   desc: "Check initial state.",
   expected: {
     tree: [{
       role: "document",
       name: `"Accessibility Panel Test"`,
+      selected: true,
     }],
   },
 }, {
   desc: "Run an audit from a11y panel toolbar by activating a filter.",
   setup: async ({ doc }) => {
     await toggleFilter(doc, 0);
   },
   expected: {
     tree: [{
       role: "text leaf",
       name: `"Top level header "contrast`,
       badges: [ "contrast" ],
+      selected: true,
     }, {
       role: "text leaf",
       name: `"Second level header "contrast`,
       badges: [ "contrast" ],
     }],
   },
 }, {
   desc: "Select an accessible object.",
   setup: async (env) => {
     await selectAccessibleForNode(env, "body");
   },
   expected: {
     tree: [{
       role: "document",
       name: `"Accessibility Panel Test"`,
+      selected: true,
     }, {
       role: "heading",
       name: `"Top level header"`,
     }, {
       role: "text leaf",
       name: `"Top level header "contrast`,
       badges: [ "contrast" ],
     }, {
--- a/devtools/client/accessibility/test/browser/browser_accessibility_tree_audit_toolbar.js
+++ b/devtools/client/accessibility/test/browser/browser_accessibility_tree_audit_toolbar.js
@@ -1,14 +1,14 @@
 /* Any copyright is dedicated to the Public Domain.
  * http://creativecommons.org/publicdomain/zero/1.0/ */
 
 "use strict";
 
-/* global toggleRow, toggleBadge, toggleFilter */
+/* global toggleRow, toggleFilter */
 
 const TEST_URI = `<html>
   <head>
     <meta charset="utf-8"/>
     <title>Accessibility Panel Test</title>
   </head>
   <body>
     <h1 style="color:rgba(255,0,0,0.1); background-color:rgba(255,255,255,1);">
@@ -30,50 +30,53 @@ const TEST_URI = `<html>
  * }
  */
 const tests = [{
   desc: "Check initial state.",
   expected: {
     tree: [{
       role: "document",
       name: `"Accessibility Panel Test"`,
+      selected: true,
     }],
   },
 }, {
   desc: "Run an audit from a11y panel toolbar by activating a filter.",
   setup: async ({ doc }) => {
     await toggleFilter(doc, 0);
   },
   expected: {
     tree: [{
       role: "text leaf",
       name: `"Top level header "contrast`,
       badges: [ "contrast" ],
+      selected: true,
     }, {
       role: "text leaf",
       name: `"Second level header "contrast`,
       badges: [ "contrast" ],
     }],
   },
 }, {
   desc: "Click on the filter again.",
   setup: async ({ doc }) => {
-    await toggleBadge(doc, 0, 0);
+    await toggleFilter(doc, 0);
   },
   expected: {
     tree: [{
       role: "document",
       name: `"Accessibility Panel Test"`,
     }, {
       role: "heading",
       name: `"Top level header"`,
     }, {
       role: "text leaf",
       name: `"Top level header "contrast`,
       badges: [ "contrast" ],
+      selected: true,
     }, {
       role: "heading",
       name: `"Second level header"`,
     }, {
       role: "text leaf",
       name: `"Second level header "contrast`,
       badges: [ "contrast" ],
     }],
--- a/devtools/client/accessibility/test/browser/head.js
+++ b/devtools/client/accessibility/test/browser/head.js
@@ -1,17 +1,17 @@
 /* Any copyright is dedicated to the Public Domain.
  http://creativecommons.org/publicdomain/zero/1.0/ */
 
 /* import-globals-from ../../../shared/test/shared-head.js */
 /* import-globals-from ../../../inspector/test/shared-head.js */
 
 /* global waitUntilState, gBrowser */
 /* exported addTestTab, checkTreeState, checkSidebarState, checkAuditState, selectRow,
-            toggleRow, toggleBadge, toggleFilter, addA11yPanelTestsTask, reload,
+            toggleRow, toggleFilter, addA11yPanelTestsTask, reload,
             navigate */
 
 "use strict";
 
 // Import framework's shared head.
 Services.scriptloader.loadSubScript(
   "chrome://mochitests/content/browser/devtools/client/shared/test/shared-head.js",
   this);
@@ -172,28 +172,90 @@ async function initAccessibilityPanel(ta
  */
 function compareBadges(badges, expected = []) {
   const badgeEls = badges ? [...badges.querySelectorAll(".badge")] : [];
   return badgeEls.length === expected.length &&
          badgeEls.every((badge, i) => badge.textContent === expected[i]);
 }
 
 /**
+ * Find an ancestor that is scrolled for a given DOMNode.
+ *
+ * @param {DOMNode} node
+ *        DOMNode that to find an ancestor for that is scrolled.
+ */
+function closestScrolledParent(node) {
+  if (node == null) {
+    return null;
+  }
+
+  if (node.scrollHeight > node.clientHeight) {
+    return node;
+  }
+
+  return closestScrolledParent(node.parentNode);
+}
+
+/**
+ * Check if a given element is visible to the user and is not scrolled off
+ * because of the overflow.
+ *
+ * @param   {Element} element
+ *          Element to be checked whether it is visible and is not scrolled off.
+ *
+ * @returns {Boolean}
+ *          True if the element is visible.
+ */
+function isVisible(element) {
+  const { top, bottom } = element.getBoundingClientRect();
+  const scrolledParent = closestScrolledParent(element.parentNode);
+  const scrolledParentRect = scrolledParent ? scrolledParent.getBoundingClientRect() :
+                                              null;
+  return !scrolledParent ||
+         (top >= scrolledParentRect.top && bottom <= scrolledParentRect.bottom);
+}
+
+/**
+ * Check selected styling and visibility for a given row in the accessibility
+ * tree.
+ * @param   {DOMNode} row
+ *          DOMNode for a given accessibility row.
+ * @param   {Boolean} expected
+ *          Expected selected state.
+ *
+ * @returns {Boolean}
+ *          True if visibility and styling matches expected selected state.
+ */
+function checkSelected(row, expected) {
+  if (!expected) {
+    return true;
+  }
+
+  if (row.classList.contains("selected") !== expected) {
+    return false;
+  }
+
+  return isVisible(row);
+}
+
+/**
  * Check the state of the accessibility tree.
  * @param  {document} doc       panel documnent.
  * @param  {Array}    expected  an array that represents an expected row list.
  */
 async function checkTreeState(doc, expected) {
   info("Checking tree state.");
   const hasExpectedStructure = await BrowserTestUtils.waitForCondition(() =>
-    [...doc.querySelectorAll(".treeRow")].every((row, i) =>
-      row.querySelector(".treeLabelCell").textContent === expected[i].role &&
-      row.querySelector(".treeValueCell").textContent === expected[i].name &&
-      compareBadges(row.querySelector(".badges"), expected[i].badges)),
-    "Wait for the right tree update.");
+    [...doc.querySelectorAll(".treeRow")].every((row, i) => {
+      const { role, name, badges, selected } = expected[i];
+      return row.querySelector(".treeLabelCell").textContent === role &&
+        row.querySelector(".treeValueCell").textContent === name &&
+        compareBadges(row.querySelector(".badges"), badges) &&
+        checkSelected(row, selected);
+    }), "Wait for the right tree update.");
 
   ok(hasExpectedStructure, "Tree structure is correct.");
 }
 
 /**
  * Check if relations object matches what is expected. Note: targets are matched by their
  * name and role.
  * @param  {Object} relations  Relations to test.
@@ -373,32 +435,16 @@ async function toggleRow(doc, rowNumber)
 
   EventUtils.sendMouseEvent({ type: "click" }, twisty, win);
   await BrowserTestUtils.waitForCondition(() =>
     !twisty.classList.contains("devtools-throbber") &&
     expected === twisty.classList.contains("open"), "Twisty updated.");
 }
 
 /**
- * Toggle an accessibility audit badge based on its index in the badges group.
- * @param  {document} doc        panel documnent.
- * @param  {Number}   badgeIndex index of the badge to be toggled.
- */
-async function toggleBadge(doc, rowNumber, badgeIndex) {
-  const win = doc.defaultView;
-  const row = doc.querySelectorAll(".treeRow")[rowNumber];
-  const badge = row.querySelectorAll(".audit-badge.badge")[badgeIndex];
-  const expected = !badge.classList.contains("checked");
-
-  EventUtils.synthesizeMouseAtCenter(badge, {}, win);
-  await BrowserTestUtils.waitForCondition(() =>
-    expected === badge.classList.contains("checked"), "Badge updated.");
-}
-
-/**
  * Toggle an accessibility audit filter based on its index in the toolbar.
  * @param  {document} doc         panel documnent.
  * @param  {Number}   filterIndex index of the filter to be toggled.
  */
 async function toggleFilter(doc, filterIndex) {
   const win = doc.defaultView;
   const filter = doc.querySelectorAll(
     ".devtools-toolbar .badge.toggle-button")[filterIndex];
--- a/devtools/client/accessibility/test/jest/components/__snapshots__/accessibility-tree-filter.test.js.snap
+++ b/devtools/client/accessibility/test/jest/components/__snapshots__/accessibility-tree-filter.test.js.snap
@@ -1,11 +1,11 @@
 // Jest Snapshot v1, https://goo.gl/fbAQLP
 
-exports[`AccessibilityTreeFilter component: audit filter filtered 1`] = `"<div role=\\"toolbar\\">accessibility.tree.filters<button aria-pressed=\\"true\\" aria-busy=\\"false\\" class=\\"audit-badge badge toggle-button checked\\">accessibility.badge.contrast</button></div>"`;
+exports[`AccessibilityTreeFilter component: audit filter filtered 1`] = `"<div role=\\"toolbar\\" class=\\"accessibility-tree-filters\\">accessibility.tree.filters<button aria-pressed=\\"true\\" aria-busy=\\"false\\" class=\\"audit-badge badge toggle-button checked\\">accessibility.badge.contrast</button></div>"`;
 
-exports[`AccessibilityTreeFilter component: audit filter filtered auditing 1`] = `"<div role=\\"toolbar\\">accessibility.tree.filters<button aria-pressed=\\"true\\" aria-busy=\\"true\\" class=\\"audit-badge badge toggle-button checked devtools-throbber\\">accessibility.badge.contrast</button></div>"`;
+exports[`AccessibilityTreeFilter component: audit filter filtered auditing 1`] = `"<div role=\\"toolbar\\" class=\\"accessibility-tree-filters\\">accessibility.tree.filters<button aria-pressed=\\"true\\" aria-busy=\\"true\\" class=\\"audit-badge badge toggle-button checked devtools-throbber\\">accessibility.badge.contrast</button></div>"`;
 
-exports[`AccessibilityTreeFilter component: audit filter not filtered 1`] = `"<div role=\\"toolbar\\">accessibility.tree.filters<button aria-pressed=\\"false\\" aria-busy=\\"false\\" class=\\"audit-badge badge toggle-button\\">accessibility.badge.contrast</button></div>"`;
+exports[`AccessibilityTreeFilter component: audit filter not filtered 1`] = `"<div role=\\"toolbar\\" class=\\"accessibility-tree-filters\\">accessibility.tree.filters<button aria-pressed=\\"false\\" aria-busy=\\"false\\" class=\\"audit-badge badge toggle-button\\">accessibility.badge.contrast</button></div>"`;
 
-exports[`AccessibilityTreeFilter component: audit filter not filtered auditing 1`] = `"<div role=\\"toolbar\\">accessibility.tree.filters<button aria-pressed=\\"false\\" aria-busy=\\"true\\" class=\\"audit-badge badge toggle-button devtools-throbber\\">accessibility.badge.contrast</button></div>"`;
+exports[`AccessibilityTreeFilter component: audit filter not filtered auditing 1`] = `"<div role=\\"toolbar\\" class=\\"accessibility-tree-filters\\">accessibility.tree.filters<button aria-pressed=\\"false\\" aria-busy=\\"true\\" class=\\"audit-badge badge toggle-button devtools-throbber\\">accessibility.badge.contrast</button></div>"`;
 
-exports[`AccessibilityTreeFilter component: toggle filter 1`] = `"<div role=\\"toolbar\\">accessibility.tree.filters<button aria-pressed=\\"false\\" aria-busy=\\"false\\" class=\\"audit-badge badge toggle-button\\">accessibility.badge.contrast</button></div>"`;
+exports[`AccessibilityTreeFilter component: toggle filter 1`] = `"<div role=\\"toolbar\\" class=\\"accessibility-tree-filters\\">accessibility.tree.filters<button aria-pressed=\\"false\\" aria-busy=\\"false\\" class=\\"audit-badge badge toggle-button\\">accessibility.badge.contrast</button></div>"`;
--- a/devtools/client/accessibility/test/jest/components/__snapshots__/badge.test.js.snap
+++ b/devtools/client/accessibility/test/jest/components/__snapshots__/badge.test.js.snap
@@ -1,7 +1,3 @@
 // Jest Snapshot v1, https://goo.gl/fbAQLP
 
-exports[`Badge component: basic render active 1`] = `"<button aria-pressed=\\"true\\" class=\\"audit-badge badge toggle-button checked\\">Contrast</button>"`;
-
-exports[`Badge component: basic render inactive 1`] = `"<button aria-pressed=\\"false\\" class=\\"audit-badge badge toggle-button\\">Contrast</button>"`;
-
-exports[`Badge component: toggle filter 1`] = `"<button aria-pressed=\\"false\\" class=\\"audit-badge badge toggle-button\\">Contrast</button>"`;
+exports[`Badge component: basic render 1`] = `"<span class=\\"audit-badge badge\\" title=\\"Does not meet WCAG standards for accessible text.\\" aria-label=\\"Contrast\\">Contrast</span>"`;
--- a/devtools/client/accessibility/test/jest/components/__snapshots__/badges.test.js.snap
+++ b/devtools/client/accessibility/test/jest/components/__snapshots__/badges.test.js.snap
@@ -1,13 +1,13 @@
 // Jest Snapshot v1, https://goo.gl/fbAQLP
 
-exports[`Badges component: contrast ratio fail range render 1`] = `"<span class=\\"badges\\" role=\\"group\\" aria-label=\\"accessibility.badges\\"><button aria-pressed=\\"false\\" class=\\"audit-badge badge toggle-button\\" title=\\"accessibility.badge.contrast.tooltip\\">accessibility.badge.contrast</button></span>"`;
+exports[`Badges component: contrast ratio fail range render 1`] = `"<span class=\\"badges\\" role=\\"group\\" aria-label=\\"accessibility.badges\\"><span class=\\"audit-badge badge\\" title=\\"accessibility.badge.contrast.tooltip\\" aria-label=\\"accessibility.badge.contrast\\">accessibility.badge.contrast</span></span>"`;
 
-exports[`Badges component: contrast ratio fail render 1`] = `"<span class=\\"badges\\" role=\\"group\\" aria-label=\\"accessibility.badges\\"><button aria-pressed=\\"false\\" class=\\"audit-badge badge toggle-button\\" title=\\"accessibility.badge.contrast.tooltip\\">accessibility.badge.contrast</button></span>"`;
+exports[`Badges component: contrast ratio fail render 1`] = `"<span class=\\"badges\\" role=\\"group\\" aria-label=\\"accessibility.badges\\"><span class=\\"audit-badge badge\\" title=\\"accessibility.badge.contrast.tooltip\\" aria-label=\\"accessibility.badge.contrast\\">accessibility.badge.contrast</span></span>"`;
 
 exports[`Badges component: contrast ratio success render 1`] = `"<span class=\\"badges\\" role=\\"group\\" aria-label=\\"accessibility.badges\\"></span>"`;
 
 exports[`Badges component: empty checks render 1`] = `null`;
 
 exports[`Badges component: no props render 1`] = `null`;
 
 exports[`Badges component: null checks render 1`] = `null`;
--- a/devtools/client/accessibility/test/jest/components/__snapshots__/contrast-badge.test.js.snap
+++ b/devtools/client/accessibility/test/jest/components/__snapshots__/contrast-badge.test.js.snap
@@ -1,11 +1,11 @@
 // Jest Snapshot v1, https://goo.gl/fbAQLP
 
 exports[`ContrastBadge component: error render 1`] = `null`;
 
-exports[`ContrastBadge component: fail render 1`] = `"<button aria-pressed=\\"false\\" class=\\"audit-badge badge toggle-button\\" title=\\"accessibility.badge.contrast.tooltip\\">accessibility.badge.contrast</button>"`;
+exports[`ContrastBadge component: fail render 1`] = `"<span class=\\"audit-badge badge\\" title=\\"accessibility.badge.contrast.tooltip\\" aria-label=\\"accessibility.badge.contrast\\">accessibility.badge.contrast</span>"`;
 
 exports[`ContrastBadge component: success large text render 1`] = `null`;
 
 exports[`ContrastBadge component: success range render 1`] = `null`;
 
 exports[`ContrastBadge component: success render 1`] = `null`;
--- a/devtools/client/accessibility/test/jest/components/badge.test.js
+++ b/devtools/client/accessibility/test/jest/components/badge.test.js
@@ -4,73 +4,31 @@
 "use strict";
 
 const { mount } = require("enzyme");
 
 const { createFactory } = require("devtools/client/shared/vendor/react");
 const Provider = createFactory(require("devtools/client/shared/vendor/react-redux").Provider);
 const { setupStore } = require("devtools/client/accessibility/test/jest/helpers");
 
-const { ToggleButton } = require("devtools/client/accessibility/components/Button");
-const ConnectedBadgeClass = require("devtools/client/accessibility/components/Badge");
-const BadgeClass = ConnectedBadgeClass.WrappedComponent;
-const Badge = createFactory(ConnectedBadgeClass);
-
-const { FILTERS } = require("devtools/client/accessibility/constants");
+const BadgeClass = require("devtools/client/accessibility/components/Badge");
+const Badge = createFactory(BadgeClass);
 
 describe("Badge component:", () => {
-  const props = {
-    label: "Contrast",
-    filterKey: FILTERS.CONTRAST,
-  };
+  const label = "Contrast";
+  const tooltip = "Does not meet WCAG standards for accessible text.";
+  const props = { label, tooltip };
 
-  it("basic render inactive", () => {
+  it("basic render", () => {
     const store = setupStore();
     const wrapper = mount(Provider({ store }, Badge(props)));
     expect(wrapper.html()).toMatchSnapshot();
 
     const badge = wrapper.find(BadgeClass);
-    expect(badge.prop("active")).toBe(false);
     expect(badge.children().length).toBe(1);
-
-    const toggleButton = badge.childAt(0);
-    expect(toggleButton.type()).toBe(ToggleButton);
-    expect(toggleButton.children().length).toBe(1);
-
-    const button = toggleButton.childAt(0);
-    expect(button.is("button")).toBe(true);
-    expect(button.hasClass("audit-badge")).toBe(true);
-    expect(button.hasClass("badge")).toBe(true);
-    expect(button.hasClass("toggle-button")).toBe(true);
-    expect(button.prop("aria-pressed")).toBe(false);
-    expect(button.text()).toBe("Contrast");
-  });
+    expect(badge.find(`span[aria-label="${label}"][title="${tooltip}"]`)).toHaveLength(1);
 
-  it("basic render active", () => {
-    const store = setupStore({
-      preloadedState: { audit: { filters: { [FILTERS.CONTRAST]: true }}},
-    });
-    const wrapper = mount(Provider({ store }, Badge(props)));
-    expect(wrapper.html()).toMatchSnapshot();
-    const badge = wrapper.find(BadgeClass);
-    expect(badge.prop("active")).toBe(true);
-
-    const button = wrapper.find("button");
-    expect(button.prop("aria-pressed")).toBe(true);
-  });
-
-  it("toggle filter", () => {
-    const store = setupStore();
-    const wrapper = mount(Provider({ store }, Badge(props)));
-    expect(wrapper.html()).toMatchSnapshot();
-
-    const badgeInstance = wrapper.find(BadgeClass).instance();
-    badgeInstance.toggleFilter = jest.fn();
-    wrapper.find("button.audit-badge.badge").simulate("keydown", { key: " " });
-    expect(badgeInstance.toggleFilter.mock.calls.length).toBe(1);
-
-    wrapper.find("button.audit-badge.badge").simulate("keydown", { key: "Enter" });
-    expect(badgeInstance.toggleFilter.mock.calls.length).toBe(2);
-
-    wrapper.find("button.audit-badge.badge").simulate("click");
-    expect(badgeInstance.toggleFilter.mock.calls.length).toBe(3);
+    const badgeText = badge.childAt(0);
+    expect(badgeText.hasClass("audit-badge")).toBe(true);
+    expect(badgeText.hasClass("badge")).toBe(true);
+    expect(badgeText.text()).toBe(label);
   });
 });
--- a/devtools/client/accessibility/test/jest/components/contrast-badge.test.js
+++ b/devtools/client/accessibility/test/jest/components/contrast-badge.test.js
@@ -9,17 +9,16 @@ const { shallow, mount } = require("enzy
 const { createFactory } = require("devtools/client/shared/vendor/react");
 
 const Provider = createFactory(require("devtools/client/shared/vendor/react-redux").Provider);
 const { setupStore } = require("devtools/client/accessibility/test/jest/helpers");
 
 const Badge = require("devtools/client/accessibility/components/Badge");
 const ContrastBadgeClass = require("devtools/client/accessibility/components/ContrastBadge");
 const ContrastBadge = createFactory(ContrastBadgeClass);
-const { FILTERS } = require("devtools/client/accessibility/constants");
 
 describe("ContrastBadge component:", () => {
   const store = setupStore();
 
   it("error render", () => {
     const wrapper = shallow(ContrastBadge({ error: true }));
     expect(wrapper.html()).toMatchSnapshot();
     expect(wrapper.isEmptyRender()).toBe(true);
@@ -65,12 +64,12 @@ describe("ContrastBadge component:", () 
 
     expect(wrapper.html()).toMatchSnapshot();
     expect(wrapper.children().length).toBe(1);
     const contrastBadge = wrapper.find(ContrastBadgeClass);
     const badge = contrastBadge.childAt(0);
     expect(badge.type()).toBe(Badge);
     expect(badge.props()).toMatchObject({
       label: "accessibility.badge.contrast",
-      filterKey: FILTERS.CONTRAST,
+      tooltip: "accessibility.badge.contrast.tooltip",
     });
   });
 });
--- a/devtools/client/jsonview/test/browser_jsonview_row_selection.js
+++ b/devtools/client/jsonview/test/browser_jsonview_row_selection.js
@@ -10,24 +10,34 @@ add_task(async function() {
 
   // Create a tall JSON so that there is a scrollbar.
   const numRows = 1e3;
   const json = JSON.stringify(Array(numRows).fill().map((_, i) => i));
   const tab = await addJsonViewTab("data:application/json," + json);
 
   is(await getElementCount(".treeRow"), numRows, "Got the expected number of rows.");
   await assertRowSelected(null);
+
+  // Focus the tree and select first row.
+  await ContentTask.spawn(gBrowser.selectedBrowser, null, function() {
+    const tree = content.document.querySelector(".treeTable");
+    tree.focus();
+    is(tree, content.document.activeElement, "Tree should be focused");
+    content.document.querySelector(".treeRow:nth-child(1)").click();
+  });
+  await assertRowSelected(1);
+
   await ContentTask.spawn(gBrowser.selectedBrowser, null, function() {
     const scroller = content.document.querySelector(".jsonPanelBox .panelContent");
     ok(scroller.clientHeight < scroller.scrollHeight, "There is a scrollbar.");
     is(scroller.scrollTop, 0, "Initially scrolled to the top.");
+  });
 
-    // Click to select last row.
-    content.document.querySelector(".treeRow:last-child").click();
-  });
+  // Select last row.
+  await BrowserTestUtils.synthesizeKey("VK_END", {}, tab.linkedBrowser);
   await assertRowSelected(numRows);
 
   await ContentTask.spawn(gBrowser.selectedBrowser, null, function() {
     const scroller = content.document.querySelector(".jsonPanelBox .panelContent");
     is(scroller.scrollTop + scroller.clientHeight, scroller.scrollHeight,
        "Scrolled to the bottom.");
     // Click to select 2nd row.
     content.document.querySelector(".treeRow:nth-child(2)").click();
@@ -72,71 +82,69 @@ add_task(async function() {
   await assertRowSelected(numRows - 1);
 });
 
 add_task(async function() {
   info("Test 3 JSON row selection started");
 
   // Create a JSON with a row taller than the panel.
   const json = JSON.stringify([0, "a ".repeat(1e4), 1]);
-  await addJsonViewTab("data:application/json," + encodeURI(json));
+  const tab = await addJsonViewTab("data:application/json," + encodeURI(json));
 
   is(await getElementCount(".treeRow"), 3, "Got the expected number of rows.");
   await assertRowSelected(null);
   await ContentTask.spawn(gBrowser.selectedBrowser, null, function() {
     const scroller = content.document.querySelector(".jsonPanelBox .panelContent");
     const row = content.document.querySelector(".treeRow:nth-child(2)");
     ok(scroller.clientHeight < row.clientHeight, "The row is taller than the scroller.");
     is(scroller.scrollTop, 0, "Initially scrolled to the top.");
 
     // Select the tall row.
+    content.document.querySelector(".treeTable").focus();
     row.click();
   });
   await assertRowSelected(2);
   await ContentTask.spawn(gBrowser.selectedBrowser, null, function() {
     const scroller = content.document.querySelector(".jsonPanelBox .panelContent");
-    const row = content.document.querySelector(".treeRow:nth-child(2)");
-    is(scroller.scrollTop, row.offsetTop,
-       "Scrolled to the top of the row.");
+    is(scroller.scrollTop, 0, "When the row is visible, do not scroll on click.");
   });
 
   // Select the last row.
-  await ContentTask.spawn(gBrowser.selectedBrowser, null, function() {
-    content.document.querySelector(".treeRow:last-child").click();
-  });
+  await BrowserTestUtils.synthesizeKey("VK_DOWN", {}, tab.linkedBrowser);
   await assertRowSelected(3);
   await ContentTask.spawn(gBrowser.selectedBrowser, null, function() {
     const scroller = content.document.querySelector(".jsonPanelBox .panelContent");
     is(scroller.scrollTop + scroller.offsetHeight,
        scroller.scrollHeight, "Scrolled to the bottom.");
 
     // Select the tall row.
     const row = content.document.querySelector(".treeRow:nth-child(2)");
     row.click();
   });
 
   await assertRowSelected(2);
   const scroll = await ContentTask.spawn(gBrowser.selectedBrowser, null, function() {
     const scroller = content.document.querySelector(".jsonPanelBox .panelContent");
     const row = content.document.querySelector(".treeRow:nth-child(2)");
-    is(scroller.scrollTop + scroller.offsetHeight, row.offsetTop + row.offsetHeight,
-       "Scrolled to the bottom of the row.");
+    is(scroller.scrollTop + scroller.offsetHeight, scroller.scrollHeight,
+      "Scrolled to the bottom. When the row is visible, do not scroll on click.");
 
     // Scroll up a bit, so that both the top and bottom of the row are not visible.
     const scrollPos =
       scroller.scrollTop = Math.ceil((scroller.scrollTop + row.offsetTop) / 2);
     ok(scroller.scrollTop > row.offsetTop,
        "The top of the row is not visible.");
     ok(scroller.scrollTop + scroller.offsetHeight < row.offsetTop + row.offsetHeight,
        "The bottom of the row is not visible.");
 
     // Select the tall row.
     row.click();
     return scrollPos;
   });
+
   await assertRowSelected(2);
   await ContentTask.spawn(gBrowser.selectedBrowser, scroll, function(scrollPos) {
     const scroller = content.document.querySelector(".jsonPanelBox .panelContent");
     is(scroller.scrollTop, scrollPos, "Scroll did not change");
   });
 });
 
 async function assertRowSelected(rowNum) {
--- a/devtools/client/shared/components/splitter/SplitBox.js
+++ b/devtools/client/shared/components/splitter/SplitBox.js
@@ -198,17 +198,23 @@ class SplitBox extends Component {
   }
 
   // Rendering
 
   render() {
     const { endPanelControl, splitterSize, vert } = this.state;
     const { startPanel, endPanel, minSize, maxSize } = this.props;
 
-    const style = Object.assign({}, this.props.style);
+    const style = Object.assign({
+      // Set the size of the controlled panel (height or width depending on the
+      // current state). This can be used to help with styling of dependent
+      // panels.
+      "--split-box-controlled-panel-size":
+        `${vert ? this.state.width : this.state.height}`,
+    }, this.props.style);
 
     // Calculate class names list.
     let classNames = ["split-box"];
     classNames.push(vert ? "vert" : "horz");
     if (this.props.className) {
       classNames = classNames.concat(this.props.className.split(" "));
     }
 
--- a/devtools/client/shared/components/tree/TreeRow.js
+++ b/devtools/client/shared/components/tree/TreeRow.js
@@ -16,18 +16,16 @@ define(function(require, exports, module
   const dom = require("devtools/client/shared/vendor/react-dom-factories");
   const { findDOMNode } = require("devtools/client/shared/vendor/react-dom");
   const { tr } = dom;
 
   // Tree
   const TreeCell = createFactory(require("./TreeCell"));
   const LabelCell = createFactory(require("./LabelCell"));
 
-  // Scroll
-  const { scrollIntoViewIfNeeded } = require("devtools/client/shared/scroll");
   const { focusableSelector } = require("devtools/client/shared/focus");
 
   const UPDATE_ON_PROPS = [
     "name",
     "open",
     "value",
     "loading",
     "selected",
@@ -118,27 +116,16 @@ define(function(require, exports, module
         if (nextProps.member[prop] != this.props.member[prop]) {
           return true;
         }
       }
 
       return false;
     }
 
-    componentDidUpdate() {
-      if (this.props.member.selected) {
-        const row = findDOMNode(this);
-        // Because this is called asynchronously, context window might be
-        // already gone.
-        if (row.ownerDocument.defaultView) {
-          scrollIntoViewIfNeeded(row);
-        }
-      }
-    }
-
     componentWillUnmount() {
       this.observer.disconnect();
       this.observer = null;
     }
 
     /**
      * Makes sure that none of the focusable elements inside the row container
      * are tabbable if the row is not active. If the row is active and focus
--- a/devtools/client/shared/components/tree/TreeView.js
+++ b/devtools/client/shared/components/tree/TreeView.js
@@ -17,16 +17,18 @@ define(function(require, exports, module
   const PropTypes = require("devtools/client/shared/vendor/react-prop-types");
   const dom = require("devtools/client/shared/vendor/react-dom-factories");
 
   // Reps
   const { ObjectProvider } = require("./ObjectProvider");
   const TreeRow = createFactory(require("./TreeRow"));
   const TreeHeader = createFactory(require("./TreeHeader"));
 
+  const { scrollIntoView } = require("devtools/client/shared/scroll");
+
   const SUPPORTED_KEYS = [
     "ArrowUp",
     "ArrowDown",
     "ArrowLeft",
     "ArrowRight",
     "End",
     "Home",
     "Enter",
@@ -235,17 +237,18 @@ define(function(require, exports, module
 
       this.setState(Object.assign({}, this.state, state));
     }
 
     componentDidUpdate() {
       const selected = this.getSelectedRow();
       if (!selected && this.rows.length > 0) {
         this.selectRow(this.rows[
-          Math.min(this.state.lastSelectedIndex, this.rows.length - 1)]);
+          Math.min(this.state.lastSelectedIndex, this.rows.length - 1)
+        ], { alignTo: "top" });
       }
     }
 
     // Node expand/collapse
 
     toggle(nodePath) {
       const nodes = this.state.expandedNodes;
       if (this.isExpanded(nodePath)) {
@@ -286,49 +289,44 @@ define(function(require, exports, module
           break;
         case "ArrowLeft":
           if (row && row.props.member.open) {
             this.toggle(this.state.selected);
           } else {
             const parentRow = this.rows.slice(0, index).reverse().find(
               r => r.props.member.level < row.props.member.level);
             if (parentRow) {
-              this.selectRow(parentRow);
+              this.selectRow(parentRow, { alignTo: "top" });
             }
           }
           break;
         case "ArrowDown":
           const nextRow = this.rows[index + 1];
           if (nextRow) {
-            this.selectRow(nextRow);
+            this.selectRow(nextRow, { alignTo: "bottom" });
           }
           break;
         case "ArrowUp":
           const previousRow = this.rows[index - 1];
           if (previousRow) {
-            this.selectRow(previousRow);
+            this.selectRow(previousRow, { alignTo: "top" });
           }
           break;
         case "Home":
           const firstRow = this.rows[0];
 
           if (firstRow) {
-            // Due to the styling, the first row is sometimes overlapped by
-            // the table head. So we want to force the tree to scroll to the very top.
-            this.selectRow(firstRow, {
-              block: "end",
-              inline: "nearest",
-            });
+            this.selectRow(firstRow, { alignTo: "top" });
           }
           break;
 
         case "End":
           const lastRow = this.rows[this.rows.length - 1];
           if (lastRow) {
-            this.selectRow(lastRow);
+            this.selectRow(lastRow, { alignTo: "bottom" });
           }
           break;
 
         case "Enter":
         case " ":
           // On space or enter make selected row active. This means keyboard
           // focus handling is passed on to the tree row itself.
           if (this.treeRef.current === document.activeElement) {
@@ -362,17 +360,20 @@ define(function(require, exports, module
         return;
       }
 
       event.stopPropagation();
       const cell = event.target.closest("td");
       if (cell && cell.classList.contains("treeLabelCell")) {
         this.toggle(nodePath);
       }
-      this.selectRow(event.currentTarget);
+
+      this.selectRow(
+        this.rows.find(row => row.props.member.path === nodePath),
+        { preventAutoScroll: true });
     }
 
     onContextMenu(member, event) {
       const onContextMenuRow = this.props.onContextMenuRow;
       if (onContextMenuRow) {
         onContextMenuRow.call(this, member, event);
       }
     }
@@ -389,37 +390,57 @@ define(function(require, exports, module
       if (!row) {
         // If selected row is not found, return index of the first row.
         return 0;
       }
 
       return this.rows.indexOf(row);
     }
 
-    selectRow(row, scrollOptions = {block: "nearest"}) {
-      row = findDOMNode(row);
+    _scrollIntoView(row, options = {}) {
+      const treeEl = this.treeRef.current;
+      if (!treeEl || !row) {
+        return;
+      }
+
+      const { props: { member: { path } = {} } = {} } = row;
+      if (!path) {
+        return;
+      }
 
-      if (this.state.selected === row.id) {
-        row.scrollIntoView(scrollOptions);
+      const element = treeEl.ownerDocument.getElementById(path);
+      if (!element) {
+        return;
+      }
+
+      scrollIntoView(element, { ...options });
+    }
+
+    selectRow(row, options = {}) {
+      const { props: { member: { path } = {} } = {} } = row;
+      if (this.isSelected(path)) {
         return;
       }
 
       if (this.state.active != null) {
-        if (this.treeRef.current !== document.activeElement) {
-          this.treeRef.current.focus();
+        const treeEl = this.treeRef.current;
+        if (treeEl && treeEl !== treeEl.ownerDocument.activeElement) {
+          treeEl.focus();
         }
       }
 
+      if (!options.preventAutoScroll) {
+        this._scrollIntoView(row, options);
+      }
+
       this.setState({
         ...this.state,
-        selected: row.id,
+        selected: path,
         active: null,
       });
-
-      row.scrollIntoView(scrollOptions);
     }
 
     activateRow(active) {
       this.setState({
         ...this.state,
         active,
       });
     }
--- a/devtools/shared/adb/adb.js
+++ b/devtools/shared/adb/adb.js
@@ -28,19 +28,21 @@ class Adb extends EventEmitter {
 
     this._listeners = new Set();
     this._devices = new Map();
     this._runtimes = [];
 
     this._updateAdbProcess = this._updateAdbProcess.bind(this);
     this._onDeviceConnected = this._onDeviceConnected.bind(this);
     this._onDeviceDisconnected = this._onDeviceDisconnected.bind(this);
+    this._onNoDevicesDetected = this._onNoDevicesDetected.bind(this);
 
     this._trackDevicesCommand.on("device-connected", this._onDeviceConnected);
     this._trackDevicesCommand.on("device-disconnected", this._onDeviceDisconnected);
+    this._trackDevicesCommand.on("no-devices-detected", this._onNoDevicesDetected);
     adbAddon.on("update", this._updateAdbProcess);
   }
 
   registerListener(listener) {
     this._listeners.add(listener);
     this.on("runtime-list-updated", listener);
     this._updateAdbProcess();
   }
@@ -121,15 +123,19 @@ class Adb extends EventEmitter {
     this.updateRuntimes();
   }
 
   _onDeviceDisconnected(deviceId) {
     this._devices.delete(deviceId);
     this.updateRuntimes();
   }
 
+  _onNoDevicesDetected() {
+    this.updateRuntimes();
+  }
+
   async _getDeviceRuntimes(device) {
     const socketPaths = [...await device.getRuntimeSocketPaths()];
     return socketPaths.map(socketPath => new AdbRuntime(device, socketPath));
   }
 }
 
 exports.adb = new Adb();
--- a/devtools/shared/adb/commands/track-devices.js
+++ b/devtools/shared/adb/commands/track-devices.js
@@ -118,19 +118,24 @@ class TrackDevicesCommand extends EventE
       }
 
       // Update devices.
       this._devices = newDevices;
     }
   }
 
   _disconnectAllDevices() {
-    for (const [deviceId, status] of this._devices.entries()) {
-      if (status !== ADB_STATUS_OFFLINE) {
-        this.emit("device-disconnected", deviceId);
+    if (this._devices.size === 0) {
+      // If no devices were detected, fire an event to let consumer resume.
+      this.emit("no-devices-detected");
+    } else {
+      for (const [deviceId, status] of this._devices.entries()) {
+        if (status !== ADB_STATUS_OFFLINE) {
+          this.emit("device-disconnected", deviceId);
+        }
       }
     }
     this._devices = new Map();
   }
 
   _fireConnectionEventIfNeeded(deviceId, currentStatus, newStatus) {
     const isCurrentOnline = !!(currentStatus && currentStatus !== ADB_STATUS_OFFLINE);
     const isNewOnline = !!(newStatus && newStatus !== ADB_STATUS_OFFLINE);
--- a/dom/base/ResizeObserverController.cpp
+++ b/dom/base/ResizeObserverController.cpp
@@ -4,16 +4,17 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "mozilla/dom/ResizeObserverController.h"
 
 #include "mozilla/dom/Document.h"
 #include "mozilla/dom/ErrorEvent.h"
 #include "mozilla/PresShell.h"
+#include "mozilla/Unused.h"
 #include "nsPresContext.h"
 #include "nsRefreshDriver.h"
 #include <limits>
 
 namespace mozilla {
 namespace dom {
 
 void ResizeObserverNotificationHelper::WillRefresh(TimeStamp aTime) {
@@ -58,16 +59,17 @@ void ResizeObserverNotificationHelper::U
   }
 
   nsRefreshDriver* refreshDriver = GetRefreshDriver();
   MOZ_RELEASE_ASSERT(refreshDriver,
                      "We should not leave a dangling reference to the observer around");
 
   bool rv = refreshDriver->RemoveRefreshObserver(this, FlushType::Display);
   MOZ_DIAGNOSTIC_ASSERT(rv, "Should remove the observer successfully");
+  Unused << rv;
 
   mRegistered = false;
 }
 
 ResizeObserverNotificationHelper::~ResizeObserverNotificationHelper() {
   MOZ_RELEASE_ASSERT(!mRegistered, "How can we die when registered?");
   MOZ_RELEASE_ASSERT(!mOwner, "Forgot to clear weak pointer?");
 }
--- a/dom/base/test/browser_bug593387.js
+++ b/dom/base/test/browser_bug593387.js
@@ -3,17 +3,17 @@
  * Loads a chrome document in a content docshell and then inserts a
  * X-Frame-Options: DENY iframe into the document and verifies that the document
  * loads. The policy we are enforcing is outlined here:
  * https://bugzilla.mozilla.org/show_bug.cgi?id=593387#c17
 */
 
 add_task(async function test() {
   await BrowserTestUtils.withNewTab({ gBrowser,
-                                      url: "chrome://global/content/mozilla.xhtml" },
+                                      url: "chrome://global/content/aboutProfiles.xhtml" },
                                      async function(newBrowser) {
     // NB: We load the chrome:// page in the parent process.
     await testXFOFrameInChrome(newBrowser);
 
     // Run next test (try the same with a content top-level context)
     await BrowserTestUtils.loadURI(newBrowser, "http://example.com/");
     await BrowserTestUtils.browserLoaded(newBrowser);
 
--- a/dom/html/HTMLMediaElement.cpp
+++ b/dom/html/HTMLMediaElement.cpp
@@ -2450,37 +2450,53 @@ void HTMLMediaElement::ResumeLoad(Preloa
     }
   }
 }
 
 bool HTMLMediaElement::AllowedToPlay() const {
   return AutoplayPolicy::IsAllowedToPlay(*this);
 }
 
+uint32_t HTMLMediaElement::GetPreloadDefault() const {
+  if (mMediaSource) {
+    return HTMLMediaElement::PRELOAD_ATTR_METADATA;
+  }
+  if (OnCellularConnection()) {
+    return Preferences::GetInt("media.preload.default.cellular",
+                               HTMLMediaElement::PRELOAD_ATTR_NONE);
+  }
+  return Preferences::GetInt("media.preload.default",
+                             HTMLMediaElement::PRELOAD_ATTR_METADATA);
+}
+
+uint32_t HTMLMediaElement::GetPreloadDefaultAuto() const {
+  if (OnCellularConnection()) {
+    return Preferences::GetInt("media.preload.auto.cellular",
+                               HTMLMediaElement::PRELOAD_ATTR_METADATA);
+  }
+  return Preferences::GetInt("media.preload.auto",
+                             HTMLMediaElement::PRELOAD_ENOUGH);
+}
+
 void HTMLMediaElement::UpdatePreloadAction() {
   PreloadAction nextAction = PRELOAD_UNDEFINED;
   // If autoplay is set, or we're playing, we should always preload data,
   // as we'll need it to play.
   if ((AutoplayPolicy::IsAllowedToPlay(*this) &&
        HasAttr(kNameSpaceID_None, nsGkAtoms::autoplay)) ||
       !mPaused) {
     nextAction = HTMLMediaElement::PRELOAD_ENOUGH;
   } else {
     // Find the appropriate preload action by looking at the attribute.
     const nsAttrValue* val =
         mAttrs.GetAttr(nsGkAtoms::preload, kNameSpaceID_None);
     // MSE doesn't work if preload is none, so it ignores the pref when src is
     // from MSE.
-    uint32_t preloadDefault =
-        mMediaSource
-            ? HTMLMediaElement::PRELOAD_ATTR_METADATA
-            : Preferences::GetInt("media.preload.default",
-                                  HTMLMediaElement::PRELOAD_ATTR_METADATA);
-    uint32_t preloadAuto = Preferences::GetInt(
-        "media.preload.auto", HTMLMediaElement::PRELOAD_ENOUGH);
+    uint32_t preloadDefault = GetPreloadDefault();
+    uint32_t preloadAuto = GetPreloadDefaultAuto();
     if (!val) {
       // Attribute is not set. Use the preload action specified by the
       // media.preload.default pref, or just preload metadata if not present.
       nextAction = static_cast<PreloadAction>(preloadDefault);
     } else if (val->Type() == nsAttrValue::eEnum) {
       PreloadAttrValue attr =
           static_cast<PreloadAttrValue>(val->GetEnumValue());
       if (attr == HTMLMediaElement::PRELOAD_ATTR_EMPTY ||
--- a/dom/html/HTMLMediaElement.h
+++ b/dom/html/HTMLMediaElement.h
@@ -1732,16 +1732,19 @@ class HTMLMediaElement : public nsGeneri
 
  private:
   already_AddRefed<PlayPromise> CreatePlayPromise(ErrorResult& aRv) const;
 
   void UpdateHadAudibleAutoplayState();
 
   virtual void MaybeBeginCloningVisually(){};
 
+  uint32_t GetPreloadDefault() const;
+  uint32_t GetPreloadDefaultAuto() const;
+
   /**
    * This function is called by AfterSetAttr and OnAttrSetButNotChanged.
    * It will not be called if the value is being unset.
    *
    * @param aNamespaceID the namespace of the attr being set
    * @param aName the localname of the attribute being set
    * @param aNotify Whether we plan to notify document observers.
    */
--- a/dom/ipc/ContentChild.cpp
+++ b/dom/ipc/ContentChild.cpp
@@ -2024,16 +2024,27 @@ mozilla::ipc::IPCResult ContentChild::Re
   }
 
   static_cast<loader::ScriptCacheChild*>(actor)->Init(fd, wantCacheData);
   return IPC_OK();
 }
 
 PNeckoChild* ContentChild::AllocPNeckoChild() { return new NeckoChild(); }
 
+mozilla::ipc::IPCResult ContentChild::RecvNetworkLinkTypeChange(
+    const uint32_t& aType) {
+  mNetworkLinkType = aType;
+  nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
+  if (obs) {
+    obs->NotifyObservers(nullptr, "contentchild:network-link-type-changed",
+                         nullptr);
+  }
+  return IPC_OK();
+}
+
 bool ContentChild::DeallocPNeckoChild(PNeckoChild* necko) {
   delete necko;
   return true;
 }
 
 PPrintingChild* ContentChild::AllocPPrintingChild() {
   // The ContentParent should never attempt to allocate the nsPrintingProxy,
   // which implements PPrintingChild. Instead, the nsPrintingProxy service is
--- a/dom/ipc/ContentChild.h
+++ b/dom/ipc/ContentChild.h
@@ -484,16 +484,19 @@ class ContentChild final : public PConte
 
   mozilla::ipc::IPCResult RecvActivate(PBrowserChild* aTab);
 
   mozilla::ipc::IPCResult RecvDeactivate(PBrowserChild* aTab);
 
   mozilla::ipc::IPCResult RecvRefreshScreens(
       nsTArray<ScreenDetails>&& aScreens);
 
+  mozilla::ipc::IPCResult RecvNetworkLinkTypeChange(const uint32_t& aType);
+  uint32_t NetworkLinkType() const { return mNetworkLinkType; }
+
   // Get the directory for IndexedDB files. We query the parent for this and
   // cache the value
   nsString& GetIndexedDBPath();
 
   ContentParentId GetID() const { return mID; }
 
 #if defined(XP_WIN) && defined(ACCESSIBILITY)
   uint32_t GetChromeMainThreadId() const { return mMainChromeTid; }
@@ -806,16 +809,18 @@ class ContentChild final : public PConte
   mozilla::Atomic<bool> mShuttingDown;
 
 #ifdef NIGHTLY_BUILD
   // NOTE: This member is atomic because it can be accessed from
   // off-main-thread.
   mozilla::Atomic<uint32_t> mPendingInputEvents;
 #endif
 
+  uint32_t mNetworkLinkType = 0;
+
   DISALLOW_EVIL_CONSTRUCTORS(ContentChild);
 };
 
 uint64_t NextWindowID();
 
 }  // namespace dom
 }  // namespace mozilla
 
--- a/dom/ipc/ContentParent.cpp
+++ b/dom/ipc/ContentParent.cpp
@@ -153,16 +153,17 @@
 #include "nsIGfxInfo.h"
 #include "nsIIdleService.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsILocalStorageManager.h"
 #include "nsIMemoryInfoDumper.h"
 #include "nsIMemoryReporter.h"
 #include "nsIMozBrowserFrame.h"
 #include "nsIMutable.h"
+#include "nsINetworkLinkService.h"
 #include "nsIObserverService.h"
 #include "nsIParentChannel.h"
 #include "nsIRemoteWindowContext.h"
 #include "nsIScriptError.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsISearchService.h"
 #include "nsIServiceWorkerManager.h"
 #include "nsISiteSecurityService.h"
@@ -609,16 +610,17 @@ static const char* sObserverTopics[] = {
     "a11y-init-or-shutdown",
 #endif
     "cacheservice:empty-cache",
     "intl:app-locales-changed",
     "intl:requested-locales-changed",
     "cookie-changed",
     "private-cookie-changed",
     "clear-site-data-reload-needed",
+    NS_NETWORK_LINK_TYPE_TOPIC,
 };
 
 #if defined(XP_MACOSX) && defined(MOZ_SANDBOX)
 bool ContentParent::sEarlySandboxInit = false;
 #endif
 
 // PreallocateProcess is called by the PreallocatedProcessManager.
 // ContentParent then takes this process back within GetNewOrUsedBrowserProcess.
@@ -3119,20 +3121,40 @@ ContentParent::Observe(nsISupports* aSub
       cs->RemoveCookie(xpcCookie);
     } else if ((!nsCRT::strcmp(aData, u"added")) ||
                (!nsCRT::strcmp(aData, u"changed"))) {
       cs->AddCookie(xpcCookie);
     }
   } else if (!strcmp(aTopic, "clear-site-data-reload-needed")) {
     // Rebroadcast "clear-site-data-reload-needed".
     Unused << SendClearSiteDataReloadNeeded(nsString(aData));
-  }
+  } else if (!strcmp(aTopic, NS_NETWORK_LINK_TYPE_TOPIC)) {
+    UpdateNetworkLinkType();
+  }
+
   return NS_OK;
 }
 
+void ContentParent::UpdateNetworkLinkType() {
+  nsresult rv;
+  nsCOMPtr<nsINetworkLinkService> nls =
+      do_GetService(NS_NETWORK_LINK_SERVICE_CONTRACTID, &rv);
+  if (NS_FAILED(rv)) {
+    return;
+  }
+
+  uint32_t linkType = nsINetworkLinkService::LINK_TYPE_UNKNOWN;
+  rv = nls->GetLinkType(&linkType);
+  if (NS_FAILED(rv)) {
+    return;
+  }
+
+  Unused << SendNetworkLinkTypeChange(linkType);
+}
+
 NS_IMETHODIMP
 ContentParent::GetInterface(const nsIID& aIID, void** aResult) {
   NS_ENSURE_ARG_POINTER(aResult);
 
   if (aIID.Equals(NS_GET_IID(nsIMessageSender))) {
     nsCOMPtr<nsIMessageSender> mm = GetMessageManager();
     mm.forget(aResult);
     return NS_OK;
--- a/dom/ipc/ContentParent.h
+++ b/dom/ipc/ContentParent.h
@@ -1208,16 +1208,18 @@ class ContentParent final : public PCont
 
   bool IsRecordingOrReplaying() const {
     return mRecordReplayState != eNotRecordingOrReplaying;
   }
 
   void OnBrowsingContextGroupSubscribe(BrowsingContextGroup* aGroup);
   void OnBrowsingContextGroupUnsubscribe(BrowsingContextGroup* aGroup);
 
+  void UpdateNetworkLinkType();
+
  private:
   // Released in ActorDestroy; deliberately not exposed to the CC.
   RefPtr<ContentParent> mSelfRef;
 
   // If you add strong pointers to cycle collected objects here, be sure to
   // release these objects in ShutDownProcess.  See the comment there for more
   // details.
 
--- a/dom/ipc/PContent.ipdl
+++ b/dom/ipc/PContent.ipdl
@@ -425,16 +425,18 @@ child:
       Endpoint<PCompositorManagerChild> compositor,
       Endpoint<PImageBridgeChild> bridge,
       Endpoint<PVRManagerChild> vr,
       Endpoint<PVideoDecoderManagerChild> video,
       uint32_t[] namespaces);
 
     async AudioDefaultDeviceChange();
 
+    async NetworkLinkTypeChange(uint32_t type);
+
     // Re-create the rendering stack for a device reset.
     async ReinitRenderingForDeviceReset();
 
     /**
      * Enable system-level sandboxing features, if available.  Can
      * usually only be performed zero or one times.  The child may
      * abnormally exit if this fails; the details are OS-specific.
      */
--- a/dom/media/ChannelMediaDecoder.cpp
+++ b/dom/media/ChannelMediaDecoder.cpp
@@ -6,16 +6,17 @@
 
 #include "ChannelMediaDecoder.h"
 #include "DecoderTraits.h"
 #include "MediaDecoderStateMachine.h"
 #include "MediaFormatReader.h"
 #include "BaseMediaResource.h"
 #include "MediaShutdownManager.h"
 #include "mozilla/StaticPrefs.h"
+#include "VideoUtils.h"
 
 namespace mozilla {
 
 extern LazyLogModule gMediaDecoderLog;
 #define LOG(x, ...) \
   DDMOZ_LOG(gMediaDecoderLog, LogLevel::Debug, x, ##__VA_ARGS__)
 
 ChannelMediaDecoder::ResourceCallback::ResourceCallback(
@@ -453,32 +454,34 @@ MediaStatistics ChannelMediaDecoder::Get
   result.mPlaybackRateReliable = aInfo.mReliable;
   result.mPlaybackPosition = aPlaybackPosition;
   return result;
 }
 
 bool ChannelMediaDecoder::ShouldThrottleDownload(
     const MediaStatistics& aStats) {
   // We throttle the download if either the throttle override pref is set
-  // (so that we can always throttle in Firefox on mobile) or if the download
-  // is fast enough that there's no concern about playback being interrupted.
+  // (so that we always throttle at the readahead limit on mobile if using
+  // a cellular network) or if the download is fast enough that there's no
+  // concern about playback being interrupted.
   MOZ_ASSERT(NS_IsMainThread());
   NS_ENSURE_TRUE(GetStateMachine(), false);
 
   int64_t length = aStats.mTotalBytes;
   if (length > 0 &&
       length <= int64_t(StaticPrefs::MediaMemoryCacheMaxSize()) * 1024) {
     // Don't throttle the download of small resources. This is to speed
     // up seeking, as seeks into unbuffered ranges would require starting
     // up a new HTTP transaction, which adds latency.
     return false;
   }
 
-  if (Preferences::GetBool("media.throttle-regardless-of-download-rate",
-                           false)) {
+  if (OnCellularConnection() &&
+      Preferences::GetBool(
+          "media.throttle-cellular-regardless-of-download-rate", false)) {
     return true;
   }
 
   if (!aStats.mDownloadRateReliable || !aStats.mPlaybackRateReliable) {
     return false;
   }
   uint32_t factor =
       std::max(2u, Preferences::GetUint("media.throttle-factor", 2));
--- a/dom/media/FileBlockCache.cpp
+++ b/dom/media/FileBlockCache.cpp
@@ -120,39 +120,36 @@ void FileBlockCache::Flush() {
     MutexAutoLock mon(self->mDataMutex);
     // Just discard pending changes, assume MediaCache won't read from
     // blocks it hasn't written to.
     self->mChangeIndexList.clear();
     self->mBlockChanges.Clear();
   }));
 }
 
-int32_t FileBlockCache::GetMaxBlocks() const {
+size_t FileBlockCache::GetMaxBlocks(size_t aCacheSizeInKB) const {
   // We look up the cache size every time. This means dynamic changes
   // to the pref are applied.
-  const uint32_t cacheSizeKb =
-      std::min(StaticPrefs::MediaCacheSize(), uint32_t(INT32_MAX) * 2);
   // Ensure we can divide BLOCK_SIZE by 1024.
   static_assert(MediaCacheStream::BLOCK_SIZE % 1024 == 0,
                 "BLOCK_SIZE should be a multiple of 1024");
   // Ensure BLOCK_SIZE/1024 is at least 2.
   static_assert(MediaCacheStream::BLOCK_SIZE / 1024 >= 2,
                 "BLOCK_SIZE / 1024 should be at least 2");
   // Ensure we can convert BLOCK_SIZE/1024 to a uint32_t without truncation.
   static_assert(MediaCacheStream::BLOCK_SIZE / 1024 <= int64_t(UINT32_MAX),
                 "BLOCK_SIZE / 1024 should be at most UINT32_MAX");
   // Since BLOCK_SIZE is a strict multiple of 1024,
-  // cacheSizeKb * 1024 / BLOCK_SIZE == cacheSizeKb / (BLOCK_SIZE / 1024),
-  // but the latter formula avoids a potential overflow from `* 1024`.
+  // aCacheSizeInKB * 1024 / BLOCK_SIZE == aCacheSizeInKB / (BLOCK_SIZE /
+  // 1024), but the latter formula avoids a potential overflow from `* 1024`.
   // And because BLOCK_SIZE/1024 is at least 2, the maximum cache size
   // INT32_MAX*2 will give a maxBlocks that can fit in an int32_t.
-  constexpr uint32_t blockSizeKb =
-      uint32_t(MediaCacheStream::BLOCK_SIZE / 1024);
-  const int32_t maxBlocks = int32_t(cacheSizeKb / blockSizeKb);
-  return std::max(maxBlocks, int32_t(1));
+  constexpr size_t blockSizeKb = size_t(MediaCacheStream::BLOCK_SIZE / 1024);
+  const size_t maxBlocks = aCacheSizeInKB / blockSizeKb;
+  return std::max(maxBlocks, size_t(1));
 }
 
 FileBlockCache::FileBlockCache()
     : mFileMutex("MediaCache.Writer.IO.Mutex"),
       mFD(nullptr),
       mFDCurrentPos(0),
       mDataMutex("MediaCache.Writer.Data.Mutex"),
       mIsWriteScheduled(false),
--- a/dom/media/FileBlockCache.h
+++ b/dom/media/FileBlockCache.h
@@ -63,17 +63,17 @@ class FileBlockCache : public MediaBlock
   // Launch thread and open temporary file.
   nsresult Init() override;
 
   // Will discard pending changes if any.
   void Flush() override;
 
   // Maximum number of blocks allowed in this block cache.
   // Calculated from "media.cache_size" pref.
-  int32_t GetMaxBlocks() const override;
+  size_t GetMaxBlocks(size_t aCacheSizeInKB) const override;
 
   // Can be called on any thread. This defers to a non-main thread.
   nsresult WriteBlock(uint32_t aBlockIndex, Span<const uint8_t> aData1,
                       Span<const uint8_t> aData2) override;
 
   // Synchronously reads data from file. May read from file or memory
   // depending on whether written blocks have been flushed to file yet.
   // Not recommended to be called from the main thread, as can cause jank.
--- a/dom/media/MediaBlockCacheBase.h
+++ b/dom/media/MediaBlockCacheBase.h
@@ -51,17 +51,17 @@ class MediaBlockCacheBase {
   virtual nsresult Init() = 0;
 
   // Erase data and discard pending changes to reset the cache to its pristine
   // state as it was after Init().
   virtual void Flush() = 0;
 
   // Maximum number of blocks expected in this block cache. (But allow overflow
   // to accomodate incoming traffic before MediaCache can handle it.)
-  virtual int32_t GetMaxBlocks() const = 0;
+  virtual size_t GetMaxBlocks(size_t aCacheSizeInKiB) const = 0;
 
   // Can be called on any thread. This defers to a non-main thread.
   virtual nsresult WriteBlock(uint32_t aBlockIndex, Span<const uint8_t> aData1,
                               Span<const uint8_t> aData2) = 0;
 
   // Synchronously reads data from file. May read from file or memory
   // depending on whether written blocks have been flushed to file yet.
   // Not recommended to be called from the main thread, as can cause jank.
--- a/dom/media/MediaCache.cpp
+++ b/dom/media/MediaCache.cpp
@@ -6,34 +6,37 @@
 
 #include "MediaCache.h"
 
 #include "ChannelMediaResource.h"
 #include "FileBlockCache.h"
 #include "MediaBlockCacheBase.h"
 #include "MediaResource.h"
 #include "MemoryBlockCache.h"
+#include "mozilla/Atomics.h"
 #include "mozilla/Attributes.h"
 #include "mozilla/ClearOnShutdown.h"
 #include "mozilla/ErrorNames.h"
 #include "mozilla/Logging.h"
 #include "mozilla/Monitor.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/Services.h"
 #include "mozilla/StaticPtr.h"
 #include "mozilla/StaticPrefs.h"
 #include "mozilla/SystemGroup.h"
 #include "mozilla/Telemetry.h"
 #include "nsContentUtils.h"
+#include "nsINetworkLinkService.h"
 #include "nsIObserverService.h"
 #include "nsIPrincipal.h"
 #include "nsPrintfCString.h"
 #include "nsProxyRelease.h"
 #include "nsThreadUtils.h"
 #include "prio.h"
+#include "VideoUtils.h"
 #include <algorithm>
 
 namespace mozilla {
 
 #undef LOG
 #undef LOGI
 #undef LOGE
 LazyLogModule gMediaCacheLog("MediaCache");
@@ -109,24 +112,27 @@ StaticRefPtr<MediaCacheFlusher> MediaCac
 NS_IMPL_ISUPPORTS(MediaCacheFlusher, nsIObserver, nsISupportsWeakReference)
 
 /* static */
 void MediaCacheFlusher::RegisterMediaCache(MediaCache* aMediaCache) {
   NS_ASSERTION(NS_IsMainThread(), "Only call on main thread");
 
   if (!gMediaCacheFlusher) {
     gMediaCacheFlusher = new MediaCacheFlusher();
-
     nsCOMPtr<nsIObserverService> observerService =
         mozilla::services::GetObserverService();
     if (observerService) {
       observerService->AddObserver(gMediaCacheFlusher, "last-pb-context-exited",
                                    true);
       observerService->AddObserver(gMediaCacheFlusher,
                                    "cacheservice:empty-cache", true);
+      observerService->AddObserver(
+          gMediaCacheFlusher, "contentchild:network-link-type-changed", true);
+      observerService->AddObserver(gMediaCacheFlusher,
+                                   NS_NETWORK_LINK_TYPE_TOPIC, true);
     }
   }
 
   gMediaCacheFlusher->mMediaCaches.AppendElement(aMediaCache);
 }
 
 /* static */
 void MediaCacheFlusher::UnregisterMediaCache(MediaCache* aMediaCache) {
@@ -237,16 +243,20 @@ class MediaCache {
 
   mozilla::Monitor& Monitor() {
     // This method should only be called outside the main thread.
     // The MOZ_DIAGNOSTIC_ASSERT(!NS_IsMainThread()) assertion should be
     // re-added as part of bug 1464045
     return mMonitor;
   }
 
+  // Updates the cache size, readahead limit, and resume threshold, based on
+  // whether we're on a cellular connection or not. Main thread only.
+  static void UpdateGeometryStatics();
+
   /**
    * An iterator that makes it easy to iterate through all streams that
    * have a given resource ID and are not closed.
    * Must be used while holding the media cache lock.
    */
   class ResourceStreamIterator {
    public:
     ResourceStreamIterator(MediaCache* aMediaCache, int64_t aResourceID)
@@ -277,16 +287,17 @@ class MediaCache {
 #ifdef DEBUG
         ,
         mInUpdate(false)
 #endif
   {
     NS_ASSERTION(NS_IsMainThread(), "Only construct MediaCache on main thread");
     MOZ_COUNT_CTOR(MediaCache);
     MediaCacheFlusher::RegisterMediaCache(this);
+    UpdateGeometryStatics();
   }
 
   ~MediaCache() {
     NS_ASSERTION(NS_IsMainThread(), "Only destroy MediaCache on main thread");
     if (this == gMediaCache) {
       LOG("~MediaCache(Global file-backed MediaCache)");
       // This is the file-backed MediaCache, reset the global pointer.
       gMediaCache = nullptr;
@@ -308,16 +319,31 @@ class MediaCache {
     MediaCacheFlusher::UnregisterMediaCache(this);
     NS_ASSERTION(mStreams.IsEmpty(), "Stream(s) still open!");
     Truncate();
     NS_ASSERTION(mIndex.Length() == 0, "Blocks leaked?");
 
     MOZ_COUNT_DTOR(MediaCache);
   }
 
+  static size_t CacheSize() {
+    MOZ_ASSERT(sThread->IsOnCurrentThread());
+    return sCacheSizeInKB;
+  }
+
+  static size_t ReadaheadLimit() {
+    MOZ_ASSERT(sThread->IsOnCurrentThread());
+    return sReadaheadLimit;
+  }
+
+  static size_t ResumeThreshold() {
+    MOZ_ASSERT(sThread->IsOnCurrentThread());
+    return sResumeThreshold;
+  }
+
   // Find a free or reusable block and return its index. If there are no
   // free blocks and no reusable blocks, add a new block to the cache
   // and return it. Can return -1 on OOM.
   int32_t FindBlockForIncomingData(AutoLock&, TimeStamp aNow,
                                    MediaCacheStream* aStream,
                                    int32_t aStreamBlockIndex);
   // Find a reusable block --- a free block, if there is one, otherwise
   // the reusable block with the latest predicted-next-use, or -1 if
@@ -446,16 +472,21 @@ class MediaCache {
   nsTArray<int64_t> mSuspendedStatusToNotify;
   // The thread on which we will run data callbacks from the channels.
   // Note this thread is shared among all MediaCache instances.
   static StaticRefPtr<nsIThread> sThread;
   // True if we've tried to init sThread. Note we try once only so it is safe
   // to access sThread on all threads.
   static bool sThreadInit;
 
+  // Accesson MediaCache thread only.
+  static size_t sCacheSizeInKB;
+  static size_t sReadaheadLimit;
+  static size_t sResumeThreshold;
+
  private:
   // Used by MediaCacheStream::GetDebugInfo() only for debugging.
   // Don't add new callers to this function.
   friend nsCString MediaCacheStream::GetDebugInfo();
   mozilla::Monitor& GetMonitorOnTheMainThread() {
     MOZ_DIAGNOSTIC_ASSERT(NS_IsMainThread());
     return mMonitor;
   }
@@ -465,16 +496,47 @@ class MediaCache {
 /* static */
 MediaCache* MediaCache::gMediaCache;
 
 /* static */
 StaticRefPtr<nsIThread> MediaCache::sThread;
 /* static */
 bool MediaCache::sThreadInit = false;
 
+/* static */ size_t MediaCache::sCacheSizeInKB = 0;
+/* static */ size_t MediaCache::sReadaheadLimit = 0;
+/* static */ size_t MediaCache::sResumeThreshold = 0;
+
+void MediaCache::UpdateGeometryStatics() {
+  NS_ASSERTION(NS_IsMainThread(),
+               "Only call on main thread");  // JNI required on Android...
+  bool cacheAggressively = !OnCellularConnection();
+  LOG("MediaCache::UpdateGeometryStatics() cacheAggressively=%d",
+      cacheAggressively);
+  // Read the prefs on the main thread, and post their value to the MediaCache
+  // thread. This ensures the values are synchronized.
+  uint32_t cacheSize = 0, readaheadLimit = 0, resumeThreshold = 0;
+  if (cacheAggressively) {
+    cacheSize = StaticPrefs::MediaCacheSize();
+    readaheadLimit = StaticPrefs::MediaCacheReadaheadLimit();
+    resumeThreshold = StaticPrefs::MediaCacheResumeThreshold();
+  } else {
+    cacheSize = StaticPrefs::MediaCacheCellularSize();
+    readaheadLimit = StaticPrefs::MediaCacheCellularReadaheadLimit();
+    resumeThreshold = StaticPrefs::MediaCacheCellularResumeThreshold();
+  }
+  nsCOMPtr<nsIRunnable> r =
+      NS_NewRunnableFunction("MediaCache::UpdateGeometryStatics", [=]() {
+        sCacheSizeInKB = cacheSize;
+        sReadaheadLimit = readaheadLimit;
+        sResumeThreshold = resumeThreshold;
+      });
+  sThread->Dispatch(r.forget());
+}
+
 NS_IMETHODIMP
 MediaCacheFlusher::Observe(nsISupports* aSubject, char const* aTopic,
                            char16_t const* aData) {
   NS_ASSERTION(NS_IsMainThread(), "Only call on main thread");
 
   if (strcmp(aTopic, "last-pb-context-exited") == 0) {
     for (MediaCache* mc : mMediaCaches) {
       mc->CloseStreamsForPrivateBrowsing();
@@ -482,16 +544,20 @@ MediaCacheFlusher::Observe(nsISupports* 
     return NS_OK;
   }
   if (strcmp(aTopic, "cacheservice:empty-cache") == 0) {
     for (MediaCache* mc : mMediaCaches) {
       mc->Flush();
     }
     return NS_OK;
   }
+  if (strcmp(aTopic, "contentchild:network-link-type-changed") == 0 ||
+      strcmp(aTopic, NS_NETWORK_LINK_TYPE_TOPIC) == 0) {
+    MediaCache::UpdateGeometryStatics();
+  }
   return NS_OK;
 }
 
 MediaCacheStream::MediaCacheStream(ChannelMediaResource* aClient,
                                    bool aIsPrivateBrowsing)
     : mMediaCache(nullptr),
       mClient(aClient),
       mIsTransportSeekable(false),
@@ -822,17 +888,18 @@ int32_t MediaCache::FindBlockForIncoming
       FindReusableBlock(aLock, aNow, aStream, aStreamBlockIndex, INT32_MAX);
 
   if (blockIndex < 0 || !IsBlockFree(blockIndex)) {
     // The block returned is already allocated.
     // Don't reuse it if a) there's room to expand the cache or
     // b) the data we're going to store in the free block is not higher
     // priority than the data already stored in the free block.
     // The latter can lead us to go over the cache limit a bit.
-    if ((mIndex.Length() < uint32_t(mBlockCache->GetMaxBlocks()) ||
+    if ((mIndex.Length() <
+             uint32_t(mBlockCache->GetMaxBlocks(MediaCache::CacheSize())) ||
          blockIndex < 0 ||
          PredictNextUseForIncomingData(aLock, aStream) >=
              PredictNextUse(aLock, aNow, blockIndex))) {
       blockIndex = mIndex.Length();
       if (!mIndex.AppendElement()) return -1;
       mIndexWatermark = std::max(mIndexWatermark, blockIndex + 1);
       mFreeBlocks.AddFirstBlock(blockIndex);
       return blockIndex;
@@ -1150,17 +1217,17 @@ void MediaCache::Update() {
   // stream, decoder and element code.
   AutoTArray<StreamAction, 10> actions;
 
   mUpdateQueued = false;
 #ifdef DEBUG
   mInUpdate = true;
 #endif
 
-  int32_t maxBlocks = mBlockCache->GetMaxBlocks();
+  int32_t maxBlocks = mBlockCache->GetMaxBlocks(MediaCache::CacheSize());
   TimeStamp now = TimeStamp::Now();
 
   int32_t freeBlockCount = mFreeBlocks.GetCount();
   TimeDuration latestPredictedUseForOverflow = 0;
   if (mIndex.Length() > uint32_t(maxBlocks)) {
     // Try to trim back the cache to its desired maximum size. The cache may
     // have overflowed simply due to data being received when we have
     // no blocks in the main part of the cache that are free or lower
@@ -1271,18 +1338,18 @@ void MediaCache::Update() {
   TimeDuration latestNextUse;
   if (freeBlockCount == 0) {
     int32_t reusableBlock = FindReusableBlock(lock, now, nullptr, 0, maxBlocks);
     if (reusableBlock >= 0) {
       latestNextUse = PredictNextUse(lock, now, reusableBlock);
     }
   }
 
-  int32_t resumeThreshold = StaticPrefs::MediaCacheResumeThreshold();
-  int32_t readaheadLimit = StaticPrefs::MediaCacheReadaheadLimit();
+  int32_t resumeThreshold = MediaCache::ResumeThreshold();
+  int32_t readaheadLimit = MediaCache::ReadaheadLimit();
 
   for (uint32_t i = 0; i < mStreams.Length(); ++i) {
     actions.AppendElement(StreamAction{});
 
     MediaCacheStream* stream = mStreams[i];
     if (stream->mClosed) {
       LOG("Stream %p closed", stream);
       continue;
--- a/dom/media/MemoryBlockCache.h
+++ b/dom/media/MemoryBlockCache.h
@@ -40,17 +40,17 @@ class MemoryBlockCache : public MediaBlo
   // Allocate initial buffer.
   // If re-initializing, clear buffer.
   virtual nsresult Init() override;
 
   void Flush() override;
 
   // Maximum number of blocks allowed in this block cache.
   // Based on initial content length, and minimum usable block cache.
-  int32_t GetMaxBlocks() const override { return mMaxBlocks; }
+  size_t GetMaxBlocks(size_t) const override { return mMaxBlocks; }
 
   // Can be called on any thread.
   virtual nsresult WriteBlock(uint32_t aBlockIndex, Span<const uint8_t> aData1,
                               Span<const uint8_t> aData2) override;
 
   // Synchronously reads data from buffer.
   virtual nsresult Read(int64_t aOffset, uint8_t* aData, int32_t aLength,
                         int32_t* aBytes) override;
@@ -68,17 +68,17 @@ class MemoryBlockCache : public MediaBlo
   // aContentLength bytes. Buffer size can only grow.
   // Returns false if allocation failed.
   bool EnsureBufferCanContain(size_t aContentLength);
 
   // Initial content length.
   const size_t mInitialContentLength;
 
   // Maximum number of blocks that this MemoryBlockCache expects.
-  const int32_t mMaxBlocks;
+  const size_t mMaxBlocks;
 
   // Mutex which controls access to all members below.
   Mutex mMutex;
 
   nsTArray<uint8_t> mBuffer;
   bool mHasGrown = false;
 };
 
--- a/dom/media/VideoUtils.cpp
+++ b/dom/media/VideoUtils.cpp
@@ -9,28 +9,31 @@
 
 #include "CubebUtils.h"
 #include "ImageContainer.h"
 #include "MediaContainerType.h"
 #include "MediaResource.h"
 #include "TimeUnits.h"
 #include "VorbisUtils.h"
 #include "mozilla/Base64.h"
+#include "mozilla/dom/ContentChild.h"
 #include "mozilla/SharedThreadPool.h"
 #include "mozilla/StaticPrefs.h"
 #include "mozilla/SystemGroup.h"
 #include "mozilla/TaskCategory.h"
 #include "mozilla/TaskQueue.h"
 #include "mozilla/Telemetry.h"
 #include "nsCharSeparatedTokenizer.h"
 #include "nsContentTypeParser.h"
 #include "nsIConsoleService.h"
+#include "nsINetworkLinkService.h"
 #include "nsIRandomGenerator.h"
 #include "nsIServiceManager.h"
 #include "nsMathUtils.h"
+#include "nsNetCID.h"
 #include "nsServiceManagerUtils.h"
 #include "nsThreadUtils.h"
 
 namespace mozilla {
 
 using layers::PlanarYCbCrImage;
 using media::TimeUnit;
 
@@ -707,9 +710,51 @@ UniquePtr<TrackInfo> CreateTrackInfoWith
       if (maybeSamplerate && *maybeSamplerate > 0) {
         audioInfo->mRate = *maybeSamplerate;
       }
     }
   }
   return trackInfo;
 }
 
+bool OnCellularConnection() {
+  uint32_t linkType = nsINetworkLinkService::LINK_TYPE_UNKNOWN;
+  if (XRE_IsContentProcess()) {
+    mozilla::dom::ContentChild* cpc =
+        mozilla::dom::ContentChild::GetSingleton();
+    if (!cpc) {
+      NS_WARNING("Can't get ContentChild singleton in content process!");
+      return false;
+    }
+    linkType = cpc->NetworkLinkType();
+  } else {
+    nsresult rv;
+    nsCOMPtr<nsINetworkLinkService> nls =
+        do_GetService(NS_NETWORK_LINK_SERVICE_CONTRACTID, &rv);
+    if (NS_FAILED(rv)) {
+      NS_WARNING("Can't get nsINetworkLinkService.");
+      return false;
+    }
+
+    rv = nls->GetLinkType(&linkType);
+    if (NS_FAILED(rv)) {
+      NS_WARNING("Can't get network link type.");
+      return false;
+    }
+  }
+
+  switch (linkType) {
+    case nsINetworkLinkService::LINK_TYPE_UNKNOWN:
+    case nsINetworkLinkService::LINK_TYPE_ETHERNET:
+    case nsINetworkLinkService::LINK_TYPE_USB:
+    case nsINetworkLinkService::LINK_TYPE_WIFI:
+      return false;
+    case nsINetworkLinkService::LINK_TYPE_WIMAX:
+    case nsINetworkLinkService::LINK_TYPE_2G:
+    case nsINetworkLinkService::LINK_TYPE_3G:
+    case nsINetworkLinkService::LINK_TYPE_4G:
+      return true;
+  }
+
+  return false;
+}
+
 }  // end namespace mozilla
--- a/dom/media/VideoUtils.h
+++ b/dom/media/VideoUtils.h
@@ -540,11 +540,15 @@ static bool StringListContains(const Lis
 
 inline void AppendStringIfNotEmpty(nsACString& aDest, nsACString&& aSrc) {
   if (!aSrc.IsEmpty()) {
     aDest.Append(NS_LITERAL_CSTRING("\n"));
     aDest.Append(aSrc);
   }
 }
 
+// Returns true if we're running on a cellular connection; 2G, 3G, etc.
+// Main thread only.
+bool OnCellularConnection();
+
 }  // end namespace mozilla
 
 #endif
--- a/dom/security/test/csp/test_CSP.html
+++ b/dom/security/test/csp/test_CSP.html
@@ -101,22 +101,24 @@ window.testResult = function(testname, r
   // ... otherwise, finish
   window.examiner.remove();
   SimpleTest.finish();
 }
 
 SimpleTest.waitForExplicitFinish();
 
 SpecialPowers.pushPrefEnv(
-  {'set':[// This defaults to 0 ("preload none") on mobile (B2G/Android), which
-          // blocks loading the resource until the user interacts with a
-          // corresponding widget, which breaks the media_* tests. We set it
-          // back to the default used by desktop Firefox to get consistent
-          // behavior.
-          ["media.preload.default", 2]]},
+  {'set':[// On a cellular connection the default preload value is 0 ("preload
+          // none"). Our Android emulators emulate a cellular connection, and
+          // so by default preload no media data. This causes the media_* tests
+          // to timeout. We set the default used by cellular connections to the
+          // same as used by non-cellular connections in order to get
+          // consistent behavior across platforms/devices.
+          ["media.preload.default", 2],
+          ["media.preload.default.cellular", 2]]},
     function() {
       // save this for last so that our listeners are registered.
       // ... this loads the testbed of good and bad requests.
       document.getElementById('cspframe').src = 'file_main.html';
     });
 </script>
 </pre>
 </body>
--- a/dom/security/test/csp/test_redirects.html
+++ b/dom/security/test/csp/test_redirects.html
@@ -114,22 +114,24 @@ var testResult = function(testName, url,
 
   window.examiner.remove();
   SimpleTest.finish();
 }
 
 SimpleTest.waitForExplicitFinish();
 
 SpecialPowers.pushPrefEnv(
-  {'set':[// This defaults to 0 ("preload none") on mobile (B2G/Android), which
-          // blocks loading the resource until the user interacts with a
-          // corresponding widget, which breaks the media_* tests. We set it
-          // back to the default used by desktop Firefox to get consistent
-          // behavior.
-          ["media.preload.default", 2]]},
+  {'set':[// On a cellular connection the default preload value is 0 ("preload
+          // none"). Our Android emulators emulate a cellular connection, and
+          // so by default preload no media data. This causes the media_* tests
+          // to timeout. We set the default used by cellular connections to the
+          // same as used by non-cellular connections in order to get
+          // consistent behavior across platforms/devices.
+          ["media.preload.default", 2],
+          ["media.preload.default.cellular", 2]]},
   function() {
     // save this for last so that our listeners are registered.
     // ... this loads the testbed of good and bad requests.
     document.getElementById("harness").src = "file_redirects_main.html";
   });
 </script>
 </pre>
 
--- a/editor/libeditor/EditorBase.h
+++ b/editor/libeditor/EditorBase.h
@@ -1815,16 +1815,23 @@ class EditorBase : public nsIEditor,
       case NS_ERROR_EDITOR_DESTROYED:
         return NS_OK;
       // If editor meets unexpected DOM tree due to modified by mutation event
       // listener, editor needs to stop handling it.  However, editor shouldn't
       // return error for the users because Chrome does not throw exception in
       // this case.
       case NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE:
         return NS_OK;
+      // If the editing action is canceled by event listeners, editor needs
+      // to stop handling it.  However, editor shouldn't return error for
+      // the callers but they should be able to distinguish whether it's
+      // canceled or not.  Although it's DOM specific code, let's return
+      // DOM_SUCCESS_DOM_NO_OPERATION here.
+      case NS_ERROR_EDITOR_ACTION_CANCELED:
+        return NS_SUCCESS_DOM_NO_OPERATION;
       default:
         return aRv;
     }
   }
 
   /**
    * GetDocumentCharsetInternal() returns charset of the document.
    */
--- a/editor/libeditor/HTMLEditorCommands.cpp
+++ b/editor/libeditor/HTMLEditorCommands.cpp
@@ -46,22 +46,25 @@ static nsresult GetListState(HTMLEditor*
  * mozilla::StateUpdatingCommandBase
  *****************************************************************************/
 
 bool StateUpdatingCommandBase::IsCommandEnabled(Command aCommand,
                                                 TextEditor* aTextEditor) const {
   if (!aTextEditor) {
     return false;
   }
-  if (!aTextEditor->IsSelectionEditable()) {
+  HTMLEditor* htmlEditor = aTextEditor->AsHTMLEditor();
+  if (!htmlEditor) {
+    return false;
+  }
+  if (!htmlEditor->IsSelectionEditable()) {
     return false;
   }
   if (aCommand == Command::FormatAbsolutePosition) {
-    HTMLEditor* htmlEditor = aTextEditor->AsHTMLEditor();
-    return htmlEditor && htmlEditor->IsAbsolutePositionEditorEnabled();
+    return htmlEditor->IsAbsolutePositionEditorEnabled();
   }
   return true;
 }
 
 nsresult StateUpdatingCommandBase::DoCommand(Command aCommand,
                                              TextEditor& aTextEditor) const {
   HTMLEditor* htmlEditor = aTextEditor.AsHTMLEditor();
   if (NS_WARN_IF(!htmlEditor)) {
@@ -103,20 +106,16 @@ nsresult StateUpdatingCommandBase::GetCo
 
 StaticRefPtr<PasteNoFormattingCommand> PasteNoFormattingCommand::sInstance;
 
 bool PasteNoFormattingCommand::IsCommandEnabled(Command aCommand,
                                                 TextEditor* aTextEditor) const {
   if (!aTextEditor) {
     return false;
   }
-
-  // This command is only implemented by nsIHTMLEditor, since
-  //  pasting in a plaintext editor automatically only supplies
-  //  "unformatted" text
   HTMLEditor* htmlEditor = aTextEditor->AsHTMLEditor();
   if (!htmlEditor) {
     return false;
   }
   return htmlEditor->CanPaste(nsIClipboard::kGlobalClipboard);
 }
 
 nsresult PasteNoFormattingCommand::DoCommand(Command aCommand,
@@ -369,39 +368,39 @@ nsresult ListItemCommand::ToggleState(ns
 StaticRefPtr<RemoveListCommand> RemoveListCommand::sInstance;
 
 bool RemoveListCommand::IsCommandEnabled(Command aCommand,
                                          TextEditor* aTextEditor) const {
   if (!aTextEditor) {
     return false;
   }
 
-  if (!aTextEditor->IsSelectionEditable()) {
+  HTMLEditor* htmlEditor = aTextEditor->AsHTMLEditor();
+  if (!htmlEditor) {
+    return false;
+  }
+
+  if (!htmlEditor->IsSelectionEditable()) {
     return false;
   }
 
   // It is enabled if we are in any list type
-  HTMLEditor* htmlEditor = aTextEditor->AsHTMLEditor();
-  if (NS_WARN_IF(!htmlEditor)) {
-    return false;
-  }
-
   bool bMixed;
   nsAutoString localName;
   nsresult rv = GetListState(MOZ_KnownLive(htmlEditor), &bMixed, localName);
   if (NS_WARN_IF(NS_FAILED(rv))) {
     return false;
   }
   return bMixed || !localName.IsEmpty();
 }
 
 nsresult RemoveListCommand::DoCommand(Command aCommand,
                                       TextEditor& aTextEditor) const {
   HTMLEditor* htmlEditor = aTextEditor.AsHTMLEditor();
-  if (!htmlEditor) {
+  if (NS_WARN_IF(!htmlEditor)) {
     return NS_OK;
   }
   // This removes any list type
   return htmlEditor->RemoveList(EmptyString());
 }
 
 nsresult RemoveListCommand::DoCommandParams(Command aCommand,
                                             nsCommandParams* aParams,
@@ -422,23 +421,27 @@ nsresult RemoveListCommand::GetCommandSt
 
 StaticRefPtr<IndentCommand> IndentCommand::sInstance;
 
 bool IndentCommand::IsCommandEnabled(Command aCommand,
                                      TextEditor* aTextEditor) const {
   if (!aTextEditor) {
     return false;
   }
-  return aTextEditor->IsSelectionEditable();
+  HTMLEditor* htmlEditor = aTextEditor->AsHTMLEditor();
+  if (!htmlEditor) {
+    return false;
+  }
+  return htmlEditor->IsSelectionEditable();
 }
 
 nsresult IndentCommand::DoCommand(Command aCommand,
                                   TextEditor& aTextEditor) const {
   HTMLEditor* htmlEditor = aTextEditor.AsHTMLEditor();
-  if (!htmlEditor) {
+  if (NS_WARN_IF(!htmlEditor)) {
     return NS_OK;
   }
   nsresult rv = htmlEditor->IndentAsAction();
   if (NS_WARN_IF(NS_FAILED(rv))) {
     return rv;
   }
   return NS_OK;
 }
@@ -462,23 +465,27 @@ nsresult IndentCommand::GetCommandStateP
 
 StaticRefPtr<OutdentCommand> OutdentCommand::sInstance;
 
 bool OutdentCommand::IsCommandEnabled(Command aCommand,
                                       TextEditor* aTextEditor) const {
   if (!aTextEditor) {
     return false;
   }
-  return aTextEditor->IsSelectionEditable();
+  HTMLEditor* htmlEditor = aTextEditor->AsHTMLEditor();
+  if (!htmlEditor) {
+    return false;
+  }
+  return htmlEditor->IsSelectionEditable();
 }
 
 nsresult OutdentCommand::DoCommand(Command aCommand,
                                    TextEditor& aTextEditor) const {
   HTMLEditor* htmlEditor = aTextEditor.AsHTMLEditor();
-  if (!htmlEditor) {
+  if (NS_WARN_IF(!htmlEditor)) {
     return NS_OK;
   }
   nsresult rv = htmlEditor->OutdentAsAction();
   if (NS_WARN_IF(NS_FAILED(rv))) {
     return rv;
   }
   return NS_OK;
 }
@@ -500,18 +507,22 @@ nsresult OutdentCommand::GetCommandState
  * mozilla::MultiStateCommandBase
  *****************************************************************************/
 
 bool MultiStateCommandBase::IsCommandEnabled(Command aCommand,
                                              TextEditor* aTextEditor) const {
   if (!aTextEditor) {
     return false;
   }
+  HTMLEditor* htmlEditor = aTextEditor->AsHTMLEditor();
+  if (!htmlEditor) {
+    return false;
+  }
   // should be disabled sometimes, like if the current selection is an image
-  return aTextEditor->IsSelectionEditable();
+  return htmlEditor->IsSelectionEditable();
 }
 
 nsresult MultiStateCommandBase::DoCommand(Command aCommand,
                                           TextEditor& aTextEditor) const {
   NS_WARNING(
       "who is calling MultiStateCommandBase::DoCommand (no implementation)?");
   return NS_OK;
 }
@@ -1036,24 +1047,28 @@ nsresult IncreaseZIndexCommand::GetComma
 
 StaticRefPtr<RemoveStylesCommand> RemoveStylesCommand::sInstance;
 
 bool RemoveStylesCommand::IsCommandEnabled(Command aCommand,
                                            TextEditor* aTextEditor) const {
   if (!aTextEditor) {
     return false;
   }
+  HTMLEditor* htmlEditor = aTextEditor->AsHTMLEditor();
+  if (!htmlEditor) {
+    return false;
+  }
   // test if we have any styles?
-  return aTextEditor->IsSelectionEditable();
+  return htmlEditor->IsSelectionEditable();
 }
 
 nsresult RemoveStylesCommand::DoCommand(Command aCommand,
                                         TextEditor& aTextEditor) const {
   HTMLEditor* htmlEditor = aTextEditor.AsHTMLEditor();
-  if (!htmlEditor) {
+  if (NS_WARN_IF(!htmlEditor)) {
     return NS_OK;
   }
   return MOZ_KnownLive(htmlEditor)->RemoveAllInlineProperties();
 }
 
 nsresult RemoveStylesCommand::DoCommandParams(Command aCommand,
                                               nsCommandParams* aParams,
                                               TextEditor& aTextEditor) const {
@@ -1073,24 +1088,28 @@ nsresult RemoveStylesCommand::GetCommand
 
 StaticRefPtr<IncreaseFontSizeCommand> IncreaseFontSizeCommand::sInstance;
 
 bool IncreaseFontSizeCommand::IsCommandEnabled(Command aCommand,
                                                TextEditor* aTextEditor) const {
   if (!aTextEditor) {
     return false;
   }
+  HTMLEditor* htmlEditor = aTextEditor->AsHTMLEditor();
+  if (!htmlEditor) {
+    return false;
+  }
   // test if we are at max size?
-  return aTextEditor->IsSelectionEditable();
+  return htmlEditor->IsSelectionEditable();
 }
 
 nsresult IncreaseFontSizeCommand::DoCommand(Command aCommand,
                                             TextEditor& aTextEditor) const {
   HTMLEditor* htmlEditor = aTextEditor.AsHTMLEditor();
-  if (!htmlEditor) {
+  if (NS_WARN_IF(!htmlEditor)) {
     return NS_OK;
   }
   return MOZ_KnownLive(htmlEditor)->IncreaseFontSize();
 }
 
 nsresult IncreaseFontSizeCommand::DoCommandParams(
     Command aCommand, nsCommandParams* aParams, TextEditor& aTextEditor) const {
   return DoCommand(aCommand, aTextEditor);
@@ -1109,24 +1128,28 @@ nsresult IncreaseFontSizeCommand::GetCom
 
 StaticRefPtr<DecreaseFontSizeCommand> DecreaseFontSizeCommand::sInstance;
 
 bool DecreaseFontSizeCommand::IsCommandEnabled(Command aCommand,
                                                TextEditor* aTextEditor) const {
   if (!aTextEditor) {
     return false;
   }
+  HTMLEditor* htmlEditor = aTextEditor->AsHTMLEditor();
+  if (!htmlEditor) {
+    return false;
+  }
   // test if we are at min size?
-  return aTextEditor->IsSelectionEditable();
+  return htmlEditor->IsSelectionEditable();
 }
 
 nsresult DecreaseFontSizeCommand::DoCommand(Command aCommand,
                                             TextEditor& aTextEditor) const {
   HTMLEditor* htmlEditor = aTextEditor.AsHTMLEditor();
-  if (!htmlEditor) {
+  if (NS_WARN_IF(!htmlEditor)) {
     return NS_OK;
   }
   return MOZ_KnownLive(htmlEditor)->DecreaseFontSize();
 }
 
 nsresult DecreaseFontSizeCommand::DoCommandParams(
     Command aCommand, nsCommandParams* aParams, TextEditor& aTextEditor) const {
   return DoCommand(aCommand, aTextEditor);
@@ -1145,17 +1168,21 @@ nsresult DecreaseFontSizeCommand::GetCom
 
 StaticRefPtr<InsertHTMLCommand> InsertHTMLCommand::sInstance;
 
 bool InsertHTMLCommand::IsCommandEnabled(Command aCommand,
                                          TextEditor* aTextEditor) const {
   if (!aTextEditor) {
     return false;
   }
-  return aTextEditor->IsSelectionEditable();
+  HTMLEditor* htmlEditor = aTextEditor->AsHTMLEditor();
+  if (!htmlEditor) {
+    return false;
+  }
+  return htmlEditor->IsSelectionEditable();
 }
 
 nsresult InsertHTMLCommand::DoCommand(Command aCommand,
                                       TextEditor& aTextEditor) const {
   // If nsInsertHTMLCommand is called with no parameters, it was probably called
   // with an empty string parameter ''. In this case, it should act the same as
   // the delete command
   HTMLEditor* htmlEditor = aTextEditor.AsHTMLEditor();
@@ -1200,17 +1227,21 @@ nsresult InsertHTMLCommand::GetCommandSt
 
 StaticRefPtr<InsertTagCommand> InsertTagCommand::sInstance;
 
 bool InsertTagCommand::IsCommandEnabled(Command aCommand,
                                         TextEditor* aTextEditor) const {
   if (!aTextEditor) {
     return false;
   }
-  return aTextEditor->IsSelectionEditable();
+  HTMLEditor* htmlEditor = aTextEditor->AsHTMLEditor();
+  if (!htmlEditor) {
+    return false;
+  }
+  return htmlEditor->IsSelectionEditable();
 }
 
 // corresponding STATE_ATTRIBUTE is: src (img) and href (a)
 nsresult InsertTagCommand::DoCommand(Command aCommand,
                                      TextEditor& aTextEditor) const {
   nsAtom* tagName = GetTagName(aCommand);
   if (NS_WARN_IF(tagName != nsGkAtoms::hr)) {
     return NS_ERROR_NOT_IMPLEMENTED;
--- a/editor/libeditor/HTMLEditorDataTransfer.cpp
+++ b/editor/libeditor/HTMLEditorDataTransfer.cpp
@@ -1449,17 +1449,17 @@ bool HTMLEditor::HavePrivateHTMLFlavor(n
   return false;
 }
 
 nsresult HTMLEditor::PasteInternal(int32_t aClipboardType,
                                    bool aDispatchPasteEvent) {
   MOZ_ASSERT(IsEditActionDataAvailable());
 
   if (aDispatchPasteEvent && !FireClipboardEvent(ePaste, aClipboardType)) {
-    return NS_OK;
+    return NS_ERROR_EDITOR_ACTION_CANCELED;
   }
 
   // Get Clipboard Service
   nsresult rv;
   nsCOMPtr<nsIClipboard> clipboard =
       do_GetService("@mozilla.org/widget/clipboard;1", &rv);
   if (NS_WARN_IF(NS_FAILED(rv))) {
     return rv;
@@ -1541,17 +1541,17 @@ nsresult HTMLEditor::PasteTransferable(n
     return NS_ERROR_NOT_INITIALIZED;
   }
   editActionData.InitializeDataTransfer(aTransferable);
 
   // Use an invalid value for the clipboard type as data comes from
   // aTransferable and we don't currently implement a way to put that in the
   // data transfer yet.
   if (!FireClipboardEvent(ePaste, nsIClipboard::kGlobalClipboard)) {
-    return NS_OK;
+    return EditorBase::ToGenericNSResult(NS_ERROR_EDITOR_ACTION_CANCELED);
   }
 
   nsAutoString contextStr, infoStr;
   nsresult rv = InsertFromTransferable(aTransferable, nullptr, contextStr,
                                        infoStr, false, true);
   if (NS_WARN_IF(NS_FAILED(rv))) {
     return EditorBase::ToGenericNSResult(rv);
   }
@@ -1566,17 +1566,17 @@ HTMLEditor::PasteNoFormatting(int32_t aS
   AutoEditActionDataSetter editActionData(*this, EditAction::ePaste);
   if (NS_WARN_IF(!editActionData.CanHandle())) {
     return NS_ERROR_NOT_INITIALIZED;
   }
   editActionData.InitializeDataTransferWithClipboard(
       SettingDataTransfer::eWithoutFormat, aSelectionType);
 
   if (!FireClipboardEvent(ePasteNoFormatting, aSelectionType)) {
-    return NS_OK;
+    return EditorBase::ToGenericNSResult(NS_ERROR_EDITOR_ACTION_CANCELED);
   }
 
   CommitComposition();
 
   // Get Clipboard Service
   nsresult rv;
   nsCOMPtr<nsIClipboard> clipboard(
       do_GetService("@mozilla.org/widget/clipboard;1", &rv));
--- a/editor/libeditor/HTMLEditorDocumentCommands.cpp
+++ b/editor/libeditor/HTMLEditorDocumentCommands.cpp
@@ -34,31 +34,35 @@ namespace mozilla {
  *    for more than one of this type of command
  *    We check the input command param for different behavior
  *****************************************************************************/
 
 StaticRefPtr<SetDocumentStateCommand> SetDocumentStateCommand::sInstance;
 
 bool SetDocumentStateCommand::IsCommandEnabled(Command aCommand,
                                                TextEditor* aTextEditor) const {
-  // These commands are always enabled
-  return true;
+  // These commands are always enabled if given editor is an HTMLEditor.
+  return aTextEditor && aTextEditor->AsHTMLEditor();
 }
 
 nsresult SetDocumentStateCommand::DoCommand(Command aCommand,
                                             TextEditor& aTextEditor) const {
   return NS_ERROR_NOT_IMPLEMENTED;
 }
 
 nsresult SetDocumentStateCommand::DoCommandParams(
     Command aCommand, nsCommandParams* aParams, TextEditor& aTextEditor) const {
   if (NS_WARN_IF(!aParams)) {
     return NS_ERROR_INVALID_ARG;
   }
 
+  if (NS_WARN_IF(!aTextEditor.AsHTMLEditor())) {
+    return NS_ERROR_FAILURE;
+  }
+
   switch (aCommand) {
     case Command::SetDocumentModified: {
       ErrorResult error;
       bool modified = aParams->GetBool(STATE_ATTRIBUTE, error);
       // Should we fail if this param wasn't set?
       // I'm not sure we should be that strict
       if (NS_WARN_IF(error.Failed())) {
         return error.StealNSResult();
@@ -212,16 +216,21 @@ nsresult SetDocumentStateCommand::GetCom
   // If the result is set to STATE_ATTRIBUTE as CString value,
   // queryCommandValue() returns the string value.
   // Otherwise, ignored.
 
   // The base editor owns most state info
   if (NS_WARN_IF(!aTextEditor)) {
     return NS_ERROR_INVALID_ARG;
   }
+
+  if (NS_WARN_IF(!aTextEditor->AsHTMLEditor())) {
+    return NS_ERROR_FAILURE;
+  }
+
   // Always get the enabled state
   nsresult rv =
       aParams.SetBool(STATE_ENABLED, IsCommandEnabled(aCommand, aTextEditor));
   if (NS_WARN_IF(NS_FAILED(rv))) {
     return rv;
   }
 
   switch (aCommand) {
--- a/editor/libeditor/TextEditor.cpp
+++ b/editor/libeditor/TextEditor.cpp
@@ -1783,17 +1783,18 @@ TextEditor::Cut() {
   bool actionTaken = false;
   if (FireClipboardEvent(eCut, nsIClipboard::kGlobalClipboard, &actionTaken)) {
     // XXX This transaction name is referred by PlaceholderTransaction::Merge()
     //     so that we need to keep using it here.
     AutoPlaceholderBatch treatAsOneTransaction(*this,
                                                *nsGkAtoms::DeleteTxnName);
     DeleteSelectionAsSubAction(eNone, eStrip);
   }
-  return actionTaken ? NS_OK : NS_ERROR_FAILURE;
+  return EditorBase::ToGenericNSResult(
+      actionTaken ? NS_OK : NS_ERROR_EDITOR_ACTION_CANCELED);
 }
 
 bool TextEditor::CanCut() const {
   AutoEditActionDataSetter editActionData(*this, EditAction::eNotEditing);
   if (NS_WARN_IF(!editActionData.CanHandle())) {
     return false;
   }
 
@@ -1811,17 +1812,18 @@ TextEditor::Copy() {
   AutoEditActionDataSetter editActionData(*this, EditAction::eCopy);
   if (NS_WARN_IF(!editActionData.CanHandle())) {
     return NS_ERROR_NOT_INITIALIZED;
   }
 
   bool actionTaken = false;
   FireClipboardEvent(eCopy, nsIClipboard::kGlobalClipboard, &actionTaken);
 
-  return actionTaken ? NS_OK : NS_ERROR_FAILURE;
+  return EditorBase::ToGenericNSResult(
+      actionTaken ? NS_OK : NS_ERROR_EDITOR_ACTION_CANCELED);
 }
 
 bool TextEditor::CanCopy() const {
   AutoEditActionDataSetter editActionData(*this, EditAction::eNotEditing);
   if (NS_WARN_IF(!editActionData.CanHandle())) {
     return false;
   }
 
--- a/editor/libeditor/TextEditorDataTransfer.cpp
+++ b/editor/libeditor/TextEditorDataTransfer.cpp
@@ -373,17 +373,17 @@ nsresult TextEditor::PasteAsAction(int32
                       ->PasteInternal(aClipboardType, aDispatchPasteEvent);
     if (NS_WARN_IF(NS_FAILED(rv))) {
       return EditorBase::ToGenericNSResult(rv);
     }
     return NS_OK;
   }
 
   if (aDispatchPasteEvent && !FireClipboardEvent(ePaste, aClipboardType)) {
-    return NS_OK;
+    return EditorBase::ToGenericNSResult(NS_ERROR_EDITOR_ACTION_CANCELED);
   }
 
   // Get Clipboard Service
   nsresult rv;
   nsCOMPtr<nsIClipboard> clipboard =
       do_GetService("@mozilla.org/widget/clipboard;1", &rv);
   if (NS_WARN_IF(NS_FAILED(rv))) {
     return rv;
@@ -420,17 +420,17 @@ TextEditor::PasteTransferable(nsITransfe
   if (NS_WARN_IF(!editActionData.CanHandle())) {
     return NS_ERROR_NOT_INITIALIZED;
   }
 
   // Use an invalid value for the clipboard type as data comes from
   // aTransferable and we don't currently implement a way to put that in the
   // data transfer yet.
   if (!FireClipboardEvent(ePaste, -1)) {
-    return NS_OK;
+    return EditorBase::ToGenericNSResult(NS_ERROR_EDITOR_ACTION_CANCELED);
   }
 
   if (!IsModifiable()) {
     return NS_OK;
   }
 
   nsresult rv = InsertTextFromTransferable(aTransferable);
   if (NS_WARN_IF(NS_FAILED(rv))) {
--- a/gfx/thebes/gfxFont.cpp
+++ b/gfx/thebes/gfxFont.cpp
@@ -177,19 +177,20 @@ void gfxFontCache::Shutdown() {
 
 gfxFontCache::gfxFontCache(nsIEventTarget* aEventTarget)
     : gfxFontCacheExpirationTracker(aEventTarget) {
   nsCOMPtr<nsIObserverService> obs = GetObserverService();
   if (obs) {
     obs->AddObserver(new Observer, "memory-pressure", false);
   }
 
-#ifndef RELEASE_OR_BETA
+#ifdef EARLY_BETA_OR_EARLIER
   // Currently disabled for release builds, due to unexplained crashes
   // during expiration; see bug 717175 & 894798.
+  // Bug 1548661: enabled for early beta, to see what crash-stats shows.
   nsIEventTarget* target = nullptr;
   if (XRE_IsContentProcess() && NS_IsMainThread()) {
     target = aEventTarget;
   }
   NS_NewTimerWithFuncCallback(getter_AddRefs(mWordCacheExpirationTimer),
                               WordCacheExpirationTimerCallback, this,
                               SHAPED_WORD_TIMEOUT_SECONDS * 1000,
                               nsITimer::TYPE_REPEATING_SLACK,
--- a/image/ClippedImage.cpp
+++ b/image/ClippedImage.cpp
@@ -209,24 +209,22 @@ ClippedImage::GetIntrinsicSize(nsSize* a
   if (!ShouldClip()) {
     return InnerImage()->GetIntrinsicSize(aSize);
   }
 
   *aSize = nsSize(mClip.Width(), mClip.Height());
   return NS_OK;
 }
 
-NS_IMETHODIMP
-ClippedImage::GetIntrinsicRatio(nsSize* aRatio) {
+Maybe<AspectRatio> ClippedImage::GetIntrinsicRatio() {
   if (!ShouldClip()) {
-    return InnerImage()->GetIntrinsicRatio(aRatio);
+    return InnerImage()->GetIntrinsicRatio();
   }
 
-  *aRatio = nsSize(mClip.Width(), mClip.Height());
-  return NS_OK;
+  return Some(AspectRatio::FromSize(mClip.Width(), mClip.Height()));
 }
 
 NS_IMETHODIMP_(already_AddRefed<SourceSurface>)
 ClippedImage::GetFrame(uint32_t aWhichFrame, uint32_t aFlags) {
   ImgDrawResult result;
   RefPtr<SourceSurface> surface;
   Tie(result, surface) =
       GetFrameInternal(mClip.Size(), Nothing(), aWhichFrame, aFlags, 1.0);
--- a/image/ClippedImage.h
+++ b/image/ClippedImage.h
@@ -29,17 +29,17 @@ class ClippedImage : public ImageWrapper
   typedef gfx::SourceSurface SourceSurface;
 
  public:
   NS_INLINE_DECL_REFCOUNTING_INHERITED(ClippedImage, ImageWrapper)
 
   NS_IMETHOD GetWidth(int32_t* aWidth) override;
   NS_IMETHOD GetHeight(int32_t* aHeight) override;
   NS_IMETHOD GetIntrinsicSize(nsSize* aSize) override;
-  NS_IMETHOD GetIntrinsicRatio(nsSize* aRatio) override;
+  Maybe<AspectRatio> GetIntrinsicRatio() override;
   NS_IMETHOD_(already_AddRefed<SourceSurface>)
   GetFrame(uint32_t aWhichFrame, uint32_t aFlags) override;
   NS_IMETHOD_(already_AddRefed<SourceSurface>)
   GetFrameAtSize(const gfx::IntSize& aSize, uint32_t aWhichFrame,
                  uint32_t aFlags) override;
   NS_IMETHOD_(bool)
   IsImageContainerAvailable(layers::LayerManager* aManager,
                             uint32_t aFlags) override;
--- a/image/DynamicImage.cpp
+++ b/image/DynamicImage.cpp
@@ -99,21 +99,19 @@ size_t DynamicImage::GetNativeSizesLengt
 
 NS_IMETHODIMP
 DynamicImage::GetIntrinsicSize(nsSize* aSize) {
   IntSize intSize(mDrawable->Size());
   *aSize = nsSize(intSize.width, intSize.height);
   return NS_OK;
 }
 
-NS_IMETHODIMP
-DynamicImage::GetIntrinsicRatio(nsSize* aSize) {
-  IntSize intSize(mDrawable->Size());
-  *aSize = nsSize(intSize.width, intSize.height);
-  return NS_OK;
+Maybe<AspectRatio> DynamicImage::GetIntrinsicRatio() {
+  auto size = mDrawable->Size();
+  return Some(AspectRatio::FromSize(size.width, size.height));
 }
 
 NS_IMETHODIMP_(Orientation)
 DynamicImage::GetOrientation() { return Orientation(); }
 
 NS_IMETHODIMP
 DynamicImage::GetType(uint16_t* aType) {
   *aType = imgIContainer::TYPE_RASTER;
--- a/image/ImageWrapper.cpp
+++ b/image/ImageWrapper.cpp
@@ -115,19 +115,18 @@ size_t ImageWrapper::GetNativeSizesLengt
   return mInnerImage->GetNativeSizesLength();
 }
 
 NS_IMETHODIMP
 ImageWrapper::GetIntrinsicSize(nsSize* aSize) {
   return mInnerImage->GetIntrinsicSize(aSize);
 }
 
-NS_IMETHODIMP
-ImageWrapper::GetIntrinsicRatio(nsSize* aSize) {
-  return mInnerImage->GetIntrinsicRatio(aSize);
+Maybe<AspectRatio> ImageWrapper::GetIntrinsicRatio() {
+  return mInnerImage->GetIntrinsicRatio();
 }
 
 NS_IMETHODIMP_(Orientation)
 ImageWrapper::GetOrientation() { return mInnerImage->GetOrientation(); }
 
 NS_IMETHODIMP
 ImageWrapper::GetType(uint16_t* aType) { return mInnerImage->GetType(aType); }
 
--- a/image/OrientedImage.cpp
+++ b/image/OrientedImage.cpp
@@ -62,25 +62,22 @@ OrientedImage::GetIntrinsicSize(nsSize* 
 
   if (mOrientation.SwapsWidthAndHeight()) {
     swap(aSize->width, aSize->height);
   }
 
   return rv;
 }
 
-NS_IMETHODIMP
-OrientedImage::GetIntrinsicRatio(nsSize* aRatio) {
-  nsresult rv = InnerImage()->GetIntrinsicRatio(aRatio);
-
-  if (mOrientation.SwapsWidthAndHeight()) {
-    swap(aRatio->width, aRatio->height);
+Maybe<AspectRatio> OrientedImage::GetIntrinsicRatio() {
+  Maybe<AspectRatio> ratio = InnerImage()->GetIntrinsicRatio();
+  if (ratio && mOrientation.SwapsWidthAndHeight()) {
+    ratio = Some(ratio->Inverted());
   }
-
-  return rv;
+  return ratio;
 }
 
 NS_IMETHODIMP_(already_AddRefed<SourceSurface>)
 OrientedImage::GetFrame(uint32_t aWhichFrame, uint32_t aFlags) {
   nsresult rv;
 
   if (mOrientation.IsIdentity()) {
     return InnerImage()->GetFrame(aWhichFrame, aFlags);
--- a/image/OrientedImage.h
+++ b/image/OrientedImage.h
@@ -26,17 +26,17 @@ class OrientedImage : public ImageWrappe
 
  public:
   NS_INLINE_DECL_REFCOUNTING_INHERITED(OrientedImage, ImageWrapper)
 
   NS_IMETHOD GetWidth(int32_t* aWidth) override;
   NS_IMETHOD GetHeight(int32_t* aHeight) override;
   nsresult GetNativeSizes(nsTArray<gfx::IntSize>& aNativeSizes) const override;
   NS_IMETHOD GetIntrinsicSize(nsSize* aSize) override;
-  NS_IMETHOD GetIntrinsicRatio(nsSize* aRatio) override;
+  Maybe<AspectRatio> GetIntrinsicRatio() override;
   NS_IMETHOD_(already_AddRefed<SourceSurface>)
   GetFrame(uint32_t aWhichFrame, uint32_t aFlags) override;
   NS_IMETHOD_(already_AddRefed<SourceSurface>)
   GetFrameAtSize(const gfx::IntSize& aSize, uint32_t aWhichFrame,
                  uint32_t aFlags) override;
   NS_IMETHOD_(bool)
   IsImageContainerAvailable(layers::LayerManager* aManager,
                             uint32_t aFlags) override;
--- a/image/RasterImage.cpp
+++ b/image/RasterImage.cpp
@@ -249,24 +249,22 @@ RasterImage::GetIntrinsicSize(nsSize* aS
   }
 
   *aSize = nsSize(nsPresContext::CSSPixelsToAppUnits(mSize.width),
                   nsPresContext::CSSPixelsToAppUnits(mSize.height));
   return NS_OK;
 }
 
 //******************************************************************************
-NS_IMETHODIMP
-RasterImage::GetIntrinsicRatio(nsSize* aRatio) {
+Maybe<AspectRatio> RasterImage::GetIntrinsicRatio() {
   if (mError) {
-    return NS_ERROR_FAILURE;
+    return Nothing();
   }
 
-  *aRatio = nsSize(mSize.width, mSize.height);
-  return NS_OK;
+  return Some(AspectRatio::FromSize(mSize.width, mSize.height));
 }
 
 NS_IMETHODIMP_(Orientation)
 RasterImage::GetOrientation() { return mOrientation; }
 
 //******************************************************************************
 NS_IMETHODIMP
 RasterImage::GetType(uint16_t* aType) {
--- a/image/VectorImage.cpp
+++ b/image/VectorImage.cpp
@@ -630,29 +630,27 @@ VectorImage::GetIntrinsicSize(nsSize* aS
   }
   if (rfSize.height) {
     aSize->height = *rfSize.height;
   }
   return NS_OK;
 }
 
 //******************************************************************************
-NS_IMETHODIMP
-VectorImage::GetIntrinsicRatio(nsSize* aRatio) {
+Maybe<AspectRatio> VectorImage::GetIntrinsicRatio() {
   if (mError || !mIsFullyLoaded) {
-    return NS_ERROR_FAILURE;
+    return Nothing();
   }
 
   nsIFrame* rootFrame = mSVGDocumentWrapper->GetRootLayoutFrame();
   if (!rootFrame) {
-    return NS_ERROR_FAILURE;
+    return Nothing();
   }
 
-  *aRatio = rootFrame->GetIntrinsicRatio();
-  return NS_OK;
+  return Some(rootFrame->GetIntrinsicRatio());
 }
 
 NS_IMETHODIMP_(Orientation)
 VectorImage::GetOrientation() { return Orientation(); }
 
 //******************************************************************************
 NS_IMETHODIMP
 VectorImage::GetType(uint16_t* aType) {
--- a/image/imgIContainer.idl
+++ b/image/imgIContainer.idl
@@ -9,16 +9,17 @@
 webidl Document;
 
 %{C++
 #include "ImgDrawResult.h"
 #include "gfxContext.h"
 #include "gfxMatrix.h"
 #include "gfxRect.h"
 #include "mozilla/gfx/2D.h"
+#include "mozilla/AspectRatio.h"
 #include "mozilla/Maybe.h"
 #include "mozilla/RefPtr.h"
 #include "nsRect.h"
 #include "nsSize.h"
 #include "limits.h"
 
 namespace mozilla {
 namespace layers {
@@ -40,16 +41,17 @@ namespace image {
 class ImageRegion;
 struct Orientation;
 
 }
 }
 
 %}
 
+native MaybeAspectRatio(mozilla::Maybe<mozilla::AspectRatio>);
 native ImgDrawResult(mozilla::image::ImgDrawResult);
 [ptr] native gfxContext(gfxContext);
 [ref] native gfxMatrix(gfxMatrix);
 [ref] native gfxRect(gfxRect);
 [ref] native gfxSize(gfxSize);
 native SamplingFilter(mozilla::gfx::SamplingFilter);
 [ref] native nsIntRect(nsIntRect);
 native nsIntRectByVal(nsIntRect);
@@ -94,19 +96,19 @@ interface imgIContainer : nsISupports
    * The intrinsic size of this image in appunits. If the image has no intrinsic
    * size in a dimension, -1 will be returned for that dimension. In the case of
    * any error, an exception will be thrown.
    */
   [noscript] readonly attribute nsSize intrinsicSize;
 
   /**
    * The (dimensionless) intrinsic ratio of this image. In the case of any
-   * error, an exception will be thrown.
+   * error, Nothing() will be returned.
    */
-  [noscript] readonly attribute nsSize intrinsicRatio;
+  [notxpcom, nostdcall] readonly attribute MaybeAspectRatio intrinsicRatio;
 
   /**
    * Given a size at which this image will be displayed, and the drawing
    * parameters affecting how it will be drawn, returns the image size which
    * should be used to draw to produce the highest quality result. This is the
    * appropriate size, for example, to use as an input to the pixel snapping
    * algorithm.
    *
new file mode 100644
--- /dev/null
+++ b/js/src/jit-test/tests/ion/bug1544792.js
@@ -0,0 +1,13 @@
+var res = undefined;
+function X() {
+    try {
+        foobar();
+    } catch (e) {
+        res = this.hasOwnProperty("prop");
+    }
+    this.prop = 1;
+}
+for (var i = 0; i < 50; i++) {
+    new X();
+    assertEq(res, false);
+}
new file mode 100644
--- /dev/null
+++ b/js/src/jit-test/tests/ion/bug1546228.js
@@ -0,0 +1,10 @@
+function Obj() {
+    this.a = 1;
+}
+Obj.prototype = this;
+
+function test() {
+    return o.a;
+}
+var o = new Obj();
+test();
--- a/js/src/jit/BaselineCompiler.cpp
+++ b/js/src/jit/BaselineCompiler.cpp
@@ -26,16 +26,17 @@
 #include "vm/EnvironmentObject.h"
 #include "vm/Interpreter.h"
 #include "vm/JSFunction.h"
 #include "vm/TraceLogging.h"
 #include "vtune/VTuneWrapper.h"
 
 #include "jit/BaselineFrameInfo-inl.h"
 #include "jit/MacroAssembler-inl.h"
+#include "jit/SharedICHelpers-inl.h"
 #include "jit/VMFunctionList-inl.h"
 #include "vm/Interpreter-inl.h"
 #include "vm/JSScript-inl.h"
 #include "vm/NativeObject-inl.h"
 #include "vm/TypeInference-inl.h"
 
 using namespace js;
 using namespace js::jit;
@@ -5654,17 +5655,19 @@ bool BaselineCodeGen<Handler>::emit_JSOP
   }
 
   masm.loadValue(frame.addressOfReturnValue(), JSReturnOperand);
   return emitReturn();
 }
 
 template <>
 void BaselineCompilerCodeGen::emitJumpToInterpretOpLabel() {
-  MOZ_CRASH("NYI: Interpreter emitJumpToInterpretOpLabel");
+  TrampolinePtr code =
+      cx->runtime()->jitRuntime()->baselineInterpreter().interpretOpAddr();
+  masm.jump(code);
 }
 
 template <>
 void BaselineInterpreterCodeGen::emitJumpToInterpretOpLabel() {
   masm.jump(handler.interpretOpLabel());
 }
 
 template <typename Handler>
@@ -6536,13 +6539,89 @@ MethodStatus BaselineCompiler::emitBody(
     prevpc = handler.pc();
 #endif
   }
 
   MOZ_ASSERT(JSOp(*prevpc) == JSOP_RETRVAL);
   return Method_Compiled;
 }
 
+JitCode* JitRuntime::generateDebugTrapHandler(JSContext* cx) {
+  StackMacroAssembler masm;
+
+  AllocatableGeneralRegisterSet regs(GeneralRegisterSet::All());
+  regs.takeUnchecked(BaselineFrameReg);
+  regs.takeUnchecked(ICStubReg);
+  Register scratch1 = regs.takeAny();
+  Register scratch2 = regs.takeAny();
+  Register scratch3 = regs.takeAny();
+
+  // Load the return address in scratch1.
+  masm.loadAbiReturnAddress(scratch1);
+
+  // Load BaselineFrame pointer in scratch2.
+  masm.loadBaselineFramePtr(BaselineFrameReg, scratch2);
+
+  // Enter a stub frame and call the HandleDebugTrap VM function. Ensure
+  // the stub frame has a nullptr ICStub pointer, since this pointer is marked
+  // during GC.
+  masm.movePtr(ImmPtr(nullptr), ICStubReg);
+  EmitBaselineEnterStubFrame(masm, scratch3);
+
+  using Fn = bool (*)(JSContext*, BaselineFrame*, uint8_t*, bool*);
+  VMFunctionId id = VMFunctionToId<Fn, jit::HandleDebugTrap>::id;
+  TrampolinePtr code = cx->runtime()->jitRuntime()->getVMWrapper(id);
+
+  masm.push(scratch1);
+  masm.push(scratch2);
+  EmitBaselineCallVM(code, masm);
+
+  EmitBaselineLeaveStubFrame(masm);
+
+  // If the stub returns |true|, we have to perform a forced return
+  // (return from the JS frame). If the stub returns |false|, just return
+  // from the trap stub so that execution continues at the current pc.
+  Label forcedReturn;
+  masm.branchIfTrueBool(ReturnReg, &forcedReturn);
+  masm.abiret();
+
+  masm.bind(&forcedReturn);
+  masm.loadValue(
+      Address(BaselineFrameReg, BaselineFrame::reverseOffsetOfReturnValue()),
+      JSReturnOperand);
+  masm.moveToStackPtr(BaselineFrameReg);
+  masm.pop(BaselineFrameReg);
+
+  // Before returning, if profiling is turned on, make sure that
+  // lastProfilingFrame is set to the correct caller frame.
+  {
+    Label skipProfilingInstrumentation;
+    AbsoluteAddress addressOfEnabled(
+        cx->runtime()->geckoProfiler().addressOfEnabled());
+    masm.branch32(Assembler::Equal, addressOfEnabled, Imm32(0),
+                  &skipProfilingInstrumentation);
+    masm.profilerExitFrame();
+    masm.bind(&skipProfilingInstrumentation);
+  }
+
+  masm.ret();
+
+  Linker linker(masm, "DebugTrapHandler");
+  JitCode* handlerCode = linker.newCode(cx, CodeKind::Other);
+  if (!handlerCode) {
+    return nullptr;
+  }
+
+#ifdef JS_ION_PERF
+  writePerfSpewerJitCodeProfile(handlerCode, "DebugTrapHandler");
+#endif
+#ifdef MOZ_VTUNE
+  vtune::MarkStub(handlerCode, "DebugTrapHandler");
+#endif
+
+  return handlerCode;
+}
+
 // Instantiate explicitly for now to make sure it compiles.
 template class jit::BaselineCodeGen<BaselineInterpreterHandler>;
 
 }  // namespace jit
 }  // namespace js
--- a/js/src/jit/BaselineJIT.cpp
+++ b/js/src/jit/BaselineJIT.cpp
@@ -146,17 +146,19 @@ JitExecStatus jit::EnterBaselineAtBranch
 
     // Skip debug breakpoint/trap handler, the interpreter already handled it
     // for the current op.
     if (fp->isDebuggee()) {
       MOZ_RELEASE_ASSERT(baseline->hasDebugInstrumentation());
       data.jitcode += MacroAssembler::ToggledCallSize(data.jitcode);
     }
   } else {
-    MOZ_CRASH("NYI: Interpreter executeOp code");
+    const BaselineInterpreter& interp =
+        cx->runtime()->jitRuntime()->baselineInterpreter();
+    data.jitcode = interp.interpretOpAddr().value;
   }
 
   // Note: keep this in sync with SetEnterJitData.
 
   data.osrFrame = fp;
   data.osrNumStackValues =
       fp->script()->nfixed() + cx->interpreterRegs().stackDepth();
 
@@ -1075,40 +1077,84 @@ void BaselineScript::toggleTraceLoggerEn
   }
 
 #  if DEBUG
   traceLoggerEngineEnabled_ = enable;
 #  endif
 }
 #endif
 
+static void ToggleProfilerInstrumentation(JitCode* code,
+                                          uint32_t profilerEnterToggleOffset,
+                                          uint32_t profilerExitToggleOffset,
+                                          bool enable) {
+  CodeLocationLabel enterToggleLocation(code,
+                                        CodeOffset(profilerEnterToggleOffset));
+  CodeLocationLabel exitToggleLocation(code,
+                                       CodeOffset(profilerExitToggleOffset));
+  if (enable) {
+    Assembler::ToggleToCmp(enterToggleLocation);
+    Assembler::ToggleToCmp(exitToggleLocation);
+  } else {
+    Assembler::ToggleToJmp(enterToggleLocation);
+    Assembler::ToggleToJmp(exitToggleLocation);
+  }
+}
+
 void BaselineScript::toggleProfilerInstrumentation(bool enable) {
   if (enable == isProfilerInstrumentationOn()) {
     return;
   }
 
   JitSpew(JitSpew_BaselineIC, "  toggling profiling %s for BaselineScript %p",
           enable ? "on" : "off", this);
 
-  // Toggle the jump
-  CodeLocationLabel enterToggleLocation(method_,
-                                        CodeOffset(profilerEnterToggleOffset_));
-  CodeLocationLabel exitToggleLocation(method_,
-                                       CodeOffset(profilerExitToggleOffset_));
+  ToggleProfilerInstrumentation(method_, profilerEnterToggleOffset_,
+                                profilerExitToggleOffset_, enable);
+
   if (enable) {
-    Assembler::ToggleToCmp(enterToggleLocation);
-    Assembler::ToggleToCmp(exitToggleLocation);
     flags_ |= uint32_t(PROFILER_INSTRUMENTATION_ON);
   } else {
-    Assembler::ToggleToJmp(enterToggleLocation);
-    Assembler::ToggleToJmp(exitToggleLocation);
     flags_ &= ~uint32_t(PROFILER_INSTRUMENTATION_ON);
   }
 }
 
+void BaselineInterpreter::toggleProfilerInstrumentation(bool enable) {
+  if (!JitOptions.baselineInterpreter) {
+    return;
+  }
+
+  AutoWritableJitCode awjc(code_);
+  ToggleProfilerInstrumentation(code_, profilerEnterToggleOffset_,
+                                profilerExitToggleOffset_, enable);
+}
+
+void BaselineInterpreter::toggleDebuggerInstrumentation(bool enable) {
+  if (!JitOptions.baselineInterpreter) {
+    return;
+  }
+
+  AutoWritableJitCode awjc(code_);
+
+  // Toggle prologue IsDebuggeeCheck code.
+  CodeLocationLabel debuggeeCheckLocation(code_,
+                                          CodeOffset(debuggeeCheckOffset_));
+  if (enable) {
+    Assembler::ToggleToCmp(debuggeeCheckLocation);
+  } else {
+    Assembler::ToggleToJmp(debuggeeCheckLocation);
+  }
+
+  // Toggle DebugTrapHandler calls.
+  for (uint32_t offset : debugTrapOffsets_) {
+    CodeLocationLabel trapLocation(code_, CodeOffset(offset));
+    Assembler::ToggleCall(trapLocation, enable);
+  }
+}
+
 void ICScript::purgeOptimizedStubs(JSScript* script) {
   MOZ_ASSERT(script->icScript() == this);
 
   Zone* zone = script->zone();
   if (zone->isGCSweeping() && IsAboutToBeFinalizedDuringSweep(*script)) {
     // We're sweeping and the script is dead. Don't purge optimized stubs
     // because (1) accessing CacheIRStubInfo pointers in ICStubs is invalid
     // because we may have swept them already when we started (incremental)
@@ -1272,16 +1318,18 @@ void jit::AddSizeOfBaselineData(JSScript
 }
 
 void jit::ToggleBaselineProfiling(JSRuntime* runtime, bool enable) {
   JitRuntime* jrt = runtime->jitRuntime();
   if (!jrt) {
     return;
   }
 
+  jrt->baselineInterpreter().toggleProfilerInstrumentation(enable);
+
   for (ZonesIter zone(runtime, SkipAtoms); !zone.done(); zone.next()) {
     for (auto script = zone->cellIter<JSScript>(); !script.done();
          script.next()) {
       if (!script->hasBaselineScript()) {
         continue;
       }
       AutoWritableJitCode awjc(script->baselineScript()->method());
       script->baselineScript()->toggleProfilerInstrumentation(enable);
@@ -1360,8 +1408,31 @@ void jit::MarkActiveTypeScripts(Zone* zo
   }
   JSContext* cx = TlsContext.get();
   for (JitActivationIterator iter(cx); !iter.done(); ++iter) {
     if (iter->compartment()->zone() == zone) {
       MarkActiveTypeScripts(cx, iter);
     }
   }
 }
+
+void BaselineInterpreter::init(JitCode* code, uint32_t interpretOpOffset,
+                               uint32_t profilerEnterToggleOffset,
+                               uint32_t profilerExitToggleOffset,
+                               uint32_t debuggeeCheckOffset,
+                               DebugTrapOffsets&& debugTrapOffsets) {
+  code_ = code;
+  interpretOpOffset_ = interpretOpOffset;
+  profilerEnterToggleOffset_ = profilerEnterToggleOffset;
+  profilerExitToggleOffset_ = profilerExitToggleOffset;
+  debuggeeCheckOffset_ = debuggeeCheckOffset;
+  debugTrapOffsets_ = std::move(debugTrapOffsets);
+}
+
+bool jit::GenerateBaselineInterpreter(JSContext* cx,
+                                      BaselineInterpreter& interpreter) {
+  // Temporary JitOptions check to prevent crashes for now.
+  if (JitOptions.baselineInterpreter) {
+    MOZ_CRASH("NYI: GenerateBaselineInterpreter");
+  }
+
+  return true;
+}
--- a/js/src/jit/BaselineJIT.h
+++ b/js/src/jit/BaselineJIT.h
@@ -646,16 +646,61 @@ MethodStatus BaselineCompile(JSContext* 
                              bool forceDebugInstrumentation = false);
 
 #ifdef JS_STRUCTURED_SPEW
 void JitSpewBaselineICStats(JSScript* script, const char* dumpReason);
 #endif
 
 static const unsigned BASELINE_MAX_ARGS_LENGTH = 20000;
 
+// Class storing the generated Baseline Interpreter code for the runtime.
+class BaselineInterpreter {
+  // The interpreter code.
+  JitCode* code_ = nullptr;
+
+  // Offset of the code to start interpreting a bytecode op.
+  uint32_t interpretOpOffset_ = 0;
+
+  // The offsets for the toggledJump instructions for profiler instrumentation.
+  uint32_t profilerEnterToggleOffset_ = 0;
+  uint32_t profilerExitToggleOffset_ = 0;
+
+  // The offset for the toggledJump instruction for the debugger's
+  // IsDebuggeeCheck code in the prologue.
+  uint32_t debuggeeCheckOffset_ = 0;
+
+  // Offsets of toggled calls to the DebugTrapHandler trampoline (for
+  // breakpoints and stepping).
+  using DebugTrapOffsets = js::Vector<uint32_t, 0, SystemAllocPolicy>;
+  DebugTrapOffsets debugTrapOffsets_;
+
+ public:
+  BaselineInterpreter() = default;
+
+  BaselineInterpreter(const BaselineInterpreter&) = delete;
+  void operator=(const BaselineInterpreter&) = delete;
+
+  void init(JitCode* code, uint32_t interpretOpOffset,
+            uint32_t profilerEnterToggleOffset,
+            uint32_t profilerExitToggleOffset, uint32_t debuggeeCheckOffset,
+            DebugTrapOffsets&& debugTrapOffsets);
+
+  uint8_t* codeRaw() const { return code_->raw(); }
+
+  TrampolinePtr interpretOpAddr() const {
+    return TrampolinePtr(codeRaw() + interpretOpOffset_);
+  }
+
+  void toggleProfilerInstrumentation(bool enable);
+  void toggleDebuggerInstrumentation(bool enable);
+};
+
+MOZ_MUST_USE bool GenerateBaselineInterpreter(JSContext* cx,
+                                              BaselineInterpreter& interpreter);
+
 }  // namespace jit
 }  // namespace js
 
 namespace JS {
 
 template <>
 struct DeletePolicy<js::jit::BaselineScript> {
   explicit DeletePolicy(JSRuntime* rt) : rt_(rt) {}
--- a/js/src/jit/Ion.cpp
+++ b/js/src/jit/Ion.cpp
@@ -161,16 +161,17 @@ JitRuntime::JitRuntime()
       argumentsRectifierOffset_(0),
       argumentsRectifierReturnOffset_(0),
       invalidatorOffset_(0),
       lazyLinkStubOffset_(0),
       interpreterStubOffset_(0),
       doubleToInt32ValueStubOffset_(0),
       debugTrapHandler_(nullptr),
       baselineDebugModeOSRHandler_(nullptr),
+      baselineInterpreter_(),
       trampolineCode_(nullptr),
       jitcodeGlobalTable_(nullptr),
 #ifdef DEBUG
       ionBailAfter_(0),
 #endif
       numFinishedBuilders_(0),
       ionLazyLinkListSize_(0) {
 }
@@ -208,16 +209,20 @@ bool JitRuntime::initialize(JSContext* c
     return false;
   }
 
   jitcodeGlobalTable_ = cx->new_<JitcodeGlobalTable>();
   if (!jitcodeGlobalTable_) {
     return false;
   }
 
+  if (!GenerateBaselineInterpreter(cx, baselineInterpreter_)) {
+    return false;
+  }
+
   return true;
 }
 
 bool JitRuntime::generateTrampolines(JSContext* cx) {
   StackMacroAssembler masm;
 
   Label bailoutTail;
   JitSpew(JitSpew_Codegen, "# Emitting bailout tail stub");
--- a/js/src/jit/IonBuilder.cpp
+++ b/js/src/jit/IonBuilder.cpp
@@ -3199,21 +3199,20 @@ AbortReasonOr<Ok> IonBuilder::visitCondS
 
 AbortReasonOr<Ok> IonBuilder::visitTry(CFGTry* try_) {
   // We don't support try-finally. The ControlFlowGenerator should have
   // aborted compilation in this case.
 
   // Try-catch within inline frames is not yet supported.
   MOZ_ASSERT(!isInlineBuilder());
 
-  // Try-catch during the arguments usage analysis is not yet supported. Code
-  // accessing the arguments within the 'catch' block is not accounted for.
-  if (info().analysisMode() == Analysis_ArgumentsUsage) {
-    return abort(AbortReason::Disable,
-                 "Try-catch during arguments usage analysis");
+  // Try-catch during analyses is not yet supported. Code within the 'catch'
+  // block is not accounted for.
+  if (info().isAnalysis()) {
+    return abort(AbortReason::Disable, "Try-catch during analysis");
   }
 
   graph().setHasTryBlock();
 
   MBasicBlock* tryBlock;
   MOZ_TRY_VAR(tryBlock, newBlock(current, try_->tryBlock()->startPc()));
 
   blockWorklist[try_->tryBlock()->id()] = tryBlock;
--- a/js/src/jit/Jit.cpp
+++ b/js/src/jit/Jit.cpp
@@ -15,18 +15,21 @@
 #include "vm/Stack-inl.h"
 
 using namespace js;
 using namespace js::jit;
 
 static EnterJitStatus JS_HAZ_JSNATIVE_CALLER EnterJit(JSContext* cx,
                                                       RunState& state,
                                                       uint8_t* code) {
-  MOZ_ASSERT(state.script()->hasBaselineScript());
+  // We don't want to call the interpreter stub here (because
+  // C++ -> interpreterStub -> C++ is slower than staying in C++).
   MOZ_ASSERT(code);
+  MOZ_ASSERT(code != cx->runtime()->jitRuntime()->interpreterStub().value);
+
   MOZ_ASSERT(IsBaselineEnabled(cx));
 
   if (!CheckRecursionLimit(cx)) {
     return EnterJitStatus::Error;
   }
 
 #ifdef DEBUG
   // Assert we don't GC before entering JIT code. A GC could discard JIT code
@@ -50,17 +53,21 @@ static EnterJitStatus JS_HAZ_JSNATIVE_CA
     numActualArgs = args.length();
 
     if (TooManyActualArguments(numActualArgs)) {
       // Too many arguments for Ion. Baseline supports more actual
       // arguments, so in that case force Baseline code.
       if (numActualArgs > BASELINE_MAX_ARGS_LENGTH) {
         return EnterJitStatus::NotEntered;
       }
-      code = script->baselineScript()->method()->raw();
+      if (script->hasBaselineScript()) {
+        code = script->baselineScript()->method()->raw();
+      } else {
+        code = cx->runtime()->jitRuntime()->baselineInterpreter().codeRaw();
+      }
     }
 
     constructing = state.asInvoke()->constructing();
     maxArgc = args.length() + 1;
     maxArgv = args.array() - 1;  // -1 to include |this|
     envChain = nullptr;
     calleeToken = CalleeToToken(&args.callee().as<JSFunction>(), constructing);
 
@@ -126,21 +133,26 @@ static EnterJitStatus JS_HAZ_JSNATIVE_CA
   return EnterJitStatus::Ok;
 }
 
 EnterJitStatus js::jit::MaybeEnterJit(JSContext* cx, RunState& state) {
   JSScript* script = state.script();
 
   uint8_t* code = script->jitCodeRaw();
   do {
-    // Make sure we have a BaselineScript: we don't want to call the
-    // interpreter stub here. Note that Baseline code contains warm-up
-    // checks in the prologue to Ion-compile if needed.
-    if (script->hasBaselineScript()) {
-      break;
+    // Make sure we can enter Baseline Interpreter or JIT code. Note that
+    // the prologue has warm-up checks to tier up if needed.
+    if (JitOptions.baselineInterpreter) {
+      if (script->types()) {
+        break;
+      }
+    } else {
+      if (script->hasBaselineScript()) {
+        break;
+      }
     }
 
     script->incWarmUpCounter();
 
     // Try to Ion-compile.
     if (jit::IsIonEnabled(cx)) {
       jit::MethodStatus status = jit::CanEnterIon(cx, state);
       if (status == jit::Method_Error) {
--- a/js/src/jit/JitFrames.cpp
+++ b/js/src/jit/JitFrames.cpp
@@ -371,31 +371,45 @@ static bool ProcessTryNotesBaseline(JSCo
         SettleOnTryNote(cx, tn, frame, ei, rfe, pc);
 
         // Ion can compile try-catch, but bailing out to catch
         // exceptions is slow. Reset the warm-up counter so that if we
         // catch many exceptions we won't Ion-compile the script.
         script->resetWarmUpCounter();
 
         // Resume at the start of the catch block.
-        PCMappingSlotInfo slotInfo;
         rfe->kind = ResumeFromException::RESUME_CATCH;
-        rfe->target =
-            script->baselineScript()->nativeCodeForPC(script, *pc, &slotInfo);
-        MOZ_ASSERT(slotInfo.isStackSynced());
+        if (frame.baselineFrame()->runningInInterpreter()) {
+          const BaselineInterpreter& interp =
+              cx->runtime()->jitRuntime()->baselineInterpreter();
+          frame.baselineFrame()->setInterpreterPC(*pc);
+          rfe->target = interp.interpretOpAddr().value;
+        } else {
+          PCMappingSlotInfo slotInfo;
+          rfe->target =
+              script->baselineScript()->nativeCodeForPC(script, *pc, &slotInfo);
+          MOZ_ASSERT(slotInfo.isStackSynced());
+        }
         return true;
       }
 
       case JSTRY_FINALLY: {
-        PCMappingSlotInfo slotInfo;
         SettleOnTryNote(cx, tn, frame, ei, rfe, pc);
         rfe->kind = ResumeFromException::RESUME_FINALLY;
-        rfe->target =
-            script->baselineScript()->nativeCodeForPC(script, *pc, &slotInfo);
-        MOZ_ASSERT(slotInfo.isStackSynced());
+        if (frame.baselineFrame()->runningInInterpreter()) {
+          const BaselineInterpreter& interp =
+              cx->runtime()->jitRuntime()->baselineInterpreter();
+          frame.baselineFrame()->setInterpreterPC(*pc);
+          rfe->target = interp.interpretOpAddr().value;
+        } else {
+          PCMappingSlotInfo slotInfo;
+          rfe->target =
+              script->baselineScript()->nativeCodeForPC(script, *pc, &slotInfo);
+          MOZ_ASSERT(slotInfo.isStackSynced());
+        }
         // Drop the exception instead of leaking cross compartment data.
         if (!cx->getPendingException(
                 MutableHandleValue::fromMarkedLocation(&rfe->exception))) {
           rfe->exception = UndefinedValue();
         }
         cx->clearPendingException();
         return true;
       }
--- a/js/src/jit/JitRealm.h
+++ b/js/src/jit/JitRealm.h
@@ -11,16 +11,17 @@
 #include "mozilla/DebugOnly.h"
 #include "mozilla/EnumeratedArray.h"
 #include "mozilla/MemoryReporting.h"
 
 #include <utility>
 
 #include "builtin/TypedObject.h"
 #include "jit/BaselineICList.h"
+#include "jit/BaselineJIT.h"
 #include "jit/CompileInfo.h"
 #include "jit/ICStubSpace.h"
 #include "jit/IonCode.h"
 #include "jit/IonControlFlow.h"
 #include "jit/JitFrames.h"
 #include "jit/shared/Assembler-shared.h"
 #include "js/GCHashTable.h"
 #include "js/Value.h"
@@ -190,16 +191,19 @@ class JitRuntime {
 
   // Thunk used by the debugger for breakpoint and step mode.
   WriteOnceData<JitCode*> debugTrapHandler_;
 
   // Thunk used to fix up on-stack recompile of baseline scripts.
   WriteOnceData<JitCode*> baselineDebugModeOSRHandler_;
   WriteOnceData<void*> baselineDebugModeOSRHandlerNoFrameRegPopAddr_;
 
+  // BaselineInterpreter state.
+  BaselineInterpreter baselineInterpreter_;
+
   // Code for trampolines and VMFunction wrappers.
   WriteOnceData<JitCode*> trampolineCode_;
 
   // Map VMFunction addresses to the offset of the wrapper in
   // trampolineCode_.
   using VMWrapperMap = HashMap<const VMFunction*, uint32_t, VMFunction>;
   WriteOnceData<VMWrapperMap*> functionWrappers_;
 
@@ -321,16 +325,18 @@ class JitRuntime {
     MOZ_ASSERT(trampolineCode_);
     return trampolineCode(tailCallFunctionWrapperOffsets_[size_t(funId)]);
   }
 
   JitCode* debugTrapHandler(JSContext* cx);
   JitCode* getBaselineDebugModeOSRHandler(JSContext* cx);
   void* getBaselineDebugModeOSRHandlerAddress(JSContext* cx, bool popFrameReg);
 
+  BaselineInterpreter& baselineInterpreter() { return baselineInterpreter_; }
+
   TrampolinePtr getGenericBailoutHandler() const {
     return trampolineCode(bailoutHandlerOffset_);
   }
 
   TrampolinePtr getExceptionTail() const {
     return trampolineCode(exceptionTailOffset_);
   }
 
--- a/js/src/jit/MacroAssembler.h
+++ b/js/src/jit/MacroAssembler.h
@@ -771,16 +771,18 @@ class MacroAssembler : public MacroAssem
   void moveValue(const ValueOperand& src, const ValueOperand& dest) PER_ARCH;
   void moveValue(const Value& src, const ValueOperand& dest) PER_ARCH;
 
   // ===============================================================
   // Load instructions
 
   inline void load32SignExtendToPtr(const Address& src, Register dest) PER_ARCH;
 
+  inline void loadAbiReturnAddress(Register dest) PER_SHARED_ARCH;
+
  public:
   // ===============================================================
   // Logical instructions
 
   inline void not32(Register reg) PER_SHARED_ARCH;
 
   inline void and32(Register src, Register dest) PER_SHARED_ARCH;
   inline void and32(Imm32 imm, Register dest) PER_SHARED_ARCH;
--- a/js/src/jit/arm/MacroAssembler-arm-inl.h
+++ b/js/src/jit/arm/MacroAssembler-arm-inl.h
@@ -80,16 +80,18 @@ void MacroAssembler::move32To64SignExten
 
 // ===============================================================
 // Load instructions
 
 void MacroAssembler::load32SignExtendToPtr(const Address& src, Register dest) {
   load32(src, dest);
 }
 
+void MacroAssembler::loadAbiReturnAddress(Register dest) { movePtr(lr, dest); }
+
 // ===============================================================
 // Logical instructions
 
 void MacroAssembler::not32(Register reg) { ma_mvn(reg, reg); }
 
 void MacroAssembler::and32(Register src, Register dest) {
   ma_and(src, dest, SetCC);
 }
--- a/js/src/jit/arm/Trampoline-arm.cpp
+++ b/js/src/jit/arm/Trampoline-arm.cpp
@@ -12,18 +12,16 @@
 #include "jit/Linker.h"
 #ifdef JS_ION_PERF
 #  include "jit/PerfSpewer.h"
 #endif
 #include "jit/VMFunctions.h"
 #include "vm/Realm.h"
 
 #include "jit/MacroAssembler-inl.h"
-#include "jit/SharedICHelpers-inl.h"
-#include "jit/VMFunctionList-inl.h"
 
 using namespace js;
 using namespace js::jit;
 
 static const FloatRegisterSet NonVolatileFloatRegs = FloatRegisterSet(
     (1ULL << FloatRegisters::d8) | (1ULL << FloatRegisters::d9) |
     (1ULL << FloatRegisters::d10) | (1ULL << FloatRegisters::d11) |
     (1ULL << FloatRegisters::d12) | (1ULL << FloatRegisters::d13) |
@@ -943,79 +941,16 @@ uint32_t JitRuntime::generatePreBarrier(
   masm.pop(temp3);
   masm.pop(temp2);
   masm.pop(temp1);
   masm.ret();
 
   return offset;
 }
 
-JitCode* JitRuntime::generateDebugTrapHandler(JSContext* cx) {
-  StackMacroAssembler masm;
-
-  Register scratch1 = r0;
-  Register scratch2 = r1;
-
-  // Load BaselineFrame pointer in scratch1.
-  masm.mov(r11, scratch1);
-  masm.subPtr(Imm32(BaselineFrame::Size()), scratch1);
-
-  // Enter a stub frame and call the HandleDebugTrap VM function. Ensure the
-  // stub frame has a nullptr ICStub pointer, since this pointer is marked
-  // during GC.
-  masm.movePtr(ImmPtr(nullptr), ICStubReg);
-  EmitBaselineEnterStubFrame(masm, scratch2);
-
-  using Fn = bool (*)(JSContext*, BaselineFrame*, uint8_t*, bool*);
-  VMFunctionId id = VMFunctionToId<Fn, jit::HandleDebugTrap>::id;
-  TrampolinePtr code = cx->runtime()->jitRuntime()->getVMWrapper(id);
-
-  masm.push(lr);
-  masm.push(scratch1);
-  EmitBaselineCallVM(code, masm);
-
-  EmitBaselineLeaveStubFrame(masm);
-
-  // If the stub returns |true|, we have to perform a forced return (return
-  // from the JS frame). If the stub returns |false|, just return from the
-  // trap stub so that execution continues at the current pc.
-  Label forcedReturn;
-  masm.branchTest32(Assembler::NonZero, ReturnReg, ReturnReg, &forcedReturn);
-  masm.mov(lr, pc);
-
-  masm.bind(&forcedReturn);
-  masm.loadValue(Address(r11, BaselineFrame::reverseOffsetOfReturnValue()),
-                 JSReturnOperand);
-  masm.mov(r11, sp);
-  masm.pop(r11);
-
-  // Before returning, if profiling is turned on, make sure that
-  // lastProfilingFrame is set to the correct caller frame.
-  {
-    Label skipProfilingInstrumentation;
-    AbsoluteAddress addressOfEnabled(
-        cx->runtime()->geckoProfiler().addressOfEnabled());
-    masm.branch32(Assembler::Equal, addressOfEnabled, Imm32(0),
-                  &skipProfilingInstrumentation);
-    masm.profilerExitFrame();
-    masm.bind(&skipProfilingInstrumentation);
-  }
-
-  masm.ret();
-
-  Linker linker(masm, "DebugTrapHandler");
-  JitCode* codeDbg = linker.newCode(cx, CodeKind::Other);
-
-#ifdef JS_ION_PERF
-  writePerfSpewerJitCodeProfile(codeDbg, "DebugTrapHandler");
-#endif
-
-  return codeDbg;
-}
-
 void JitRuntime::generateExceptionTailStub(MacroAssembler& masm, void* handler,
                                            Label* profilerExitTail) {
   exceptionTailOffset_ = startTrampolineCode(masm);
 
   masm.bind(masm.failureLabel());
   masm.handleFailureWithHandlerTail(handler, profilerExitTail);
 }
 
--- a/js/src/jit/arm64/MacroAssembler-arm64-inl.h
+++ b/js/src/jit/arm64/MacroAssembler-arm64-inl.h
@@ -69,16 +69,18 @@ void MacroAssembler::move32To64SignExten
 // ===============================================================
 // Load instructions
 
 void MacroAssembler::load32SignExtendToPtr(const Address& src, Register dest) {
   load32(src, dest);
   move32To64SignExtend(dest, Register64(dest));
 }
 
+void MacroAssembler::loadAbiReturnAddress(Register dest) { movePtr(lr, dest); }
+
 // ===============================================================
 // Logical instructions
 
 void MacroAssembler::not32(Register reg) {
   Orn(ARMRegister(reg, 32), vixl::wzr, ARMRegister(reg, 32));
 }
 
 void MacroAssembler::and32(Register src, Register dest) {
--- a/js/src/jit/arm64/Trampoline-arm64.cpp
+++ b/js/src/jit/arm64/Trampoline-arm64.cpp
@@ -10,18 +10,16 @@
 #include "jit/Linker.h"
 #ifdef JS_ION_PERF
 #  include "jit/PerfSpewer.h"
 #endif
 #include "jit/arm64/SharedICHelpers-arm64.h"
 #include "jit/VMFunctions.h"
 
 #include "jit/MacroAssembler-inl.h"
-#include "jit/SharedICHelpers-inl.h"
-#include "jit/VMFunctionList-inl.h"
 
 using namespace js;
 using namespace js::jit;
 
 /* This method generates a trampoline on ARM64 for a c++ function with
  * the following signature:
  *   bool blah(void* code, int argc, Value* argv,
  *             JSObject* scopeChain, Value* vp)
@@ -781,73 +779,16 @@ uint32_t JitRuntime::generatePreBarrier(
   masm.pop(temp3);
   masm.pop(temp2);
   masm.pop(temp1);
   masm.abiret();
 
   return offset;
 }
 
-JitCode* JitRuntime::generateDebugTrapHandler(JSContext* cx) {
-  StackMacroAssembler masm(cx);
-#ifndef JS_USE_LINK_REGISTER
-  // The first value contains the return addres,
-  // which we pull into ICTailCallReg for tail calls.
-  masm.setFramePushed(sizeof(intptr_t));
-#endif
-
-  Register scratch1 = r0;
-  Register scratch2 = r1;
-
-  // Load BaselineFrame pointer into scratch1.
-  masm.Sub(ARMRegister(scratch1, 64), BaselineFrameReg64,
-           Operand(BaselineFrame::Size()));
-
-  // Enter a stub frame and call the HandleDebugTrap VM function. Ensure the
-  // stub frame has a nullptr ICStub pointer, since this pointer is marked
-  // during GC.
-  masm.movePtr(ImmPtr(nullptr), ICStubReg);
-  EmitBaselineEnterStubFrame(masm, scratch2);
-
-  using Fn = bool (*)(JSContext*, BaselineFrame*, uint8_t*, bool*);
-  VMFunctionId id = VMFunctionToId<Fn, jit::HandleDebugTrap>::id;
-  TrampolinePtr code = cx->runtime()->jitRuntime()->getVMWrapper(id);
-
-  masm.asVIXL().Push(vixl::lr, ARMRegister(scratch1, 64));
-  EmitBaselineCallVM(code, masm);
-
-  EmitBaselineLeaveStubFrame(masm);
-
-  // If the stub returns |true|, we have to perform a forced return (return
-  // from the JS frame). If the stub returns |false|, just return from the
-  // trap stub so that execution continues at the current pc.
-  Label forcedReturn;
-  masm.branchTest32(Assembler::NonZero, ReturnReg, ReturnReg, &forcedReturn);
-  masm.abiret();
-
-  masm.bind(&forcedReturn);
-  masm.loadValue(
-      Address(BaselineFrameReg, BaselineFrame::reverseOffsetOfReturnValue()),
-      JSReturnOperand);
-  masm.Mov(masm.GetStackPointer64(), BaselineFrameReg64);
-
-  masm.pop(BaselineFrameReg, lr);
-  masm.syncStackPtr();
-  masm.abiret();
-
-  Linker linker(masm, "DebugTrapHandler");
-  JitCode* codeDbg = linker.newCode(cx, CodeKind::Other);
-
-#ifdef JS_ION_PERF
-  writePerfSpewerJitCodeProfile(codeDbg, "DebugTrapHandler");
-#endif
-
-  return codeDbg;
-}
-
 void JitRuntime::generateExceptionTailStub(MacroAssembler& masm, void* handler,
                                            Label* profilerExitTail) {
   exceptionTailOffset_ = startTrampolineCode(masm);
 
   masm.bind(masm.failureLabel());
   masm.handleFailureWithHandlerTail(handler, profilerExitTail);
 }
 
--- a/js/src/jit/mips32/Trampoline-mips32.cpp
+++ b/js/src/jit/mips32/Trampoline-mips32.cpp
@@ -15,18 +15,16 @@
 #include "jit/mips32/Bailouts-mips32.h"
 #ifdef JS_ION_PERF
 #  include "jit/PerfSpewer.h"
 #endif
 #include "jit/VMFunctions.h"
 #include "vm/Realm.h"
 
 #include "jit/MacroAssembler-inl.h"
-#include "jit/SharedICHelpers-inl.h"
-#include "jit/VMFunctionList-inl.h"
 
 using namespace js;
 using namespace js::jit;
 
 static_assert(sizeof(uintptr_t) == sizeof(uint32_t), "Not 64-bit clean.");
 
 struct EnterJITRegs {
   double f30;
@@ -930,83 +928,16 @@ uint32_t JitRuntime::generatePreBarrier(
   masm.pop(temp3);
   masm.pop(temp2);
   masm.pop(temp1);
   masm.abiret();
 
   return offset;
 }
 
-JitCode* JitRuntime::generateDebugTrapHandler(JSContext* cx) {
-  StackMacroAssembler masm(cx);
-
-  Register scratch1 = t0;
-  Register scratch2 = t1;
-
-  // Load BaselineFrame pointer in scratch1.
-  masm.movePtr(s5, scratch1);
-  masm.subPtr(Imm32(BaselineFrame::Size()), scratch1);
-
-  // Enter a stub frame and call the HandleDebugTrap VM function. Ensure
-  // the stub frame has a nullptr ICStub pointer, since this pointer is
-  // marked during GC.
-  masm.movePtr(ImmPtr(nullptr), ICStubReg);
-  EmitBaselineEnterStubFrame(masm, scratch2);
-
-  using Fn = bool (*)(JSContext*, BaselineFrame*, uint8_t*, bool*);
-  VMFunctionId id = VMFunctionToId<Fn, jit::HandleDebugTrap>::id;
-  TrampolinePtr code = cx->runtime()->jitRuntime()->getVMWrapper(id);
-
-  masm.subPtr(Imm32(2 * sizeof(uintptr_t)), StackPointer);
-  masm.storePtr(ra, Address(StackPointer, sizeof(uintptr_t)));
-  masm.storePtr(scratch1, Address(StackPointer, 0));
-
-  EmitBaselineCallVM(code, masm);
-
-  EmitBaselineLeaveStubFrame(masm);
-
-  // If the stub returns |true|, we have to perform a forced return
-  // (return from the JS frame). If the stub returns |false|, just return
-  // from the trap stub so that execution continues at the current pc.
-  Label forcedReturn;
-  masm.branchTest32(Assembler::NonZero, ReturnReg, ReturnReg, &forcedReturn);
-
-  // ra was restored by EmitLeaveStubFrame
-  masm.branch(ra);
-
-  masm.bind(&forcedReturn);
-  masm.loadValue(Address(s5, BaselineFrame::reverseOffsetOfReturnValue()),
-                 JSReturnOperand);
-  masm.movePtr(s5, StackPointer);
-  masm.pop(s5);
-
-  // Before returning, if profiling is turned on, make sure that
-  // lastProfilingFrame is set to the correct caller frame.
-  {
-    Label skipProfilingInstrumentation;
-    AbsoluteAddress addressOfEnabled(
-        cx->runtime()->geckoProfiler().addressOfEnabled());
-    masm.branch32(Assembler::Equal, addressOfEnabled, Imm32(0),
-                  &skipProfilingInstrumentation);
-    masm.profilerExitFrame();
-    masm.bind(&skipProfilingInstrumentation);
-  }
-
-  masm.ret();
-
-  Linker linker(masm, "DebugTrapHandler");
-  JitCode* codeDbg = linker.newCode(cx, CodeKind::Other);
-
-#ifdef JS_ION_PERF
-  writePerfSpewerJitCodeProfile(codeDbg, "DebugTrapHandler");
-#endif
-
-  return codeDbg;
-}
-
 void JitRuntime::generateExceptionTailStub(MacroAssembler& masm, void* handler,
                                            Label* profilerExitTail) {
   exceptionTailOffset_ = startTrampolineCode(masm);
 
   masm.bind(masm.failureLabel());
   masm.handleFailureWithHandlerTail(handler, profilerExitTail);
 }
 
--- a/js/src/jit/mips64/Trampoline-mips64.cpp
+++ b/js/src/jit/mips64/Trampoline-mips64.cpp
@@ -15,18 +15,16 @@
 #include "jit/mips64/Bailouts-mips64.h"
 #ifdef JS_ION_PERF
 #  include "jit/PerfSpewer.h"
 #endif
 #include "jit/VMFunctions.h"
 #include "vm/Realm.h"
 
 #include "jit/MacroAssembler-inl.h"
-#include "jit/SharedICHelpers-inl.h"
-#include "jit/VMFunctionList-inl.h"
 
 using namespace js;
 using namespace js::jit;
 
 // All registers to save and restore. This includes the stack pointer, since we
 // use the ability to reference register values on the stack by index.
 static const LiveRegisterSet AllRegs =
     LiveRegisterSet(GeneralRegisterSet(Registers::AllMask),
@@ -880,83 +878,16 @@ uint32_t JitRuntime::generatePreBarrier(
   masm.pop(temp3);
   masm.pop(temp2);
   masm.pop(temp1);
   masm.abiret();
 
   return offset;
 }
 
-JitCode* JitRuntime::generateDebugTrapHandler(JSContext* cx) {
-  StackMacroAssembler masm(cx);
-
-  Register scratch1 = t0;
-  Register scratch2 = t1;
-
-  // Load BaselineFrame pointer in scratch1.
-  masm.movePtr(s5, scratch1);
-  masm.subPtr(Imm32(BaselineFrame::Size()), scratch1);
-
-  // Enter a stub frame and call the HandleDebugTrap VM function. Ensure
-  // the stub frame has a nullptr ICStub pointer, since this pointer is
-  // marked during GC.
-  masm.movePtr(ImmPtr(nullptr), ICStubReg);
-  EmitBaselineEnterStubFrame(masm, scratch2);
-
-  using Fn = bool (*)(JSContext*, BaselineFrame*, uint8_t*, bool*);
-  VMFunctionId id = VMFunctionToId<Fn, jit::HandleDebugTrap>::id;
-  TrampolinePtr code = cx->runtime()->jitRuntime()->getVMWrapper(id);
-
-  masm.subPtr(Imm32(2 * sizeof(uintptr_t)), StackPointer);
-  masm.storePtr(ra, Address(StackPointer, sizeof(uintptr_t)));
-  masm.storePtr(scratch1, Address(StackPointer, 0));
-
-  EmitBaselineCallVM(code, masm);
-
-  EmitBaselineLeaveStubFrame(masm);
-
-  // If the stub returns |true|, we have to perform a forced return
-  // (return from the JS frame). If the stub returns |false|, just return
-  // from the trap stub so that execution continues at the current pc.
-  Label forcedReturn;
-  masm.branchTest32(Assembler::NonZero, ReturnReg, ReturnReg, &forcedReturn);
-
-  // ra was restored by EmitLeaveStubFrame
-  masm.branch(ra);
-
-  masm.bind(&forcedReturn);
-  masm.loadValue(Address(s5, BaselineFrame::reverseOffsetOfReturnValue()),
-                 JSReturnOperand);
-  masm.movePtr(s5, StackPointer);
-  masm.pop(s5);
-
-  // Before returning, if profiling is turned on, make sure that
-  // lastProfilingFrame is set to the correct caller frame.
-  {
-    Label skipProfilingInstrumentation;
-    AbsoluteAddress addressOfEnabled(
-        cx->runtime()->geckoProfiler().addressOfEnabled());
-    masm.branch32(Assembler::Equal, addressOfEnabled, Imm32(0),
-                  &skipProfilingInstrumentation);
-    masm.profilerExitFrame();
-    masm.bind(&skipProfilingInstrumentation);
-  }
-
-  masm.ret();
-
-  Linker linker(masm, "DebugTrapHandler");
-  JitCode* codeDbg = linker.newCode(cx, CodeKind::Other);
-
-#ifdef JS_ION_PERF
-  writePerfSpewerJitCodeProfile(codeDbg, "DebugTrapHandler");
-#endif
-
-  return codeDbg;
-}
-
 void JitRuntime::generateExceptionTailStub(MacroAssembler& masm, void* handler,
                                            Label* profilerExitTail) {
   exceptionTailOffset_ = startTrampolineCode(masm);
 
   masm.bind(masm.failureLabel());
   masm.handleFailureWithHandlerTail(handler, profilerExitTail);
 }
 
--- a/js/src/jit/none/Trampoline-none.cpp
+++ b/js/src/jit/none/Trampoline-none.cpp
@@ -23,17 +23,16 @@ JitRuntime::BailoutTable JitRuntime::gen
   MOZ_CRASH();
 }
 void JitRuntime::generateBailoutHandler(MacroAssembler&, Label*) {
   MOZ_CRASH();
 }
 uint32_t JitRuntime::generatePreBarrier(JSContext*, MacroAssembler&, MIRType) {
   MOZ_CRASH();
 }
-JitCode* JitRuntime::generateDebugTrapHandler(JSContext*) { MOZ_CRASH(); }
 void JitRuntime::generateExceptionTailStub(MacroAssembler&, void*, Label*) {
   MOZ_CRASH();
 }
 void JitRuntime::generateBailoutTailStub(MacroAssembler&, Label*) {
   MOZ_CRASH();
 }
 void JitRuntime::generateProfilerExitFrameTailStub(MacroAssembler&, Label*) {
   MOZ_CRASH();
--- a/js/src/jit/x64/Trampoline-x64.cpp
+++ b/js/src/jit/x64/Trampoline-x64.cpp
@@ -11,18 +11,16 @@
 #ifdef JS_ION_PERF
 #  include "jit/PerfSpewer.h"
 #endif
 #include "jit/VMFunctions.h"
 #include "jit/x64/SharedICHelpers-x64.h"
 #include "vtune/VTuneWrapper.h"
 
 #include "jit/MacroAssembler-inl.h"
-#include "jit/SharedICHelpers-inl.h"
-#include "jit/VMFunctionList-inl.h"
 
 using namespace js;
 using namespace js::jit;
 
 using mozilla::IsPowerOfTwo;
 
 // All registers to save and restore. This includes the stack pointer, since we
 // use the ability to reference register values on the stack by index.
@@ -815,91 +813,16 @@ uint32_t JitRuntime::generatePreBarrier(
   masm.pop(temp3);
   masm.pop(temp2);
   masm.pop(temp1);
   masm.ret();
 
   return offset;
 }
 
-JitCode* JitRuntime::generateDebugTrapHandler(JSContext* cx) {
-  StackMacroAssembler masm;
-#ifndef JS_USE_LINK_REGISTER
-  // The first value contains the return addres,
-  // which we pull into ICTailCallReg for tail calls.
-  masm.setFramePushed(sizeof(intptr_t));
-#endif
-
-  Register scratch1 = rax;
-  Register scratch2 = rcx;
-  Register scratch3 = rdx;
-
-  // Load the return address in scratch1.
-  masm.loadPtr(Address(rsp, 0), scratch1);
-
-  // Load BaselineFrame pointer in scratch2.
-  masm.mov(rbp, scratch2);
-  masm.subPtr(Imm32(BaselineFrame::Size()), scratch2);
-
-  // Enter a stub frame and call the HandleDebugTrap VM function. Ensure
-  // the stub frame has a nullptr ICStub pointer, since this pointer is marked
-  // during GC.
-  masm.movePtr(ImmPtr(nullptr), ICStubReg);
-  EmitBaselineEnterStubFrame(masm, scratch3);
-
-  using Fn = bool (*)(JSContext*, BaselineFrame*, uint8_t*, bool*);
-  VMFunctionId id = VMFunctionToId<Fn, jit::HandleDebugTrap>::id;
-  TrampolinePtr code = cx->runtime()->jitRuntime()->getVMWrapper(id);
-
-  masm.push(scratch1);
-  masm.push(scratch2);
-  EmitBaselineCallVM(code, masm);
-
-  EmitBaselineLeaveStubFrame(masm);
-
-  // If the stub returns |true|, we have to perform a forced return
-  // (return from the JS frame). If the stub returns |false|, just return
-  // from the trap stub so that execution continues at the current pc.
-  Label forcedReturn;
-  masm.branchTest32(Assembler::NonZero, ReturnReg, ReturnReg, &forcedReturn);
-  masm.ret();
-
-  masm.bind(&forcedReturn);
-  masm.loadValue(Address(ebp, BaselineFrame::reverseOffsetOfReturnValue()),
-                 JSReturnOperand);
-  masm.mov(rbp, rsp);
-  masm.pop(rbp);
-
-  // Before returning, if profiling is turned on, make sure that
-  // lastProfilingFrame is set to the correct caller frame.
-  {
-    Label skipProfilingInstrumentation;
-    AbsoluteAddress addressOfEnabled(
-        cx->runtime()->geckoProfiler().addressOfEnabled());
-    masm.branch32(Assembler::Equal, addressOfEnabled, Imm32(0),
-                  &skipProfilingInstrumentation);
-    masm.profilerExitFrame();
-    masm.bind(&skipProfilingInstrumentation);
-  }
-
-  masm.ret();
-
-  Linker linker(masm, "DebugTrapHandler");
-  JitCode* codeDbg = linker.newCode(cx, CodeKind::Other);
-
-#ifdef JS_ION_PERF
-  writePerfSpewerJitCodeProfile(codeDbg, "DebugTrapHandler");
-#endif
-#ifdef MOZ_VTUNE
-  vtune::MarkStub(codeDbg, "DebugTrapHandler");
-#endif
-
-  return codeDbg;
-}
-
 void JitRuntime::generateExceptionTailStub(MacroAssembler& masm, void* handler,
                                            Label* profilerExitTail) {
   exceptionTailOffset_ = startTrampolineCode(masm);
 
   masm.bind(masm.failureLabel());
   masm.handleFailureWithHandlerTail(handler, profilerExitTail);
 }
 
--- a/js/src/jit/x86-shared/MacroAssembler-x86-shared-inl.h
+++ b/js/src/jit/x86-shared/MacroAssembler-x86-shared-inl.h
@@ -27,16 +27,20 @@ void MacroAssembler::moveGPRToFloat32(Re
 void MacroAssembler::move8SignExtend(Register src, Register dest) {
   movsbl(src, dest);
 }
 
 void MacroAssembler::move16SignExtend(Register src, Register dest) {
   movswl(src, dest);
 }
 
+void MacroAssembler::loadAbiReturnAddress(Register dest) {
+  loadPtr(Address(getStackPointer(), 0), dest);
+}
+
 // ===============================================================
 // Logical instructions
 
 void MacroAssembler::not32(Register reg) { notl(reg); }
 
 void MacroAssembler::and32(Register src, Register dest) { andl(src, dest); }
 
 void MacroAssembler::and32(Imm32 imm, Register dest) { andl(imm, dest); }
--- a/js/src/jit/x86/Trampoline-x86.cpp
+++ b/js/src/jit/x86/Trampoline-x86.cpp
@@ -16,18 +16,16 @@
 #  include "jit/PerfSpewer.h"
 #endif
 #include "jit/VMFunctions.h"
 #include "jit/x86/SharedICHelpers-x86.h"
 #include "vm/Realm.h"
 #include "vtune/VTuneWrapper.h"
 
 #include "jit/MacroAssembler-inl.h"
-#include "jit/SharedICHelpers-inl.h"
-#include "jit/VMFunctionList-inl.h"
 #include "vm/JSScript-inl.h"
 
 using mozilla::IsPowerOfTwo;
 
 using namespace js;
 using namespace js::jit;
 
 // All registers to save and restore. This includes the stack pointer, since we
@@ -834,91 +832,16 @@ uint32_t JitRuntime::generatePreBarrier(
   masm.pop(temp3);
   masm.pop(temp2);
   masm.pop(temp1);
   masm.ret();
 
   return offset;
 }
 
-JitCode* JitRuntime::generateDebugTrapHandler(JSContext* cx) {
-  StackMacroAssembler masm;
-#ifndef JS_USE_LINK_REGISTER
-  // The first value contains the return addres,
-  // which we pull into ICTailCallReg for tail calls.
-  masm.setFramePushed(sizeof(intptr_t));
-#endif
-
-  Register scratch1 = eax;
-  Register scratch2 = ecx;
-  Register scratch3 = edx;
-
-  // Load the return address in scratch1.
-  masm.loadPtr(Address(esp, 0), scratch1);
-
-  // Load BaselineFrame pointer in scratch2.
-  masm.mov(ebp, scratch2);
-  masm.subPtr(Imm32(BaselineFrame::Size()), scratch2);
-
-  // Enter a stub frame and call the HandleDebugTrap VM function. Ensure
-  // the stub frame has a nullptr ICStub pointer, since this pointer is
-  // marked during GC.
-  masm.movePtr(ImmPtr(nullptr), ICStubReg);
-  EmitBaselineEnterStubFrame(masm, scratch3);
-
-  using Fn = bool (*)(JSContext*, BaselineFrame*, uint8_t*, bool*);
-  VMFunctionId id = VMFunctionToId<Fn, jit::HandleDebugTrap>::id;
-  TrampolinePtr code = cx->runtime()->jitRuntime()->getVMWrapper(id);
-
-  masm.push(scratch1);
-  masm.push(scratch2);
-  EmitBaselineCallVM(code, masm);
-
-  EmitBaselineLeaveStubFrame(masm);
-
-  // If the stub returns |true|, we have to perform a forced return
-  // (return from the JS frame). If the stub returns |false|, just return
-  // from the trap stub so that execution continues at the current pc.
-  Label forcedReturn;
-  masm.branchTest32(Assembler::NonZero, ReturnReg, ReturnReg, &forcedReturn);
-  masm.ret();
-
-  masm.bind(&forcedReturn);
-  masm.loadValue(Address(ebp, BaselineFrame::reverseOffsetOfReturnValue()),
-                 JSReturnOperand);
-  masm.mov(ebp, esp);
-  masm.pop(ebp);
-
-  // Before returning, if profiling is turned on, make sure that
-  // lastProfilingFrame is set to the correct caller frame.
-  {
-    Label skipProfilingInstrumentation;
-    AbsoluteAddress addressOfEnabled(
-        cx->runtime()->geckoProfiler().addressOfEnabled());
-    masm.branch32(Assembler::Equal, addressOfEnabled, Imm32(0),
-                  &skipProfilingInstrumentation);
-    masm.profilerExitFrame();
-    masm.bind(&skipProfilingInstrumentation);
-  }
-
-  masm.ret();
-
-  Linker linker(masm, "DebugTrapHandler");
-  JitCode* codeDbg = linker.newCode(cx, CodeKind::Other);
-
-#ifdef JS_ION_PERF
-  writePerfSpewerJitCodeProfile(codeDbg, "DebugTrapHandler");
-#endif
-#ifdef MOZ_VTUNE
-  vtune::MarkStub(codeDbg, "DebugTrapHandler");
-#endif
-
-  return codeDbg;
-}
-
 void JitRuntime::generateExceptionTailStub(MacroAssembler& masm, void* handler,
                                            Label* profilerExitTail) {
   exceptionTailOffset_ = startTrampolineCode(masm);
 
   masm.bind(masm.failureLabel());
   masm.handleFailureWithHandlerTail(handler, profilerExitTail);
 }
 
--- a/js/src/vm/JSScript.cpp
+++ b/js/src/vm/JSScript.cpp
@@ -5426,16 +5426,19 @@ void JSScript::updateJitCodeRaw(JSRuntim
     jitCodeRaw_ = rt->jitRuntime()->lazyLinkStub().value;
     jitCodeSkipArgCheck_ = jitCodeRaw_;
   } else if (hasIonScript()) {
     jitCodeRaw_ = ion->method()->raw();
     jitCodeSkipArgCheck_ = jitCodeRaw_ + ion->getSkipArgCheckEntryOffset();
   } else if (hasBaselineScript()) {
     jitCodeRaw_ = baseline->method()->raw();
     jitCodeSkipArgCheck_ = jitCodeRaw_;
+  } else if (types() && js::jit::JitOptions.baselineInterpreter) {
+    jitCodeRaw_ = rt->jitRuntime()->baselineInterpreter().codeRaw();
+    jitCodeSkipArgCheck_ = jitCodeRaw_;
   } else {
     jitCodeRaw_ = rt->jitRuntime()->interpreterStub().value;
     jitCodeSkipArgCheck_ = jitCodeRaw_;
   }
   MOZ_ASSERT(jitCodeRaw_);
   MOZ_ASSERT(jitCodeSkipArgCheck_);
 }
 
--- a/js/src/vm/Runtime.cpp
+++ b/js/src/vm/Runtime.cpp
@@ -765,23 +765,31 @@ void JSRuntime::clearUsedByHelperThread(
 
   JSContext* cx = mainContextFromOwnThread();
   if (gc.fullGCForAtomsRequested() && cx->canCollectAtoms()) {
     gc.triggerFullGCForAtoms(cx);
   }
 }
 
 void JSRuntime::incrementNumDebuggeeRealms() {
+  if (numDebuggeeRealms_ == 0) {
+    jitRuntime()->baselineInterpreter().toggleDebuggerInstrumentation(true);
+  }
+
   numDebuggeeRealms_++;
   MOZ_ASSERT(numDebuggeeRealms_ <= numRealms);
 }
 
 void JSRuntime::decrementNumDebuggeeRealms() {
   MOZ_ASSERT(numDebuggeeRealms_ > 0);
   numDebuggeeRealms_--;
+
+  if (numDebuggeeRealms_ == 0) {
+    jitRuntime()->baselineInterpreter().toggleDebuggerInstrumentation(false);
+  }
 }
 
 bool js::CurrentThreadCanAccessRuntime(const JSRuntime* rt) {
   return rt->mainContextFromAnyThread() == TlsContext.get();
 }
 
 bool js::CurrentThreadCanAccessZone(Zone* zone) {
   // Helper thread zones can only be used by their owning thread.
--- a/js/src/vm/TypeInference.cpp
+++ b/js/src/vm/TypeInference.cpp
@@ -3279,16 +3279,19 @@ bool js::AddClearDefiniteGetterSetterFor
                                                        HandleId id) {
   /*
    * Ensure that if the properties named here could have a getter, setter or
    * a permanent property in any transitive prototype, the definite
    * properties get cleared from the group.
    */
   RootedObject proto(cx, group->proto().toObjectOrNull());
   while (proto) {
+    if (!proto->hasStaticPrototype()) {
+      return false;
+    }
     ObjectGroup* protoGroup = JSObject::getGroup(cx, proto);
     if (!protoGroup) {
       cx->recoverFromOutOfMemory();
       return false;
     }
     AutoSweepObjectGroup sweep(protoGroup);
     if (protoGroup->unknownProperties(sweep)) {
       return false;
@@ -3547,16 +3550,20 @@ bool JSScript::makeTypes(JSContext* cx) 
   if (!typeScript) {
     return false;
   }
 
   prepareForDestruction.release();
 
   types_ = new (typeScript) TypeScript(this, std::move(icScript), numTypeSets);
 
+  // We have a TypeScript so we can set the script's jitCodeRaw_ pointer to the
+  // Baseline Interpreter code.
+  updateJitCodeRaw(cx->runtime());
+
 #ifdef DEBUG
   StackTypeSet* typeArray = typeScript->typeArrayDontCheckGeneration();
   for (unsigned i = 0; i < numBytecodeTypeSets(); i++) {
     InferSpew(ISpewOps, "typeSet: %sT%p%s bytecode%u %p",
               InferSpewColor(&typeArray[i]), &typeArray[i],
               InferSpewColorReset(), i, this);
   }
   TypeSet* thisTypes = TypeScript::ThisTypes(this);
@@ -4577,16 +4584,17 @@ void JSScript::maybeReleaseTypes() {
       types_->active()) {
     return;
   }
 
   MOZ_ASSERT(!hasIonScript());
 
   types_->destroy(zone());
   types_ = nullptr;
+  updateJitCodeRaw(runtimeFromMainThread());
 }
 
 void TypeScript::destroy(Zone* zone) {
   icScript_->prepareForDestruction(zone);
 
   js_delete(this);
 }
 
--- a/layout/base/nsLayoutUtils.cpp
+++ b/layout/base/nsLayoutUtils.cpp
@@ -4392,38 +4392,32 @@ nsRect nsLayoutUtils::GetTextShadowRects
 
     resultRect.UnionRect(resultRect, tmpRect);
   }
   return resultRect;
 }
 
 enum ObjectDimensionType { eWidth, eHeight };
 static nscoord ComputeMissingDimension(
-    const nsSize& aDefaultObjectSize, const nsSize& aIntrinsicRatio,
+    const nsSize& aDefaultObjectSize, const AspectRatio& aIntrinsicRatio,
     const Maybe<nscoord>& aSpecifiedWidth,
     const Maybe<nscoord>& aSpecifiedHeight,
     ObjectDimensionType aDimensionToCompute) {
   // The "default sizing algorithm" computes the missing dimension as follows:
   // (source: http://dev.w3.org/csswg/css-images-3/#default-sizing )
 
   // 1. "If the object has an intrinsic aspect ratio, the missing dimension of
   //     the concrete object size is calculated using the intrinsic aspect
   //     ratio and the present dimension."
-  if (aIntrinsicRatio.width > 0 && aIntrinsicRatio.height > 0) {
+  if (aIntrinsicRatio) {
     // Fill in the missing dimension using the intrinsic aspect ratio.
-    nscoord knownDimensionSize;
-    float ratio;
     if (aDimensionToCompute == eWidth) {
-      knownDimensionSize = *aSpecifiedHeight;
-      ratio = aIntrinsicRatio.width / aIntrinsicRatio.height;
-    } else {
-      knownDimensionSize = *aSpecifiedWidth;
-      ratio = aIntrinsicRatio.height / aIntrinsicRatio.width;
-    }
-    return NSCoordSaturatingNonnegativeMultiply(knownDimensionSize, ratio);
+      return aIntrinsicRatio.ApplyTo(*aSpecifiedHeight);
+    }
+    return aIntrinsicRatio.Inverted().ApplyTo(*aSpecifiedWidth);
   }
 
   // 2. "Otherwise, if the missing dimension is present in the object's
   //     intrinsic dimensions, [...]"
   // NOTE: *Skipping* this case, because we already know it's not true -- we're
   // in this function because the missing dimension is *not* present in
   // the object's intrinsic dimensions.
 
@@ -4453,17 +4447,17 @@ static nscoord ComputeMissingDimension(
  * we run the default sizing algorithm using the object's intrinsic size in
  * place of the specified size. But if the object has neither an intrinsic
  * height nor an intrinsic width, then we instead return without populating our
  * outparam, and we let the caller figure out the size (using a contain
  * constraint).
  */
 static Maybe<nsSize> MaybeComputeObjectFitNoneSize(
     const nsSize& aDefaultObjectSize, const IntrinsicSize& aIntrinsicSize,
-    const nsSize& aIntrinsicRatio) {
+    const AspectRatio& aIntrinsicRatio) {
   // "If the object has an intrinsic height or width, its size is resolved as
   // if its intrinsic dimensions were given as the specified size."
   //
   // So, first we check if we have an intrinsic height and/or width:
   const Maybe<nscoord>& specifiedWidth = aIntrinsicSize.width;
   const Maybe<nscoord>& specifiedHeight = aIntrinsicSize.height;
 
   Maybe<nsSize> noneSize;  // (the value we'll return)
@@ -4491,23 +4485,22 @@ static Maybe<nsSize> MaybeComputeObjectF
   // computations; so, we return w/out populating noneSize.
   return noneSize;
 }
 
 // Computes the concrete object size to render into, as described at
 // http://dev.w3.org/csswg/css-images-3/#concrete-size-resolution
 static nsSize ComputeConcreteObjectSize(const nsSize& aConstraintSize,
                                         const IntrinsicSize& aIntrinsicSize,
-                                        const nsSize& aIntrinsicRatio,
+                                        const AspectRatio& aIntrinsicRatio,
                                         uint8_t aObjectFit) {
   // Handle default behavior (filling the container) w/ fast early return.
   // (Also: if there's no valid intrinsic ratio, then we have the "fill"
   // behavior & just use the constraint size.)
-  if (MOZ_LIKELY(aObjectFit == NS_STYLE_OBJECT_FIT_FILL) ||
-      aIntrinsicRatio.width == 0 || aIntrinsicRatio.height == 0) {
+  if (MOZ_LIKELY(aObjectFit == NS_STYLE_OBJECT_FIT_FILL) || !aIntrinsicRatio) {
     return aConstraintSize;
   }
 
   // The type of constraint to compute (cover/contain), if needed:
   Maybe<nsImageRenderer::FitType> fitType;
 
   Maybe<nsSize> noneSize;
   if (aObjectFit == NS_STYLE_OBJECT_FIT_NONE ||
@@ -4575,17 +4568,17 @@ static bool HasInitialObjectFitAndPositi
 
   return aStylePos->mObjectFit == NS_STYLE_OBJECT_FIT_FILL &&
          IsCoord50Pct(objectPos.horizontal) && IsCoord50Pct(objectPos.vertical);
 }
 
 /* static */
 nsRect nsLayoutUtils::ComputeObjectDestRect(const nsRect& aConstraintRect,
                                             const IntrinsicSize& aIntrinsicSize,
-                                            const nsSize& aIntrinsicRatio,
+                                            const AspectRatio& aIntrinsicRatio,
                                             const nsStylePosition* aStylePos,
                                             nsPoint* aAnchorPoint) {
   // Step 1: Figure out our "concrete object size"
   // (the size of the region we'll actually draw our image's pixels into).
   nsSize concreteObjectSize =
       ComputeConcreteObjectSize(aConstraintRect.Size(), aIntrinsicSize,
                                 aIntrinsicRatio, aStylePos->mObjectFit);
 
@@ -5434,59 +5427,60 @@ nscoord nsLayoutUtils::IntrinsicForAxis(
     }
 
     // FIXME(emilio): Why the minBsize == 0 special-case? Also, shouldn't this
     // use BehavesLikeInitialValueOnBlockAxis instead?
     if (!styleBSize.IsAuto() ||
         !(styleMinBSize.IsAuto() || (styleMinBSize.ConvertsToLength() &&
                                      styleMinBSize.ToLength() == 0)) ||
         !styleMaxBSize.IsNone()) {
-      nsSize ratio(aFrame->GetIntrinsicRatio());
-      nscoord ratioISize = (horizontalAxis ? ratio.width : ratio.height);
-      nscoord ratioBSize = (horizontalAxis ? ratio.height : ratio.width);
-      if (ratioBSize != 0) {
+      if (AspectRatio ratio = aFrame->GetIntrinsicRatio()) {
+        // Convert 'ratio' if necessary, so that it's storing ISize/BSize:
+        if (!horizontalAxis) {
+          ratio = ratio.Inverted();
+        }
         AddStateBitToAncestors(
             aFrame, NS_FRAME_DESCENDANT_INTRINSIC_ISIZE_DEPENDS_ON_BSIZE);
 
         nscoord bSizeTakenByBoxSizing = GetDefiniteSizeTakenByBoxSizing(
             boxSizing, aFrame, !isInlineAxis, aFlags & IGNORE_PADDING,
             aPercentageBasis);
         // NOTE: This is only the minContentSize if we've been passed
         // MIN_INTRINSIC_ISIZE (which is fine, because this should only be used
         // inside a check for that flag).
         nscoord minContentSize = result;
         nscoord h;
         if (GetDefiniteSize(styleBSize, aFrame, !isInlineAxis, aPercentageBasis,
                             &h) ||
             (aPercentageBasis.isNothing() &&
              GetPercentBSize(styleBSize, aFrame, horizontalAxis, h))) {
           h = std::max(0, h - bSizeTakenByBoxSizing);
-          result = NSCoordMulDiv(h, ratioISize, ratioBSize);
+          result = ratio.ApplyTo(h);
         }
 
         if (GetDefiniteSize(styleMaxBSize, aFrame, !isInlineAxis,
                             aPercentageBasis, &h) ||
             (aPercentageBasis.isNothing() &&
              GetPercentBSize(styleMaxBSize, aFrame, horizontalAxis, h))) {
           h = std::max(0, h - bSizeTakenByBoxSizing);
-          nscoord maxISize = NSCoordMulDiv(h, ratioISize, ratioBSize);
+          nscoord maxISize = ratio.ApplyTo(h);
           if (maxISize < result) {
             result = maxISize;
           }
           if (maxISize < minContentSize) {
             minContentSize = maxISize;
           }
         }
 
         if (GetDefiniteSize(styleMinBSize, aFrame, !isInlineAxis,
                             aPercentageBasis, &h) ||
             (aPercentageBasis.isNothing() &&
              GetPercentBSize(styleMinBSize, aFrame, horizontalAxis, h))) {
           h = std::max(0, h - bSizeTakenByBoxSizing);
-          nscoord minISize = NSCoordMulDiv(h, ratioISize, ratioBSize);
+          nscoord minISize = ratio.ApplyTo(h);
           if (minISize > result) {
             result = minISize;
           }
           if (minISize > minContentSize) {
             minContentSize = minISize;
           }
         }
         if (MOZ_UNLIKELY(aFlags & nsLayoutUtils::MIN_INTRINSIC_ISIZE)) {
@@ -6862,55 +6856,51 @@ ImgDrawResult nsLayoutUtils::DrawSingleI
   return DrawImageInternal(aContext, aPresContext, image, aSamplingFilter, dest,
                            fill, aAnchorPoint ? *aAnchorPoint : fill.TopLeft(),
                            aDirty, aSVGContext, aImageFlags);
 }
 
 /* static */
 void nsLayoutUtils::ComputeSizeForDrawing(
     imgIContainer* aImage, /* outparam */ CSSIntSize& aImageSize,
-    /* outparam */ nsSize& aIntrinsicRatio,
+    /* outparam */ AspectRatio& aIntrinsicRatio,
     /* outparam */ bool& aGotWidth,
     /* outparam */ bool& aGotHeight) {
   aGotWidth = NS_SUCCEEDED(aImage->GetWidth(&aImageSize.width));
   aGotHeight = NS_SUCCEEDED(aImage->GetHeight(&aImageSize.height));
-  bool gotRatio = NS_SUCCEEDED(aImage->GetIntrinsicRatio(&aIntrinsicRatio));
-
-  if (!(aGotWidth && aGotHeight) && !gotRatio) {
+  Maybe<AspectRatio> intrinsicRatio = aImage->GetIntrinsicRatio();
+  aIntrinsicRatio = intrinsicRatio.valueOr(AspectRatio());
+
+  if (!(aGotWidth && aGotHeight) && intrinsicRatio.isNothing()) {
     // We hit an error (say, because the image failed to load or couldn't be
     // decoded) and should return zero size.
     aGotWidth = aGotHeight = true;
     aImageSize = CSSIntSize(0, 0);
-    aIntrinsicRatio = nsSize(0, 0);
   }
 }
 
 /* static */
 CSSIntSize nsLayoutUtils::ComputeSizeForDrawingWithFallback(
     imgIContainer* aImage, const nsSize& aFallbackSize) {
   CSSIntSize imageSize;
-  nsSize imageRatio;
+  AspectRatio imageRatio;
   bool gotHeight, gotWidth;
   ComputeSizeForDrawing(aImage, imageSize, imageRatio, gotWidth, gotHeight);
 
   // If we didn't get both width and height, try to compute them using the
   // intrinsic ratio of the image.
   if (gotWidth != gotHeight) {
     if (!gotWidth) {
-      if (imageRatio.height != 0) {
-        imageSize.width = NSCoordSaturatingNonnegativeMultiply(
-            imageSize.height,
-            float(imageRatio.width) / float(imageRatio.height));
+      if (imageRatio) {
+        imageSize.width = imageRatio.ApplyTo(imageSize.height);
         gotWidth = true;
       }
     } else {
-      if (imageRatio.width != 0) {
-        imageSize.height = NSCoordSaturatingNonnegativeMultiply(
-            imageSize.width,
-            float(imageRatio.height) / float(imageRatio.width));
+      if (imageRatio) {
+        imageSize.height = imageRatio.Inverted().ApplyTo(imageSize.width);
         gotHeight = true;
       }
     }
   }
 
   // If we still don't have a width or height, just use the fallback size the
   // caller provided.
   if (!gotWidth) {
--- a/layout/base/nsLayoutUtils.h
+++ b/layout/base/nsLayoutUtils.h
@@ -57,16 +57,17 @@ class nsView;
 class nsIFrame;
 class nsStyleCoord;
 class nsPIDOMWindowOuter;
 class imgIRequest;
 struct nsStyleFont;
 struct nsOverflowAreas;
 
 namespace mozilla {
+struct AspectRatio;
 class ComputedStyle;
 class PresShell;
 enum class PseudoStyleType : uint8_t;
 class EventListenerManager;
 enum class LayoutFrameType : uint8_t;
 struct IntrinsicSize;
 struct ContainerLayerParameters;
 class WritingMode;
@@ -141,16 +142,17 @@ enum class ReparentingDirection {
 };
 
 /**
  * nsLayoutUtils is a namespace class used for various helper
  * functions that are useful in multiple places in layout.  The goal
  * is not to define multiple copies of the same static helper.
  */
 class nsLayoutUtils {
+  typedef mozilla::AspectRatio AspectRatio;
   typedef mozilla::ComputedStyle ComputedStyle;
   typedef mozilla::LengthPercentage LengthPercentage;
   typedef mozilla::LengthPercentageOrAuto LengthPercentageOrAuto;
   typedef mozilla::dom::DOMRectList DOMRectList;
   typedef mozilla::layers::Layer Layer;
   typedef mozilla::layers::StackingContextHelper StackingContextHelper;
   typedef mozilla::ContainerLayerParameters ContainerLayerParameters;
   typedef mozilla::IntrinsicSize IntrinsicSize;
@@ -1321,17 +1323,17 @@ class nsLayoutUtils {
    * @param aAnchorPoint [out] A point that should be pixel-aligned by functions
    *                           like nsLayoutUtils::DrawImage. See documentation
    *                           in nsCSSRendering.h for ComputeObjectAnchorPoint.
    * @return The nsRect into which we should render the replaced content (using
    *         the same coordinate space as the passed-in aConstraintRect).
    */
   static nsRect ComputeObjectDestRect(const nsRect& aConstraintRect,
                                       const IntrinsicSize& aIntrinsicSize,
-                                      const nsSize& aIntrinsicRatio,
+                                      const AspectRatio& aIntrinsicRatio,
                                       const nsStylePosition* aStylePos,
                                       nsPoint* aAnchorPoint = nullptr);
 
   /**
    * Get the font metrics corresponding to the frame's style data.
    * @param aFrame the frame
    * @param aSizeInflation number to multiply font size by
    */
@@ -1921,18 +1923,18 @@ class nsLayoutUtils {
    * dimension.
    *
    * NOTE: This method is similar to ComputeSizeWithIntrinsicDimensions.  The
    * difference is that this one is simpler and is suited to places where we
    * have less information about the frame tree.
    */
   static void ComputeSizeForDrawing(imgIContainer* aImage,
                                     CSSIntSize& aImageSize,
-                                    nsSize& aIntrinsicRatio, bool& aGotWidth,
-                                    bool& aGotHeight);
+                                    AspectRatio& aIntrinsicRatio,
+                                    bool& aGotWidth, bool& aGotHeight);
 
   /**
    * Given an imgIContainer, this method attempts to obtain an intrinsic
    * px-valued height & width for it. If the imgIContainer has a non-pixel
    * value for either height or width, this method tries to generate a pixel
    * value for that dimension using the intrinsic ratio (if available). If,
    * after trying all these methods, no value is available for one or both
    * dimensions, the corresponding dimension of aFallbackSize is used instead.
new file mode 100644
--- /dev/null
+++ b/layout/generic/AspectRatio.h
@@ -0,0 +1,60 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* 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/. */
+
+#ifndef mozilla_AspectRatio_h
+#define mozilla_AspectRatio_h
+
+/* The aspect ratio of a box, in a "width / height" format. */
+
+#include "mozilla/Attributes.h"
+#include "mozilla/Maybe.h"
+#include "nsCoord.h"
+
+namespace mozilla {
+
+struct AspectRatio {
+  AspectRatio() : mRatio(0.0f) {}
+  explicit AspectRatio(float aRatio) : mRatio(std::max(aRatio, 0.0f)) {}
+
+  static AspectRatio FromSize(float aWidth, float aHeight) {
+    if (aWidth == 0.0f || aHeight == 0.0f) {
+      return AspectRatio();
+    }
+    return AspectRatio(aWidth / aHeight);
+  }
+
+  explicit operator bool() const { return mRatio != 0.0f; }
+
+  nscoord ApplyTo(nscoord aCoord) const {
+    MOZ_DIAGNOSTIC_ASSERT(*this);
+    return NSCoordSaturatingNonnegativeMultiply(aCoord, mRatio);
+  }
+
+  // Inverts the ratio, in order to get the height / width ratio.
+  MOZ_MUST_USE AspectRatio Inverted() const {
+    return *this ? AspectRatio(1.0f / mRatio) : *this;
+  }
+
+  bool operator==(const AspectRatio& aOther) const {
+    return mRatio == aOther.mRatio;
+  }
+
+  bool operator!=(const AspectRatio& aOther) const {
+    return !(*this == aOther);
+  }
+
+  bool operator<(const AspectRatio& aOther) const {
+    return mRatio < aOther.mRatio;
+  }
+
+ private:
+  // 0.0f represents no aspect ratio.
+  float mRatio;
+};
+
+}  // namespace mozilla
+
+#endif  // mozilla_AspectRatio_h
--- a/layout/generic/moz.build
+++ b/layout/generic/moz.build
@@ -128,16 +128,17 @@ EXPORTS += [
     'ScrollAnimationPhysics.h',
     'ScrollbarActivity.h',
     'ScrollSnap.h',
     'TextDrawTarget.h',
     'Visibility.h',
 ]
 
 EXPORTS.mozilla += [
+    'AspectRatio.h',
     'AutoCopyListener.h',
     'CSSAlignUtils.h',
     'CSSOrderAwareFrameIterator.h',
     'FrameTypeList.h',
     'ReflowInput.h',
     'ReflowOutput.h',
     'ViewportFrame.h',
     'WritingModes.h',
--- a/layout/generic/nsFlexContainerFrame.cpp
+++ b/layout/generic/nsFlexContainerFrame.cpp
@@ -387,31 +387,29 @@ class MOZ_STACK_CLASS nsFlexContainerFra
                           : LogicalSize(mWM, aCrossSize, aMainSize);
   }
 
   // Are my axes reversed with respect to what the author asked for?
   // (We may reverse the axes in the FlexboxAxisTracker constructor and set
   // this flag, to avoid reflowing our children in bottom-to-top order.)
   bool AreAxesInternallyReversed() const { return mAreAxesInternallyReversed; }
 
+  bool IsMainAxisHorizontal() const {
+    // If we're row-oriented, and our writing mode is NOT vertical,
+    // or we're column-oriented and our writing mode IS vertical,
+    // then our main axis is horizontal. This handles all cases:
+    return mIsRowOriented != mWM.IsVertical();
+  }
+
  private:
   // Delete copy-constructor & reassignment operator, to prevent accidental
   // (unnecessary) copying.
   FlexboxAxisTracker(const FlexboxAxisTracker&) = delete;
   FlexboxAxisTracker& operator=(const FlexboxAxisTracker&) = delete;
 
-  // Private because callers shouldn't need to care about physical axes
-  // (but we do internally, to provide one API).
-  bool IsMainAxisHorizontal() const {
-    // If we're row-oriented, and our writing mode is NOT vertical,
-    // or we're column-oriented and our writing mode IS vertical,
-    // then our main axis is horizontal. This handles all cases:
-    return mIsRowOriented != mWM.IsVertical();
-  }
-
   // Helpers for constructor which determine the orientation of our axes, based
   // on legacy box properties (-webkit-box-orient, -webkit-box-direction) or
   // modern flexbox properties (flex-direction, flex-wrap) depending on whether
   // the flex container is a "legacy box" (as determined by IsLegacyBox).
   void InitAxesFromLegacyProps(const nsFlexContainerFrame* aFlexContainer);
   void InitAxesFromModernProps(const nsFlexContainerFrame* aFlexContainer);
 
   // XXXdholbert [BEGIN DEPRECATED]
@@ -620,20 +618,18 @@ class nsFlexContainerFrame::FlexItem : p
       // regardless of mFlexShrink, we should just return 0.
       // (This is really a special-case for when mFlexShrink is infinity, to
       // avoid performing mFlexShrink * mFlexBaseSize = inf * 0 = undefined.)
       return 0.0f;
     }
     return mFlexShrink * mFlexBaseSize;
   }
 
-  // Returns a LogicalSize representing the flex item's logical intrinsic ratio
-  // (ISize:BSize), as expressed in the *flex container's* writing mode.
-  const LogicalSize& IntrinsicRatio() const { return mIntrinsicRatio; }
-  bool HasIntrinsicRatio() const { return !mIntrinsicRatio.IsAllZero(); }
+  const AspectRatio& IntrinsicRatio() const { return mIntrinsicRatio; }
+  bool HasIntrinsicRatio() const { return !!mIntrinsicRatio; }
 
   // Getters for margin:
   // ===================
   const nsMargin& GetMargin() const { return mMargin; }
 
   // Returns the margin component for a given mozilla::Side
   nscoord GetMarginComponentForSide(mozilla::Side aSide) const {
     return mMargin.Side(aSide);
@@ -841,17 +837,17 @@ class nsFlexContainerFrame::FlexItem : p
   // Helper called by the constructor, to set mNeedsMinSizeAutoResolution:
   void CheckForMinSizeAuto(const ReflowInput& aFlexItemReflowInput,
                            const FlexboxAxisTracker& aAxisTracker);
 
   // Values that we already know in constructor (and are hence mostly 'const'):
   nsIFrame* const mFrame;  // The flex item's frame.
   const float mFlexGrow;
   const float mFlexShrink;
-  const LogicalSize mIntrinsicRatio;
+  const AspectRatio mIntrinsicRatio;
   const nsMargin mBorderPadding;
   nsMargin mMargin;  // non-const because we need to resolve auto margins
 
   // These are non-const so that we can lazily update them with the item's
   // intrinsic size (obtained via a "measuring" reflow), when necessary.
   // (e.g. for "flex-basis:auto;height:auto" & "min-height:auto")
   nscoord mFlexBaseSize;
   nscoord mMainMinSize;
@@ -1447,26 +1443,27 @@ static nscoord CrossSizeToUseWithRatio(c
   }
 
   // Indefinite cross-size.
   return NS_AUTOHEIGHT;
 }
 
 // Convenience function; returns a main-size, given a cross-size and an
 // intrinsic ratio. The caller is responsible for ensuring that the passed-in
-// intrinsic ratio must not have 0 in its cross-axis component (or else we'll
-// divide by 0).
+// intrinsic ratio is not zero.
 static nscoord MainSizeFromAspectRatio(nscoord aCrossSize,
-                                       const LogicalSize& aIntrinsicRatio,
+                                       const AspectRatio& aIntrinsicRatio,
                                        const FlexboxAxisTracker& aAxisTracker) {
-  MOZ_ASSERT(aAxisTracker.GetCrossComponent(aIntrinsicRatio) != 0,
+  MOZ_ASSERT(aIntrinsicRatio,
              "Invalid ratio; will divide by 0! Caller should've checked...");
-  return NSCoordMulDiv(aCrossSize,
-                       aAxisTracker.GetMainComponent(aIntrinsicRatio),
-                       aAxisTracker.GetCrossComponent(aIntrinsicRatio));
+  AspectRatio ratio = aAxisTracker.IsMainAxisHorizontal()
+                          ? aIntrinsicRatio
+                          : aIntrinsicRatio.Inverted();
+
+  return ratio.ApplyTo(aCrossSize);
 }
 
 // Partially resolves "min-[width|height]:auto" and returns the resulting value.
 // By "partially", I mean we don't consider the min-content size (but we do
 // consider flex-basis, main max-size, and the intrinsic aspect ratio).
 // The caller is responsible for computing & considering the min-content size
 // in combination with the partially-resolved value that this function returns.
 //
@@ -1501,17 +1498,17 @@ static nscoord PartiallyResolveAutoMinSi
   }
 
   // * if the item has no intrinsic aspect ratio, its min-content size:
   //  --- SKIPPING THIS IN THIS FUNCTION --- caller's responsibility.
 
   // * if the item has an intrinsic aspect ratio, the width (height) calculated
   //   from the aspect ratio and any definite size constraints in the opposite
   //   dimension.
-  if (aAxisTracker.GetCrossComponent(aFlexItem.IntrinsicRatio()) != 0) {
+  if (aFlexItem.IntrinsicRatio()) {
     // We have a usable aspect ratio. (not going to divide by 0)
     const bool useMinSizeIfCrossSizeIsIndefinite = true;
     nscoord crossSizeToUseWithRatio = CrossSizeToUseWithRatio(
         aFlexItem, aItemReflowInput, useMinSizeIfCrossSizeIsIndefinite,
         aAxisTracker);
     nscoord minMainSizeFromRatio = MainSizeFromAspectRatio(
         crossSizeToUseWithRatio, aFlexItem.IntrinsicRatio(), aAxisTracker);
     minMainSize = std::min(minMainSize, minMainSizeFromRatio);
@@ -1531,17 +1528,17 @@ static bool ResolveAutoFlexBasisFromRati
              "Should only be called to resolve an 'auto' flex-basis");
   // If the flex item has ...
   //  - an intrinsic aspect ratio,
   //  - a [used] flex-basis of 'main-size' [auto?]
   //    [We have this, if we're here.]
   //  - a definite cross size
   // then the flex base size is calculated from its inner cross size and the
   // flex item’s intrinsic aspect ratio.
-  if (aAxisTracker.GetCrossComponent(aFlexItem.IntrinsicRatio()) != 0) {
+  if (aFlexItem.IntrinsicRatio()) {
     // We have a usable aspect ratio. (not going to divide by 0)
     const bool useMinSizeIfCrossSizeIsIndefinite = false;
     nscoord crossSizeToUseWithRatio = CrossSizeToUseWithRatio(
         aFlexItem, aItemReflowInput, useMinSizeIfCrossSizeIsIndefinite,
         aAxisTracker);
     if (crossSizeToUseWithRatio != NS_AUTOHEIGHT) {
       // We have a definite cross-size
       nscoord mainSizeFromRatio = MainSizeFromAspectRatio(
@@ -1606,18 +1603,17 @@ void nsFlexContainerFrame::ResolveAutoFl
 
   nscoord resolvedMinSize;  // (only set/used if isMainMinSizeAuto==true)
   bool minSizeNeedsToMeasureContent = false;  // assume the best
   if (isMainMinSizeAuto) {
     // Resolve the min-size, except for considering the min-content size.
     // (We'll consider that later, if we need to.)
     resolvedMinSize =
         PartiallyResolveAutoMinSize(aFlexItem, aItemReflowInput, aAxisTracker);
-    if (resolvedMinSize > 0 &&
-        aAxisTracker.GetCrossComponent(aFlexItem.IntrinsicRatio()) == 0) {
+    if (resolvedMinSize > 0 && !aFlexItem.IntrinsicRatio()) {
       // We don't have a usable aspect ratio, so we need to consider our
       // min-content size as another candidate min-size, which we'll have to
       // min() with the current resolvedMinSize.
       // (If resolvedMinSize were already at 0, we could skip this measurement
       // because it can't go any lower. But it's not 0, so we need it.)
       minSizeNeedsToMeasureContent = true;
     }
   }
@@ -1867,19 +1863,17 @@ FlexItem::FlexItem(ReflowInput& aFlexIte
                    float aFlexShrink, nscoord aFlexBaseSize,
                    nscoord aMainMinSize, nscoord aMainMaxSize,
                    nscoord aTentativeCrossSize, nscoord aCrossMinSize,
                    nscoord aCrossMaxSize,
                    const FlexboxAxisTracker& aAxisTracker)
     : mFrame(aFlexItemReflowInput.mFrame),
       mFlexGrow(aFlexGrow),
       mFlexShrink(aFlexShrink),
-      // We store the intrinsic ratio in the *flex container's* WM:
-      mIntrinsicRatio(aAxisTracker.GetWritingMode(),
-                      mFrame->GetIntrinsicRatio()),
+      mIntrinsicRatio(mFrame->GetIntrinsicRatio()),
       mBorderPadding(aFlexItemReflowInput.ComputedPhysicalBorderPadding()),
       mMargin(aFlexItemReflowInput.ComputedPhysicalMargin()),
       mMainMinSize(aMainMinSize),
       mMainMaxSize(aMainMaxSize),
       mCrossMinSize(aCrossMinSize),
       mCrossMaxSize(aCrossMaxSize),
       mMainPosn(0),
       mCrossSize(aTentativeCrossSize),
@@ -1971,17 +1965,16 @@ FlexItem::FlexItem(ReflowInput& aFlexIte
 // Simplified constructor for creating a special "strut" FlexItem, for a child
 // with visibility:collapse. The strut has 0 main-size, and it only exists to
 // impose a minimum cross size on whichever FlexLine it ends up in.
 FlexItem::FlexItem(nsIFrame* aChildFrame, nscoord aCrossSize,
                    WritingMode aContainerWM)
     : mFrame(aChildFrame),
       mFlexGrow(0.0f),
       mFlexShrink(0.0f),
-      mIntrinsicRatio(aContainerWM),
       // mBorderPadding uses default constructor,
       // mMargin uses default constructor,
       mFlexBaseSize(0),
       mMainMinSize(0),
       mMainMaxSize(0),
       mCrossMinSize(0),
       mCrossMaxSize(0),
       mMainSize(0),
--- a/layout/generic/nsFrame.cpp
+++ b/layout/generic/nsFrame.cpp
@@ -5516,27 +5516,27 @@ nsIFrame::IntrinsicISizeOffsetData nsIFr
 }
 
 /* virtual */
 IntrinsicSize nsFrame::GetIntrinsicSize() {
   return IntrinsicSize();  // default is width/height set to eStyleUnit_None
 }
 
 /* virtual */
-nsSize nsFrame::GetIntrinsicRatio() { return nsSize(0, 0); }
+AspectRatio nsFrame::GetIntrinsicRatio() { return AspectRatio(); }
 
 /* virtual */
 LogicalSize nsFrame::ComputeSize(gfxContext* aRenderingContext, WritingMode aWM,
                                  const LogicalSize& aCBSize,
                                  nscoord aAvailableISize,
                                  const LogicalSize& aMargin,
                                  const LogicalSize& aBorder,
                                  const LogicalSize& aPadding,
                                  ComputeSizeFlags aFlags) {
-  MOZ_ASSERT(GetIntrinsicRatio() == nsSize(0, 0),
+  MOZ_ASSERT(!GetIntrinsicRatio(),
              "Please override this method and call "
              "nsFrame::ComputeSizeWithIntrinsicDimensions instead.");
   LogicalSize result =
       ComputeAutoSize(aRenderingContext, aWM, aCBSize, aAvailableISize, aMargin,
                       aBorder, aPadding, aFlags);
   const nsStylePosition* stylePos = StylePosition();
 
   LogicalSize boxSizingAdjust(aWM);
@@ -5778,20 +5778,22 @@ LogicalSize nsFrame::ComputeSize(gfxCont
   result.ISize(aWM) = std::max(0, result.ISize(aWM));
   result.BSize(aWM) = std::max(0, result.BSize(aWM));
 
   return result;
 }
 
 LogicalSize nsFrame::ComputeSizeWithIntrinsicDimensions(
     gfxContext* aRenderingContext, WritingMode aWM,
-    const IntrinsicSize& aIntrinsicSize, nsSize aIntrinsicRatio,
+    const IntrinsicSize& aIntrinsicSize, const AspectRatio& aIntrinsicRatio,
     const LogicalSize& aCBSize, const LogicalSize& aMargin,
     const LogicalSize& aBorder, const LogicalSize& aPadding,
     ComputeSizeFlags aFlags) {
+  auto logicalRatio =
+      aWM.IsVertical() ? aIntrinsicRatio.Inverted() : aIntrinsicRatio;
   const nsStylePosition* stylePos = StylePosition();
   const auto* inlineStyleCoord = &stylePos->ISize(aWM);
   const auto* blockStyleCoord = &stylePos->BSize(aWM);
   auto* parentFrame = GetParent();
   const bool isGridItem = parentFrame && parentFrame->IsGridContainerFrame() &&
                           !HasAnyStateBits(NS_FRAME_OUT_OF_FLOW);
   const bool isFlexItem =
       parentFrame && parentFrame->IsFlexContainerFrame() &&
@@ -5910,20 +5912,16 @@ LogicalSize nsFrame::ComputeSizeWithIntr
   const bool hasIntrinsicISize = isizeCoord.isSome();
   nscoord intrinsicISize = std::max(0, isizeCoord.valueOr(0));
 
   const auto& bsizeCoord =
       isVertical ? aIntrinsicSize.width : aIntrinsicSize.height;
   const bool hasIntrinsicBSize = bsizeCoord.isSome();
   nscoord intrinsicBSize = std::max(0, bsizeCoord.valueOr(0));
 
-  NS_ASSERTION(aIntrinsicRatio.width >= 0 && aIntrinsicRatio.height >= 0,
-               "Intrinsic ratio has a negative component!");
-  LogicalSize logicalRatio(aWM, aIntrinsicRatio);
-
   if (!isAutoISize) {
     iSize = ComputeISizeValue(
         aRenderingContext, aCBSize.ISize(aWM), boxSizingAdjust.ISize(aWM),
         boxSizingToMarginEdgeISize, *inlineStyleCoord, aFlags);
   } else if (MOZ_UNLIKELY(isGridItem)) {
     MOZ_ASSERT(!IS_TRUE_OVERFLOW_CONTAINER(this));
     // 'auto' inline-size for grid-level box - apply 'stretch' as needed:
     auto cbSize = aCBSize.ISize(aWM);
@@ -5932,17 +5930,17 @@ LogicalSize nsFrame::ComputeSizeWithIntr
         auto inlineAxisAlignment =
             aWM.IsOrthogonalTo(GetParent()->GetWritingMode())
                 ? stylePos->UsedAlignSelf(GetParent()->Style())
                 : stylePos->UsedJustifySelf(GetParent()->Style());
         // Note: 'normal' means 'start' for elements with an intrinsic size
         // or ratio in the relevant dimension, otherwise 'stretch'.
         // https://drafts.csswg.org/css-grid/#grid-item-sizing
         if ((inlineAxisAlignment == NS_STYLE_ALIGN_NORMAL &&
-             !hasIntrinsicISize && !(logicalRatio.ISize(aWM) > 0)) ||
+             !hasIntrinsicISize && !logicalRatio) ||
             inlineAxisAlignment == NS_STYLE_ALIGN_STRETCH) {
           stretchI = eStretch;
         }
       }
       if (stretchI != eNoStretch ||
           (aFlags & ComputeSizeFlags::eIClampMarginBoxMinSize)) {
         iSize =
             std::max(nscoord(0), cbSize - aPadding.ISize(aWM) -
@@ -5999,17 +5997,17 @@ LogicalSize nsFrame::ComputeSizeWithIntr
         auto blockAxisAlignment =
             !aWM.IsOrthogonalTo(GetParent()->GetWritingMode())
                 ? stylePos->UsedAlignSelf(GetParent()->Style())
                 : stylePos->UsedJustifySelf(GetParent()->Style());
         // Note: 'normal' means 'start' for elements with an intrinsic size
         // or ratio in the relevant dimension, otherwise 'stretch'.
         // https://drafts.csswg.org/css-grid/#grid-item-sizing
         if ((blockAxisAlignment == NS_STYLE_ALIGN_NORMAL &&
-             !hasIntrinsicBSize && !(logicalRatio.BSize(aWM) > 0)) ||
+             !hasIntrinsicBSize && !logicalRatio) ||
             blockAxisAlignment == NS_STYLE_ALIGN_STRETCH) {
           stretchB = eStretch;
         }
       }
       if (stretchB != eNoStretch ||
           (aFlags & ComputeSizeFlags::eBClampMarginBoxMinSize)) {
         bSize =
             std::max(nscoord(0), cbSize - aPadding.BSize(aWM) -
@@ -6054,20 +6052,19 @@ LogicalSize nsFrame::ComputeSizeWithIntr
       // 'auto' iSize, 'auto' bSize
 
       // Get tentative values - CSS 2.1 sections 10.3.2 and 10.6.2:
 
       nscoord tentISize, tentBSize;
 
       if (hasIntrinsicISize) {
         tentISize = intrinsicISize;
-      } else if (hasIntrinsicBSize && logicalRatio.BSize(aWM) > 0) {
-        tentISize = NSCoordMulDiv(intrinsicBSize, logicalRatio.ISize(aWM),
-                                  logicalRatio.BSize(aWM));
-      } else if (logicalRatio.ISize(aWM) > 0) {
+      } else if (hasIntrinsicBSize && logicalRatio) {
+        tentISize = logicalRatio.ApplyTo(intrinsicBSize);
+      } else if (logicalRatio) {
         tentISize =
             aCBSize.ISize(aWM) - boxSizingToMarginEdgeISize;  // XXX scrollbar?
         if (tentISize < 0) tentISize = 0;
       } else {
         tentISize = nsPresContext::CSSPixelsToAppUnits(300);
       }
 
       // If we need to clamp the inline size to fit the CB, we use the 'stretch'
@@ -6075,77 +6072,62 @@ LogicalSize nsFrame::ComputeSizeWithIntr
       // unless we have 'stretch' in the other axis.
       if ((aFlags & ComputeSizeFlags::eIClampMarginBoxMinSize) &&
           stretchI != eStretch && tentISize > iSize) {
         stretchI = (stretchB == eStretch ? eStretch : eStretchPreservingRatio);
       }
 
       if (hasIntrinsicBSize) {
         tentBSize = intrinsicBSize;
-      } else if (logicalRatio.ISize(aWM) > 0) {
-        tentBSize = NSCoordMulDiv(tentISize, logicalRatio.BSize(aWM),
-                                  logicalRatio.ISize(aWM));
+      } else if (logicalRatio) {
+        tentBSize = logicalRatio.Inverted().ApplyTo(tentISize);
       } else {
         tentBSize = nsPresContext::CSSPixelsToAppUnits(150);
       }
 
       // (ditto the comment about clamping the inline size above)
       if ((aFlags & ComputeSizeFlags::eBClampMarginBoxMinSize) &&
           stretchB != eStretch && tentBSize > bSize) {
         stretchB = (stretchI == eStretch ? eStretch : eStretchPreservingRatio);
       }
 
-      if (aIntrinsicRatio != nsSize(0, 0)) {
+      if (logicalRatio) {
         if (stretchI == eStretch) {
           tentISize = iSize;  // * / 'stretch'
           if (stretchB == eStretch) {
             tentBSize = bSize;  // 'stretch' / 'stretch'
-          } else if (stretchB == eStretchPreservingRatio &&
-                     logicalRatio.ISize(aWM) > 0) {
+          } else if (stretchB == eStretchPreservingRatio) {
             // 'normal' / 'stretch'
-            tentBSize = NSCoordMulDiv(iSize, logicalRatio.BSize(aWM),
-                                      logicalRatio.ISize(aWM));
+            tentBSize = logicalRatio.Inverted().ApplyTo(iSize);
           }
         } else if (stretchB == eStretch) {
           tentBSize = bSize;  // 'stretch' / * (except 'stretch')
-          if (stretchI == eStretchPreservingRatio &&
-              logicalRatio.BSize(aWM) > 0) {
+          if (stretchI == eStretchPreservingRatio) {
             // 'stretch' / 'normal'
-            tentISize = NSCoordMulDiv(bSize, logicalRatio.ISize(aWM),
-                                      logicalRatio.BSize(aWM));
+            tentISize = logicalRatio.ApplyTo(bSize);
           }
         } else if (stretchI == eStretchPreservingRatio) {
           tentISize = iSize;  // * (except 'stretch') / 'normal'
-          if (logicalRatio.ISize(aWM) > 0) {
-            tentBSize = NSCoordMulDiv(iSize, logicalRatio.BSize(aWM),
-                                      logicalRatio.ISize(aWM));
-          }
+          tentBSize = logicalRatio.Inverted().ApplyTo(iSize);
           if (stretchB == eStretchPreservingRatio && tentBSize > bSize) {
             // Stretch within the CB size with preserved intrinsic ratio.
             tentBSize = bSize;  // 'normal' / 'normal'
-            if (logicalRatio.BSize(aWM) > 0) {
-              tentISize = NSCoordMulDiv(bSize, logicalRatio.ISize(aWM),
-                                        logicalRatio.BSize(aWM));
-            }
+            tentISize = logicalRatio.ApplyTo(bSize);
           }
         } else if (stretchB == eStretchPreservingRatio) {
           tentBSize = bSize;  // 'normal' / * (except 'normal' and 'stretch')
-          if (logicalRatio.BSize(aWM) > 0) {
-            tentISize = NSCoordMulDiv(bSize, logicalRatio.ISize(aWM),
-                                      logicalRatio.BSize(aWM));
-          }
+          tentISize = logicalRatio.ApplyTo(bSize);
         }
       }
 
       // ComputeAutoSizeWithIntrinsicDimensions preserves the ratio when
       // applying the min/max-size.  We don't want that when we have 'stretch'
       // in either axis because tentISize/tentBSize is likely not according to
       // ratio now.
-      if (aIntrinsicRatio != nsSize(0, 0) && stretchI != eStretch &&
-          stretchB != eStretch) {
+      if (logicalRatio && stretchI != eStretch && stretchB != eStretch) {
         nsSize autoSize = nsLayoutUtils::ComputeAutoSizeWithIntrinsicDimensions(
             minISize, minBSize, maxISize, maxBSize, tentISize, tentBSize);
         // The nsSize that ComputeAutoSizeWithIntrinsicDimensions returns will
         // actually contain logical values if the parameters passed to it were
         // logical coordinates, so we do NOT perform a physical-to-logical
         // conversion here, but just assign the fields directly to our result.
         iSize = autoSize.width;
         bSize = autoSize.height;
@@ -6153,38 +6135,36 @@ LogicalSize nsFrame::ComputeSizeWithIntr
         // Not honoring an intrinsic ratio: clamp the dimensions independently.
         iSize = NS_CSS_MINMAX(tentISize, minISize, maxISize);
         bSize = NS_CSS_MINMAX(tentBSize, minBSize, maxBSize);
       }
     } else {
       // 'auto' iSize, non-'auto' bSize
       bSize = NS_CSS_MINMAX(bSize, minBSize, maxBSize);
       if (stretchI != eStretch) {
-        if (logicalRatio.BSize(aWM) > 0) {
-          iSize = NSCoordMulDiv(bSize, logicalRatio.ISize(aWM),
-                                logicalRatio.BSize(aWM));
+        if (logicalRatio) {
+          iSize = logicalRatio.ApplyTo(bSize);
         } else if (hasIntrinsicISize) {
           if (!((aFlags & ComputeSizeFlags::eIClampMarginBoxMinSize) &&
                 intrinsicISize > iSize)) {
             iSize = intrinsicISize;
           }  // else - leave iSize as is to fill the CB
         } else {
           iSize = nsPresContext::CSSPixelsToAppUnits(300);
         }
       }  // else - leave iSize as is to fill the CB
       iSize = NS_CSS_MINMAX(iSize, minISize, maxISize);
     }
   } else {
     if (isAutoBSize) {
       // non-'auto' iSize, 'auto' bSize
       iSize = NS_CSS_MINMAX(iSize, minISize, maxISize);
       if (stretchB != eStretch) {
-        if (logicalRatio.ISize(aWM) > 0) {
-          bSize = NSCoordMulDiv(iSize, logicalRatio.BSize(aWM),
-                                logicalRatio.ISize(aWM));
+        if (logicalRatio) {
+          bSize = logicalRatio.Inverted().ApplyTo(iSize);
         } else if (hasIntrinsicBSize) {
           if (!((aFlags & ComputeSizeFlags::eBClampMarginBoxMinSize) &&
                 intrinsicBSize > bSize)) {
             bSize = intrinsicBSize;
           }  // else - leave bSize as is to fill the CB
         } else {
           bSize = nsPresContext::CSSPixelsToAppUnits(150);
         }
--- a/layout/generic/nsFrame.h
+++ b/layout/generic/nsFrame.h
@@ -268,31 +268,32 @@ class nsFrame : public nsBox {
   nscoord GetPrefISize(gfxContext* aRenderingContext) override;
   void AddInlineMinISize(gfxContext* aRenderingContext,
                          InlineMinISizeData* aData) override;
   void AddInlinePrefISize(gfxContext* aRenderingContext,
                           InlinePrefISizeData* aData) override;
   IntrinsicISizeOffsetData IntrinsicISizeOffsets(
       nscoord aPercentageBasis = NS_UNCONSTRAINEDSIZE) override;
   mozilla::IntrinsicSize GetIntrinsicSize() override;
-  nsSize GetIntrinsicRatio() override;
+  mozilla::AspectRatio GetIntrinsicRatio() override;
 
   mozilla::LogicalSize ComputeSize(
       gfxContext* aRenderingContext, mozilla::WritingMode aWM,
       const mozilla::LogicalSize& aCBSize, nscoord aAvailableISize,
       const mozilla::LogicalSize& aMargin, const mozilla::LogicalSize& aBorder,
       const mozilla::LogicalSize& aPadding, ComputeSizeFlags aFlags) override;
 
   /**
    * Calculate the used values for 'width' and 'height' for a replaced element.
    *   http://www.w3.org/TR/CSS21/visudet.html#min-max-widths
    */
   mozilla::LogicalSize ComputeSizeWithIntrinsicDimensions(
       gfxContext* aRenderingContext, mozilla::WritingMode aWM,
-      const mozilla::IntrinsicSize& aIntrinsicSize, nsSize aIntrinsicRatio,
+      const mozilla::IntrinsicSize& aIntrinsicSize,
+      const mozilla::AspectRatio& aIntrinsicRatio,
       const mozilla::LogicalSize& aCBSize, const mozilla::LogicalSize& aMargin,
       const mozilla::LogicalSize& aBorder, const mozilla::LogicalSize& aPadding,
       ComputeSizeFlags aFlags);
 
   // Compute tight bounds assuming this frame honours its border, background
   // and outline, its children's tight bounds, and nothing else.
   nsRect ComputeSimpleTightBounds(mozilla::gfx::DrawTarget* aDrawTarget) const;
 
--- a/layout/generic/nsHTMLCanvasFrame.cpp
+++ b/layout/generic/nsHTMLCanvasFrame.cpp
@@ -47,19 +47,19 @@ static IntrinsicSize IntrinsicSizeFromCa
 /* Helper for our nsIFrame::GetIntrinsicRatio() impl. Takes the result of
  * "GetCanvasSize()" as a parameter, which may help avoid redundant
  * indirect calls to GetCanvasSize().
  *
  * @param aCanvasSizeInPx The canvas's size in CSS pixels, as returned
  *                        by GetCanvasSize().
  * @return The canvas's intrinsic ratio, as a nsSize.
  */
-static nsSize IntrinsicRatioFromCanvasSize(const nsIntSize& aCanvasSizeInPx) {
-  return nsSize(nsPresContext::CSSPixelsToAppUnits(aCanvasSizeInPx.width),
-                nsPresContext::CSSPixelsToAppUnits(aCanvasSizeInPx.height));
+static AspectRatio IntrinsicRatioFromCanvasSize(
+    const nsIntSize& aCanvasSizeInPx) {
+  return AspectRatio::FromSize(aCanvasSizeInPx.width, aCanvasSizeInPx.height);
 }
 
 class nsDisplayCanvas final : public nsDisplayItem {
  public:
   nsDisplayCanvas(nsDisplayListBuilder* aBuilder, nsIFrame* aFrame)
       : nsDisplayItem(aBuilder, aFrame) {
     MOZ_COUNT_CTOR(nsDisplayCanvas);
   }
@@ -81,17 +81,17 @@ class nsDisplayCanvas final : public nsD
       // object-fit/object-position CSS properties), clipped to the container's
       // content box (which is what GetBounds() returns). So, we grab those
       // rects and intersect them.
       nsRect constraintRect = GetBounds(aBuilder, aSnap);
 
       // Need intrinsic size & ratio, for ComputeObjectDestRect:
       nsIntSize canvasSize = f->GetCanvasSize();
       IntrinsicSize intrinsicSize = IntrinsicSizeFromCanvasSize(canvasSize);
-      nsSize intrinsicRatio = IntrinsicRatioFromCanvasSize(canvasSize);
+      AspectRatio intrinsicRatio = IntrinsicRatioFromCanvasSize(canvasSize);
 
       const nsRect destRect = nsLayoutUtils::ComputeObjectDestRect(
           constraintRect, intrinsicSize, intrinsicRatio, f->StylePosition());
       return nsRegion(destRect.Intersect(constraintRect));
     }
     return result;
   }
 
@@ -140,17 +140,18 @@ class nsDisplayCanvas final : public nsD
         data->UpdateCompositableClient(aBuilder.GetRenderRoot());
 
         // Push IFrame for async image pipeline.
         // XXX Remove this once partial display list update is supported.
 
         nsIntSize canvasSizeInPx = data->GetSize();
         IntrinsicSize intrinsicSize =
             IntrinsicSizeFromCanvasSize(canvasSizeInPx);
-        nsSize intrinsicRatio = IntrinsicRatioFromCanvasSize(canvasSizeInPx);
+        AspectRatio intrinsicRatio =
+            IntrinsicRatioFromCanvasSize(canvasSizeInPx);
 
         nsRect area =
             mFrame->GetContentRectRelativeToSelf() + ToReferenceFrame();
         nsRect dest = nsLayoutUtils::ComputeObjectDestRect(
             area, intrinsicSize, intrinsicRatio, mFrame->StylePosition());
 
         LayoutDeviceRect bounds = LayoutDeviceRect::FromAppUnits(
             dest, mFrame->PresContext()->AppUnitsPerDevPixel());
@@ -293,34 +294,34 @@ nscoord nsHTMLCanvasFrame::GetPrefISize(
 IntrinsicSize nsHTMLCanvasFrame::GetIntrinsicSize() {
   if (StyleDisplay()->IsContainSize()) {
     return IntrinsicSize(0, 0);
   }
   return IntrinsicSizeFromCanvasSize(GetCanvasSize());
 }
 
 /* virtual */
-nsSize nsHTMLCanvasFrame::GetIntrinsicRatio() {
+AspectRatio nsHTMLCanvasFrame::GetIntrinsicRatio() {
   if (StyleDisplay()->IsContainSize()) {
-    return nsSize(0, 0);
+    return AspectRatio();
   }
   return IntrinsicRatioFromCanvasSize(GetCanvasSize());
 }
 
 /* virtual */
 LogicalSize nsHTMLCanvasFrame::ComputeSize(
     gfxContext* aRenderingContext, WritingMode aWM, const LogicalSize& aCBSize,
     nscoord aAvailableISize, const LogicalSize& aMargin,
     const LogicalSize& aBorder, const LogicalSize& aPadding,
     ComputeSizeFlags aFlags) {
   IntrinsicSize intrinsicSize;
-  nsSize intrinsicRatio;
+  AspectRatio intrinsicRatio;
   if (StyleDisplay()->IsContainSize()) {
     intrinsicSize = IntrinsicSize(0, 0);
-    // intrinsicRatio is already implicitly 0,0 via default ctor.
+    // intrinsicRatio is already implicitly zero via default ctor.
   } else {
     nsIntSize canvasSizeInPx = GetCanvasSize();
     intrinsicSize = IntrinsicSizeFromCanvasSize(canvasSizeInPx);
     intrinsicRatio = IntrinsicRatioFromCanvasSize(canvasSizeInPx);
   }
 
   return ComputeSizeWithIntrinsicDimensions(
       aRenderingContext, aWM, intrinsicSize, intrinsicRatio, aCBSize, aMargin,
@@ -411,17 +412,17 @@ already_AddRefed<Layer> nsHTMLCanvasFram
     return nullptr;
 
   CanvasLayer* oldLayer = static_cast<CanvasLayer*>(
       aManager->GetLayerBuilder()->GetLeafLayerFor(aBuilder, aItem));
   RefPtr<Layer> layer = element->GetCanvasLayer(aBuilder, oldLayer, aManager);
   if (!layer) return nullptr;
 
   IntrinsicSize intrinsicSize = IntrinsicSizeFromCanvasSize(canvasSizeInPx);
-  nsSize intrinsicRatio = IntrinsicRatioFromCanvasSize(canvasSizeInPx);
+  AspectRatio intrinsicRatio = IntrinsicRatioFromCanvasSize(canvasSizeInPx);
 
   nsRect dest = nsLayoutUtils::ComputeObjectDestRect(
       area, intrinsicSize, intrinsicRatio, StylePosition());
 
   gfxRect destGFXRect = presContext->AppUnitsToGfxUnits(dest);
 
   // Transform the canvas into the right place
   gfxPoint p = destGFXRect.TopLeft() + aContainerParameters.mOffset;
--- a/layout/generic/nsHTMLCanvasFrame.h
+++ b/layout/generic/nsHTMLCanvasFrame.h
@@ -59,17 +59,17 @@ class nsHTMLCanvasFrame final : public n
                                  WebRenderCanvasData* aCanvasData);
 
   /* get the size of the canvas's image */
   nsIntSize GetCanvasSize();
 
   virtual nscoord GetMinISize(gfxContext* aRenderingContext) override;
   virtual nscoord GetPrefISize(gfxContext* aRenderingContext) override;
   virtual mozilla::IntrinsicSize GetIntrinsicSize() override;
-  virtual nsSize GetIntrinsicRatio() override;
+  virtual mozilla::AspectRatio GetIntrinsicRatio() override;
 
   virtual mozilla::LogicalSize ComputeSize(
       gfxContext* aRenderingContext, mozilla::WritingMode aWritingMode,
       const mozilla::LogicalSize& aCBSize, nscoord aAvailableISize,
       const mozilla::LogicalSize& aMargin, const mozilla::LogicalSize& aBorder,
       const mozilla::LogicalSize& aPadding, ComputeSizeFlags aFlags) override;
 
   virtual void Reflow(nsPresContext* aPresContext, ReflowOutput& aDesiredSize,
--- a/layout/generic/nsIFrame.h
+++ b/layout/generic/nsIFrame.h
@@ -48,16 +48,17 @@
 
 #include <algorithm>
 #include <stdio.h>
 
 #include "CaretAssociationHint.h"
 #include "FrameProperties.h"
 #include "LayoutConstants.h"
 #include "mozilla/layout/FrameChildList.h"
+#include "mozilla/AspectRatio.h"
 #include "mozilla/Maybe.h"
 #include "mozilla/SmallPointerArray.h"
 #include "mozilla/WritingModes.h"
 #include "nsDirection.h"
 #include "nsFrameList.h"
 #include "nsFrameState.h"
 #include "mozilla/ReflowOutput.h"
 #include "nsITheme.h"
@@ -2366,25 +2367,24 @@ class nsIFrame : public nsQueryFrame {
    *   i.e. the Containing Block's inline-size
    */
   IntrinsicISizeOffsetData IntrinsicBSizeOffsets(
       nscoord aPercentageBasis = NS_UNCONSTRAINEDSIZE);
 
   virtual mozilla::IntrinsicSize GetIntrinsicSize() = 0;
 
   /**
-   * Get the intrinsic ratio of this element, or nsSize(0,0) if it has
-   * no intrinsic ratio.  The intrinsic ratio is the ratio of the
-   * height/width of a box with an intrinsic size or the intrinsic
-   * aspect ratio of a scalable vector image without an intrinsic size.
+   * Get the intrinsic ratio of this element, or a default-constructed
+   * AspectRatio if it has no intrinsic ratio.
    *
-   * Either one of the sides may be zero, indicating a zero or infinite
-   * ratio.
-   */
-  virtual nsSize GetIntrinsicRatio() = 0;
+   * The intrinsic ratio is the ratio of the width/height of a box with an
+   * intrinsic size or the intrinsic aspect ratio of a scalable vector image
+   * without an intrinsic size.
+   */
+  virtual mozilla::AspectRatio GetIntrinsicRatio() = 0;
 
   /**
    * Bit-flags to pass to ComputeSize in |aFlags| parameter.
    */
   enum ComputeSizeFlags {
     eDefault = 0,
     /**
      * Set if the frame is in a context where non-replaced blocks should
--- a/layout/generic/nsImageFrame.cpp
+++ b/layout/generic/nsImageFrame.cpp
@@ -204,17 +204,16 @@ nsImageFrame* nsImageFrame::CreateContin
 
 NS_IMPL_FRAMEARENA_HELPERS(nsImageFrame)
 
 nsImageFrame::nsImageFrame(ComputedStyle* aStyle, nsPresContext* aPresContext,
                            ClassID aID, Kind aKind)
     : nsAtomicContainerFrame(aStyle, aPresContext, aID),
       mComputedSize(0, 0),
       mIntrinsicSize(0, 0),
-      mIntrinsicRatio(0, 0),
       mKind(aKind),
       mContentURLRequestRegistered(false),
       mDisplayingIcon(false),
       mFirstFrameComplete(false),
       mReflowCallbackPosted(false),
       mForceSyncDecoding(false) {
   EnableVisibilityTracking();
 }
@@ -478,25 +477,23 @@ bool nsImageFrame::UpdateIntrinsicSize(i
   return mIntrinsicSize != oldIntrinsicSize;
 }
 
 bool nsImageFrame::UpdateIntrinsicRatio(imgIContainer* aImage) {
   MOZ_ASSERT(aImage, "null image");
 
   if (!aImage) return false;
 
-  nsSize oldIntrinsicRatio = mIntrinsicRatio;
-
   // Set intrinsic ratio to match aImage's reported intrinsic ratio.
   // But if we have 'contain:size', or aImage hasn't loaded enough to report
   // useful ratio, we fall back to 0,0.
-  if (StyleDisplay()->IsContainSize() ||
-      NS_FAILED(aImage->GetIntrinsicRatio(&mIntrinsicRatio))) {
-    mIntrinsicRatio.SizeTo(0, 0);
-  }
+  AspectRatio oldIntrinsicRatio = mIntrinsicRatio;
+  mIntrinsicRatio = StyleDisplay()->IsContainSize()
+                        ? AspectRatio()
+                        : aImage->GetIntrinsicRatio().valueOr(AspectRatio());
 
   return mIntrinsicRatio != oldIntrinsicRatio;
 }
 
 bool nsImageFrame::GetSourceToDestTransform(nsTransform2D& aTransform) {
   // First, figure out destRect (the rect we're rendering into).
   // NOTE: We use mComputedSize instead of just GetInnerArea()'s own size here,
   // because GetInnerArea() might be smaller if we're fragmented, whereas
@@ -694,17 +691,17 @@ nsresult nsImageFrame::OnSizeAvailable(i
     intrinsicSizeChanged = UpdateIntrinsicSize(mImage);
     intrinsicSizeChanged = UpdateIntrinsicRatio(mImage) || intrinsicSizeChanged;
   } else {
     // We no longer have a valid image, so release our stored image container.
     mImage = mPrevImage = nullptr;
 
     // Have to size to 0,0 so that GetDesiredSize recalculates the size.
     mIntrinsicSize = IntrinsicSize(0, 0);
-    mIntrinsicRatio.SizeTo(0, 0);
+    mIntrinsicRatio = AspectRatio();
     intrinsicSizeChanged = true;
   }
 
   if (!GotInitialReflow()) {
     return NS_OK;
   }
 
   MarkNeedsDisplayItemRebuild();
@@ -815,17 +812,17 @@ void nsImageFrame::NotifyNewCurrentReque
     intrinsicSizeChanged = UpdateIntrinsicSize(mImage);
     intrinsicSizeChanged = UpdateIntrinsicRatio(mImage) || intrinsicSizeChanged;
   } else {
     // We no longer have a valid image, so release our stored image container.
     mImage = mPrevImage = nullptr;
 
     // Have to size to 0,0 so that GetDesiredSize recalculates the size
     mIntrinsicSize = IntrinsicSize(0, 0);
-    mIntrinsicRatio.SizeTo(0, 0);
+    mIntrinsicRatio = AspectRatio();
   }
 
   if (GotInitialReflow()) {
     if (intrinsicSizeChanged) {
       if (!(mState & IMAGE_SIZECONSTRAINED)) {
         PresShell()->FrameNeedsReflow(this, IntrinsicDirty::StyleChange,
                                       NS_FRAME_IS_DIRTY);
       } else {
@@ -902,17 +899,17 @@ nsRect nsImageFrame::PredictedDestRect(c
                                               mIntrinsicRatio, StylePosition());
 }
 
 void nsImageFrame::EnsureIntrinsicSizeAndRatio() {
   if (StyleDisplay()->IsContainSize()) {
     // If we have 'contain:size', then our intrinsic size and ratio are 0,0
     // regardless of what our underlying image may think.
     mIntrinsicSize = IntrinsicSize(0, 0);
-    mIntrinsicRatio.SizeTo(0, 0);
+    mIntrinsicRatio = AspectRatio();
     return;
   }
 
   // If mIntrinsicSize.width and height are 0, then we need to update from the
   // image container.
   if (mIntrinsicSize != IntrinsicSize(0, 0)) {
     return;
   }
@@ -923,17 +920,17 @@ void nsImageFrame::EnsureIntrinsicSizeAn
     return;
   }
 
   // invalid image specified. make the image big enough for the "broken" icon
   if (ShouldShowBrokenImageIcon()) {
     nscoord edgeLengthToUse = nsPresContext::CSSPixelsToAppUnits(
         ICON_SIZE + (2 * (ICON_PADDING + ALT_BORDER_WIDTH)));
     mIntrinsicSize = IntrinsicSize(edgeLengthToUse, edgeLengthToUse);
-    mIntrinsicRatio.SizeTo(1, 1);
+    mIntrinsicRatio = AspectRatio(1.0f);
   }
 }
 
 /* virtual */
 LogicalSize nsImageFrame::ComputeSize(
     gfxContext* aRenderingContext, WritingMode aWM, const LogicalSize& aCBSize,
     nscoord aAvailableISize, const LogicalSize& aMargin,
     const LogicalSize& aBorder, const LogicalSize& aPadding,
@@ -992,17 +989,17 @@ nscoord nsImageFrame::GetPrefISize(gfxCo
   // convert from normal twips to scaled twips (printing...)
   return iSize.valueOr(0);
 }
 
 /* virtual */
 IntrinsicSize nsImageFrame::GetIntrinsicSize() { return mIntrinsicSize; }
 
 /* virtual */
-nsSize nsImageFrame::GetIntrinsicRatio() { return mIntrinsicRatio; }
+AspectRatio nsImageFrame::GetIntrinsicRatio() { return mIntrinsicRatio; }
 
 void nsImageFrame::Reflow(nsPresContext* aPresContext, ReflowOutput& aMetrics,
                           const ReflowInput& aReflowInput,
                           nsReflowStatus& aStatus) {
   MarkInReflow();
   DO_GLOBAL_REFLOW_COUNT("nsImageFrame");
   DISPLAY_REFLOW(aPresContext, this, aReflowInput, aMetrics, aStatus);
   MOZ_ASSERT(aStatus.IsEmpty(), "Caller should pass a fresh reflow status!");
--- a/layout/generic/nsImageFrame.h
+++ b/layout/generic/nsImageFrame.h
@@ -79,17 +79,17 @@ class nsImageFrame : public nsAtomicCont
 
   virtual void Init(nsIContent* aContent, nsContainerFrame* aParent,
                     nsIFrame* aPrevInFlow) override;
   virtual void BuildDisplayList(nsDisplayListBuilder* aBuilder,
                                 const nsDisplayListSet& aLists) override;
   virtual nscoord GetMinISize(gfxContext* aRenderingContext) override;
   virtual nscoord GetPrefISize(gfxContext* aRenderingContext) override;
   virtual mozilla::IntrinsicSize GetIntrinsicSize() override;
-  virtual nsSize GetIntrinsicRatio() override;
+  virtual mozilla::AspectRatio GetIntrinsicRatio() override;
   virtual void Reflow(nsPresContext* aPresContext, ReflowOutput& aDesiredSize,
                       const ReflowInput& aReflowInput,
                       nsReflowStatus& aStatus) override;
 
   virtual nsresult GetContentForEvent(mozilla::WidgetEvent* aEvent,
                                       nsIContent** aContent) override;
   virtual nsresult HandleEvent(nsPresContext* aPresContext,
                                mozilla::WidgetGUIEvent* aEvent,
@@ -357,17 +357,17 @@ class nsImageFrame : public nsAtomicCont
 
   // An image request created for content: url(..).
   RefPtr<imgRequestProxy> mContentURLRequest;
 
   nsCOMPtr<imgIContainer> mImage;
   nsCOMPtr<imgIContainer> mPrevImage;
   nsSize mComputedSize;
   mozilla::IntrinsicSize mIntrinsicSize;
-  nsSize mIntrinsicRatio;
+  mozilla::AspectRatio mIntrinsicRatio;
 
   const Kind mKind;
   bool mContentURLRequestRegistered;
   bool mDisplayingIcon;
   bool mFirstFrameComplete;
   bool mReflowCallbackPosted;
   bool mForceSyncDecoding;
 
--- a/layout/generic/nsLineLayout.cpp
+++ b/layout/generic/nsLineLayout.cpp
@@ -722,17 +722,17 @@ static bool IsPercentageAware(const nsIF
     // Per CSS 2.1, section 10.3.2:
     //   If 'height' and 'width' both have computed values of 'auto' and
     //   the element has an intrinsic ratio but no intrinsic height or
     //   width and the containing block's width does not itself depend
     //   on the replaced element's width, then the used value of 'width'
     //   is calculated from the constraint equation used for
     //   block-level, non-replaced elements in normal flow.
     nsIFrame* f = const_cast<nsIFrame*>(aFrame);
-    if (f->GetIntrinsicRatio() != nsSize(0, 0) &&
+    if (f->GetIntrinsicRatio() &&
         // Some percents are treated like 'auto', so check != coord
         !pos->BSize(aWM).ConvertsToLength()) {
       const IntrinsicSize& intrinsicSize = f->GetIntrinsicSize();
       if (!intrinsicSize.width && !intrinsicSize.height) {
         return true;
       }
     }
   }
--- a/layout/generic/nsSubDocumentFrame.cpp
+++ b/layout/generic/nsSubDocumentFrame.cpp
@@ -718,17 +718,17 @@ IntrinsicSize nsSubDocumentFrame::GetInt
   nsIFrame* subDocRoot = ObtainIntrinsicSizeFrame();
   if (subDocRoot) {
     return subDocRoot->GetIntrinsicSize();
   }
   return nsAtomicContainerFrame::GetIntrinsicSize();
 }
 
 /* virtual */
-nsSize nsSubDocumentFrame::GetIntrinsicRatio() {
+AspectRatio nsSubDocumentFrame::GetIntrinsicRatio() {
   nsIFrame* subDocRoot = ObtainIntrinsicSizeFrame();
   if (subDocRoot) {
     return subDocRoot->GetIntrinsicRatio();
   }
   return nsAtomicContainerFrame::GetIntrinsicRatio();
 }
 
 /* virtual */
@@ -800,17 +800,17 @@ void nsSubDocumentFrame::Reflow(nsPresCo
   if (mInnerView) {
     const nsMargin& bp = aReflowInput.ComputedPhysicalBorderPadding();
     nsSize innerSize(aDesiredSize.Width() - bp.LeftRight(),
                      aDesiredSize.Height() - bp.TopBottom());
 
     // Size & position the view according to 'object-fit' & 'object-position'.
     nsIFrame* subDocRoot = ObtainIntrinsicSizeFrame();
     IntrinsicSize intrinsSize;
-    nsSize intrinsRatio;
+    AspectRatio intrinsRatio;
     if (subDocRoot) {
       intrinsSize = subDocRoot->GetIntrinsicSize();
       intrinsRatio = subDocRoot->GetIntrinsicRatio();
     }
     nsRect destRect = nsLayoutUtils::ComputeObjectDestRect(
         nsRect(offset, innerSize), intrinsSize, intrinsRatio, StylePosition());
 
     nsViewManager* vm = mInnerView->GetViewManager();
--- a/layout/generic/nsSubDocumentFrame.h
+++ b/layout/generic/nsSubDocumentFrame.h
@@ -50,17 +50,17 @@ class nsSubDocumentFrame final : public 
 
   void DestroyFrom(nsIFrame* aDestructRoot,
                    PostDestroyData& aPostDestroyData) override;
 
   nscoord GetMinISize(gfxContext* aRenderingContext) override;
   nscoord GetPrefISize(gfxContext* aRenderingContext) override;
 
   mozilla::IntrinsicSize GetIntrinsicSize() override;
-  nsSize GetIntrinsicRatio() override;
+  mozilla::AspectRatio GetIntrinsicRatio() override;
 
   mozilla::LogicalSize ComputeAutoSize(
       gfxContext* aRenderingContext, mozilla::WritingMode aWritingMode,
       const mozilla::LogicalSize& aCBSize, nscoord aAvailableISize,
       const mozilla::LogicalSize& aMargin, const mozilla::LogicalSize& aBorder,
       const mozilla::LogicalSize& aPadding, ComputeSizeFlags aFlags) override;
 
   mozilla::LogicalSize ComputeSize(
--- a/layout/generic/nsVideoFrame.cpp
+++ b/layout/generic/nsVideoFrame.cpp
@@ -184,19 +184,21 @@ already_AddRefed<Layer> nsVideoFrame::Bu
   if (frameSize.width == 0 || frameSize.height == 0) {
     // No image, or zero-sized image. No point creating a layer.
     return nullptr;
   }
 
   // Convert video size from pixel units into app units, to get an aspect-ratio
   // (which has to be represented as a nsSize) and an IntrinsicSize that we
   // can pass to ComputeObjectRenderRect.
-  nsSize aspectRatio(nsPresContext::CSSPixelsToAppUnits(videoSizeInPx.width),
-                     nsPresContext::CSSPixelsToAppUnits(videoSizeInPx.height));
-  IntrinsicSize intrinsicSize(aspectRatio.width, aspectRatio.height);
+  auto aspectRatio =
+      AspectRatio::FromSize(videoSizeInPx.width, videoSizeInPx.height);
+  IntrinsicSize intrinsicSize(
+      nsPresContext::CSSPixelsToAppUnits(videoSizeInPx.width),
+      nsPresContext::CSSPixelsToAppUnits(videoSizeInPx.height));
 
   nsRect dest = nsLayoutUtils::ComputeObjectDestRect(
       area, intrinsicSize, aspectRatio, StylePosition());
 
   gfxRect destGFXRect = PresContext()->AppUnitsToGfxUnits(dest);
   destGFXRect.Round();
   if (destGFXRect.IsEmpty()) {
     return nullptr;
@@ -429,20 +431,21 @@ class nsDisplayVideo : public nsDisplayI
     if (frameSize.width == 0 || frameSize.height == 0) {
       // No image, or zero-sized image. Don't render.
       return true;
     }
 
     // Convert video size from pixel units into app units, to get an
     // aspect-ratio (which has to be represented as a nsSize) and an
     // IntrinsicSize that we can pass to ComputeObjectRenderRect.
-    nsSize aspectRatio(
+    IntrinsicSize intrinsicSize(
         nsPresContext::CSSPixelsToAppUnits(videoSizeInPx.width),
         nsPresContext::CSSPixelsToAppUnits(videoSizeInPx.height));
-    IntrinsicSize intrinsicSize(aspectRatio.width, aspectRatio.height);
+    auto aspectRatio =
+        AspectRatio::FromSize(videoSizeInPx.width, videoSizeInPx.height);
 
     nsRect dest = nsLayoutUtils::ComputeObjectDestRect(
         area, intrinsicSize, aspectRatio, Frame()->StylePosition());
 
     gfxRect destGFXRect = Frame()->PresContext()->AppUnitsToGfxUnits(dest);
     destGFXRect.Round();
     if (destGFXRect.IsEmpty()) {
       return true;
@@ -571,17 +574,19 @@ LogicalSize nsVideoFrame::ComputeSize(
                                          aAvailableISize, aMargin, aBorder,
                                          aPadding, aFlags);
   }
 
   nsSize size = GetVideoIntrinsicSize(aRenderingContext);
   IntrinsicSize intrinsicSize(size.width, size.height);
 
   // Only video elements have an intrinsic ratio.
-  nsSize intrinsicRatio = HasVideoElement() ? size : nsSize(0, 0);
+  auto intrinsicRatio = HasVideoElement()
+                            ? AspectRatio::FromSize(size.width, size.height)
+                            : AspectRatio();
 
   return ComputeSizeWithIntrinsicDimensions(
       aRenderingContext, aWM, intrinsicSize, intrinsicRatio, aCBSize, aMargin,
       aBorder, aPadding, aFlags);
 }
 
 nscoord nsVideoFrame::GetMinISize(gfxContext* aRenderingContext) {
   nscoord result;
@@ -622,23 +627,24 @@ nscoord nsVideoFrame::GetPrefISize(gfxCo
     } else {
       result = 0;
     }
   }
 
   return result;
 }
 
-nsSize nsVideoFrame::GetIntrinsicRatio() {
+AspectRatio nsVideoFrame::GetIntrinsicRatio() {
   if (!HasVideoElement()) {
     // Audio elements have no intrinsic ratio.
-    return nsSize(0, 0);
+    return AspectRatio();
   }
 
-  return GetVideoIntrinsicSize(nullptr);
+  nsSize size = GetVideoIntrinsicSize(nullptr);
+  return AspectRatio::FromSize(size.width, size.height);
 }
 
 bool nsVideoFrame::ShouldDisplayPoster() {
   if (!HasVideoElement()) return false;
 
   HTMLVideoElement* element = static_cast<HTMLVideoElement*>(GetContent());
   if (element->GetPlayedOrSeeked() && HasVideoData()) return false;
 
--- a/layout/generic/nsVideoFrame.h
+++ b/layout/generic/nsVideoFrame.h
@@ -50,17 +50,17 @@ class nsVideoFrame final : public nsCont
                             int32_t aModType) override;
 
   void OnVisibilityChange(
       Visibility aNewVisibility,
       const Maybe<OnNonvisible>& aNonvisibleAction = Nothing()) override;
 
   /* get the size of the video's display */
   nsSize GetVideoIntrinsicSize(gfxContext* aRenderingContext);
-  nsSize GetIntrinsicRatio() override;
+  mozilla::AspectRatio GetIntrinsicRatio() override;
   mozilla::LogicalSize ComputeSize(
       gfxContext* aRenderingContext, mozilla::WritingMode aWritingMode,
       const mozilla::LogicalSize& aCBSize, nscoord aAvailableISize,
       const mozilla::LogicalSize& aMargin, const mozilla::LogicalSize& aBorder,
       const mozilla::LogicalSize& aPadding, ComputeSizeFlags aFlags) override;
   nscoord GetMinISize(gfxContext* aRenderingContext) override;
   nscoord GetPrefISize(gfxContext* aRenderingContext) override;
   void DestroyFrom(nsIFrame* aDestructRoot,
--- a/layout/painting/nsCSSRendering.cpp
+++ b/layout/painting/nsCSSRendering.cpp
@@ -2883,39 +2883,34 @@ static nsSize ComputeDrawnSizeForBackgro
 
   // Calculate the rounded size only if the background-size computation
   // returned a correct size for the image.
   if (imageSize.width && aXRepeat == StyleImageLayerRepeat::Round) {
     imageSize.width = nsCSSRendering::ComputeRoundedSize(
         imageSize.width, aBgPositioningArea.width);
     if (!isRepeatRoundInBothDimensions && aLayerSize.IsExplicitSize() &&
         aLayerSize.explicit_size.height.IsAuto()) {
-      // Restore intrinsic rato
-      if (aIntrinsicSize.mRatio.width) {
-        float scale =
-            float(aIntrinsicSize.mRatio.height) / aIntrinsicSize.mRatio.width;
+      // Restore intrinsic ratio
+      if (aIntrinsicSize.mRatio) {
         imageSize.height =
-            NSCoordSaturatingNonnegativeMultiply(imageSize.width, scale);
+            aIntrinsicSize.mRatio.Inverted().ApplyTo(imageSize.width);
       }
     }
   }
 
   // Calculate the rounded size only if the background-size computation
   // returned a correct size for the image.
   if (imageSize.height && aYRepeat == StyleImageLayerRepeat::Round) {
     imageSize.height = nsCSSRendering::ComputeRoundedSize(
         imageSize.height, aBgPositioningArea.height);
     if (!isRepeatRoundInBothDimensions && aLayerSize.IsExplicitSize() &&
         aLayerSize.explicit_size.width.IsAuto()) {
-      // Restore intrinsic rato
-      if (aIntrinsicSize.mRatio.height) {
-        float scale =
-            float(aIntrinsicSize.mRatio.width) / aIntrinsicSize.mRatio.height;
-        imageSize.width =
-            NSCoordSaturatingNonnegativeMultiply(imageSize.height, scale);
+      // Restore intrinsic ratio
+      if (aIntrinsicSize.mRatio) {
+        imageSize.width = aIntrinsicSize.mRatio.ApplyTo(imageSize.height);
       }
     }
   }
 
   return imageSize;
 }
 
 /* ComputeSpacedRepeatSize
--- a/layout/painting/nsImageRenderer.cpp
+++ b/layout/painting/nsImageRenderer.cpp
@@ -33,25 +33,21 @@ using namespace mozilla::image;
 using namespace mozilla::layers;
 
 nsSize CSSSizeOrRatio::ComputeConcreteSize() const {
   NS_ASSERTION(CanComputeConcreteSize(), "Cannot compute");
   if (mHasWidth && mHasHeight) {
     return nsSize(mWidth, mHeight);
   }
   if (mHasWidth) {
-    nscoord height = NSCoordSaturatingNonnegativeMultiply(
-        mWidth, double(mRatio.height) / mRatio.width);
-    return nsSize(mWidth, height);
+    return nsSize(mWidth, mRatio.Inverted().ApplyTo(mWidth));
   }
 
   MOZ_ASSERT(mHasHeight);
-  nscoord width = NSCoordSaturatingNonnegativeMultiply(
-      mHeight, double(mRatio.width) / mRatio.height);
-  return nsSize(width, mHeight);
+  return nsSize(mRatio.ApplyTo(mHeight), mHeight);
 }
 
 nsImageRenderer::nsImageRenderer(nsIFrame* aForFrame,
                                  const nsStyleImage* aImage, uint32_t aFlags)
     : mForFrame(aForFrame),
       mImage(aImage),
       mType(aImage->GetType()),
       mImageContainer(nullptr),
@@ -223,25 +219,22 @@ CSSSizeOrRatio nsImageRenderer::ComputeI
       }
       if (haveHeight) {
         result.SetHeight(
             nsPresContext::CSSPixelsToAppUnits(imageIntSize.height));
       }
 
       // If we know the aspect ratio and one of the dimensions,
       // we can compute the other missing width or height.
-      if (!haveHeight && haveWidth && result.mRatio.width != 0) {
-        nscoord intrinsicHeight = NSCoordSaturatingNonnegativeMultiply(
-            imageIntSize.width,
-            float(result.mRatio.height) / float(result.mRatio.width));
+      if (!haveHeight && haveWidth && result.mRatio) {
+        nscoord intrinsicHeight =
+            result.mRatio.Inverted().ApplyTo(imageIntSize.width);
         result.SetHeight(nsPresContext::CSSPixelsToAppUnits(intrinsicHeight));
-      } else if (haveHeight && !haveWidth && result.mRatio.height != 0) {
-        nscoord intrinsicWidth = NSCoordSaturatingNonnegativeMultiply(
-            imageIntSize.height,
-            float(result.mRatio.width) / float(result.mRatio.height));
+      } else if (haveHeight && !haveWidth && result.mRatio) {
+        nscoord intrinsicWidth = result.mRatio.ApplyTo(imageIntSize.height);
         result.SetWidth(nsPresContext::CSSPixelsToAppUnits(intrinsicWidth));
       }
 
       break;
     }
     case eStyleImageType_Element: {
       // XXX element() should have the width/height of the referenced element,
       //     and that element's ratio, if it matches.  If it doesn't match, it
@@ -312,70 +305,64 @@ nsSize nsImageRenderer::ComputeConcreteS
   }
 
   MOZ_ASSERT(aSpecifiedSize.mHasWidth || aSpecifiedSize.mHasHeight);
 
   // The specified height is partial, try to compute the missing part.
   if (aSpecifiedSize.mHasWidth) {
     nscoord height;
     if (aIntrinsicSize.HasRatio()) {
-      height = NSCoordSaturatingNonnegativeMultiply(
-          aSpecifiedSize.mWidth,
-          double(aIntrinsicSize.mRatio.height) / aIntrinsicSize.mRatio.width);
+      height = aIntrinsicSize.mRatio.Inverted().ApplyTo(aSpecifiedSize.mWidth);
     } else if (aIntrinsicSize.mHasHeight) {
       height = aIntrinsicSize.mHeight;
     } else {
       height = aDefaultSize.height;
     }
     return nsSize(aSpecifiedSize.mWidth, height);
   }
 
   MOZ_ASSERT(aSpecifiedSize.mHasHeight);
   nscoord width;
   if (aIntrinsicSize.HasRatio()) {
-    width = NSCoordSaturatingNonnegativeMultiply(
-        aSpecifiedSize.mHeight,
-        double(aIntrinsicSize.mRatio.width) / aIntrinsicSize.mRatio.height);
+    width = aIntrinsicSize.mRatio.ApplyTo(aSpecifiedSize.mHeight);
   } else if (aIntrinsicSize.mHasWidth) {
     width = aIntrinsicSize.mWidth;
   } else {
     width = aDefaultSize.width;
   }
   return nsSize(width, aSpecifiedSize.mHeight);
 }
 
 /* static */
-nsSize nsImageRenderer::ComputeConstrainedSize(const nsSize& aConstrainingSize,
-                                               const nsSize& aIntrinsicRatio,
-                                               FitType aFitType) {
-  if (aIntrinsicRatio.width <= 0 && aIntrinsicRatio.height <= 0) {
+nsSize nsImageRenderer::ComputeConstrainedSize(
+    const nsSize& aConstrainingSize, const AspectRatio& aIntrinsicRatio,
+    FitType aFitType) {
+  if (!aIntrinsicRatio) {
     return aConstrainingSize;
   }
 
-  float scaleX = double(aConstrainingSize.width) / aIntrinsicRatio.width;
-  float scaleY = double(aConstrainingSize.height) / aIntrinsicRatio.height;
+  auto constrainingRatio =
+      AspectRatio::FromSize(aConstrainingSize.width, aConstrainingSize.height);
   nsSize size;
-  if ((aFitType == CONTAIN) == (scaleX < scaleY)) {
+  if ((aFitType == CONTAIN) == (constrainingRatio < aIntrinsicRatio)) {
     size.width = aConstrainingSize.width;
-    size.height =
-        NSCoordSaturatingNonnegativeMultiply(aIntrinsicRatio.height, scaleX);
+    size.height = aIntrinsicRatio.Inverted().ApplyTo(aConstrainingSize.width);
     // If we're reducing the size by less than one css pixel, then just use the
     // constraining size.
     if (aFitType == CONTAIN &&
         aConstrainingSize.height - size.height < AppUnitsPerCSSPixel()) {
       size.height = aConstrainingSize.height;
     }
   } else {
-    size.width =
-        NSCoordSaturatingNonnegativeMultiply(aIntrinsicRatio.width, scaleY);
+    size.height = aConstrainingSize.height;
+    size.width = aIntrinsicRatio.ApplyTo(aConstrainingSize.height);
     if (aFitType == CONTAIN &&
         aConstrainingSize.width - size.width < AppUnitsPerCSSPixel()) {
       size.width = aConstrainingSize.width;
     }
-    size.height = aConstrainingSize.height;
   }
   return size;
 }
 
 /**
  * mSize is the image's "preferred" size for this particular rendering, while
  * the drawn (aka concrete) size is the actual rendered size after accounting
  * for background-size etc..  The preferred size is most often the image's
--- a/layout/painting/nsImageRenderer.h
+++ b/layout/painting/nsImageRenderer.h
@@ -5,16 +5,17 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef nsImageRenderer_h__
 #define nsImageRenderer_h__
 
 #include "nsLayoutUtils.h"
 #include "nsStyleStruct.h"
 #include "Units.h"
+#include "mozilla/AspectRatio.h"
 
 class gfxDrawable;
 namespace mozilla {
 
 namespace layers {
 class StackingContextHelper;
 class WebRenderParentCommand;
 class RenderRootStateManager;
@@ -26,65 +27,61 @@ class IpcResourceUpdateQueue;
 }  // namespace wr
 
 // A CSSSizeOrRatio represents a (possibly partially specified) size for use
 // in computing image sizes. Either or both of the width and height might be
 // given. A ratio of width to height may also be given. If we at least two
 // of these then we can compute a concrete size, that is a width and height.
 struct CSSSizeOrRatio {
   CSSSizeOrRatio()
-      : mRatio(0, 0),
-        mWidth(0),
-        mHeight(0),
-        mHasWidth(false),
-        mHasHeight(false) {}
+      : mWidth(0), mHeight(0), mHasWidth(false), mHasHeight(false) {}
 
   bool CanComputeConcreteSize() const {
     return mHasWidth + mHasHeight + HasRatio() >= 2;
   }
   bool IsConcrete() const { return mHasWidth && mHasHeight; }
-  bool HasRatio() const { return mRatio.width > 0 && mRatio.height > 0; }
+  bool HasRatio() const { return !!mRatio; }
   bool IsEmpty() const {
     return (mHasWidth && mWidth <= 0) || (mHasHeight && mHeight <= 0) ||
-           mRatio.width <= 0 || mRatio.height <= 0;
+           !mRatio;
   }
 
   // CanComputeConcreteSize must return true when ComputeConcreteSize is
   // called.
   nsSize ComputeConcreteSize() const;
 
   void SetWidth(nscoord aWidth) {
     mWidth = aWidth;
     mHasWidth = true;
     if (mHasHeight) {
-      mRatio = nsSize(mWidth, mHeight);
+      mRatio = AspectRatio::FromSize(mWidth, mHeight);
     }
   }
   void SetHeight(nscoord aHeight) {
     mHeight = aHeight;
     mHasHeight = true;
     if (mHasWidth) {
-      mRatio = nsSize(mWidth, mHeight);
+      mRatio = AspectRatio::FromSize(mWidth, mHeight);
     }
   }
   void SetSize(const nsSize& aSize) {
     mWidth = aSize.width;
     mHeight = aSize.height;
     mHasWidth = true;
     mHasHeight = true;
-    mRatio = aSize;
+    mRatio = AspectRatio::FromSize(mWidth, mHeight);
   }
-  void SetRatio(const nsSize& aRatio) {
+  void SetRatio(const AspectRatio& aRatio) {
     MOZ_ASSERT(
         !mHasWidth || !mHasHeight,
         "Probably shouldn't be setting a ratio if we have a concrete size");
     mRatio = aRatio;
   }
 
-  nsSize mRatio;
+  AspectRatio mRatio;
   nscoord mWidth;
   nscoord mHeight;
   bool mHasWidth;
   bool mHasHeight;
 };
 
 /**
  * This is a small wrapper class to encapsulate image drawing that can draw an
@@ -151,22 +148,20 @@ class nsImageRenderer {
                                        const nsSize& aOriginBounds,
                                        const nsSize& aImageSize,
                                        nsPoint* aTopLeft,
                                        nsPoint* aAnchorPoint);
 
   /**
    * Compute the size of the rendered image using either the 'cover' or
    * 'contain' constraints (aFitType).
-   * aIntrinsicRatio may be an invalid ratio, that is one or both of its
-   * dimensions can be less than or equal to zero.
    */
-  static nsSize ComputeConstrainedSize(const nsSize& aConstrainingSize,
-                                       const nsSize& aIntrinsicRatio,
-                                       FitType aFitType);
+  static nsSize ComputeConstrainedSize(
+      const nsSize& aConstrainingSize,
+      const mozilla::AspectRatio& aIntrinsicRatio, FitType aFitType);
   /**
    * Compute the size of the rendered image (the concrete size) where no cover/
    * contain constraints are given. The 'default algorithm' from the CSS Image
    * Values spec.
    */
   static nsSize ComputeConcreteSize(
       const mozilla::CSSSizeOrRatio& aSpecifiedSize,
       const mozilla::CSSSizeOrRatio& aIntrinsicSize,
--- a/layout/reftests/columns/reftest.list
+++ b/layout/reftests/columns/reftest.list
@@ -37,8 +37,17 @@ fuzzy-if(OSX,0-32,0-1000) == columnfill-
 fuzzy-if(browserIsRemote&&winWidget,0-142,0-276) == fieldset-columns-001.html fieldset-columns-001-ref.html
 == fieldset-columns-002.html fieldset-columns-002-ref.html
 == dynamic-change-with-overflow-1.html dynamic-change-with-overflow-1-ref.html
 == dynamic-text-indent-1.html dynamic-text-indent-1-ref.html
 == dynamic-text-indent-2.html dynamic-text-indent-2-ref.html
 == break-avoid-line-position-1.html break-avoid-line-position-1-ref.html
 pref(layout.css.column-span.enabled,true) == column-span-bidi-1.html column-span-bidi-1-ref.html
 pref(layout.css.column-span.enabled,true) == first-line-first-letter.html first-line-first-letter-ref.html
+
+# The following lines are duplicates of other lines from further up in this
+# manifest. They're listed again here so we can re-run these tests with
+# column-span enabled. These lines can be removed once the pref becomes
+# default-enabled (Bug 1426010).
+default-preferences pref(layout.css.column-span.enabled,true)
+fails == min-width-2.html min-width-2-ref.html # Bug 1548100
+fails == column-balancing-nested-001.html column-balancing-nested-001-ref.html # Bug 1548118
+default-preferences
--- a/layout/reftests/svg/reftest.list
+++ b/layout/reftests/svg/reftest.list
@@ -522,16 +522,18 @@ fuzzy-if(skiaContent,0-1,0-100) == tspan
 == tspan-xy-02.svg tspan-xy-ref.svg
 fuzzy-if(skiaContent,0-1,0-300) == tspan-xy-03.svg tspan-xy-ref.svg
 fuzzy-if(skiaContent,0-1,0-300) == tspan-xy-04.svg tspan-xy-ref.svg
 fuzzy-if(skiaContent,0-1,0-300) == tspan-xy-05.svg tspan-xy-ref.svg
 fuzzy-if(skiaContent,0-1,0-300) == tspan-xy-06.svg tspan-xy-ref.svg
 fuzzy-if(skiaContent,0-1,0-100) == tspan-xy-anchor-middle-01.svg tspan-xy-anchor-middle-ref.svg
 fuzzy-if(skiaContent,0-1,0-100) == tspan-xy-anchor-end-01.svg tspan-xy-anchor-end-ref.svg
 
+pref(layout.css.devPixelsPerPx,"1.0") == svg-blurry-with-subpixel-position.html svg-blurry-with-subpixel-position-ref.html
+
 == use-01.svg pass.svg
 == use-01-extref.svg pass.svg
 == use-02-extref.svg use-02-extref-ref.svg
 == use-extref-dataURI-01.svg pass.svg
 == use-children.svg pass.svg
 
 == use-element-shadow-tree-rule-matching.html pass.svg
 
new file mode 100644
--- /dev/null
+++ b/layout/reftests/svg/svg-blurry-with-subpixel-position-ref.html
@@ -0,0 +1,13 @@
+<!doctype html>
+<style>
+  svg {
+    width:750px;
+    height:750px;
+    margin:3px;
+  }
+</style>
+
+<svg viewBox="0.5 0.5 750 750">
+  <path d="M3,6L277,6M3,12L277,12M3,18L277,18M3,24L277,24M3,30L277,30M3,36L277,36M3,42L277,42M3,48L277,48M3,54L277,54M3,60L277,60M3,66L277,66M3,72L277,72M3,78L277,78M3,84L277,84M3,90L277,90M3,96L277,96M3,102L277,102M3,108L277,108M3,114L277,114" style="stroke-width:1; stroke:black;" />
+  <path d="M6,3L6,277M12,3L12,277M18,3L18,277M24,3L24,277M30,3L30,277M36,3L36,277M42,3L42,277M48,3L48,277M54,3L54,277M60,3L60,277M66,3L66,277M72,3L72,277M78,3L78,277M84,3L84,277M90,3L90,277M96,3L96,277M102,3L102,277M108,3L108,277M114,3L114,277" style="stroke-width:1; stroke:black;" />
+</svg>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/svg/svg-blurry-with-subpixel-position.html
@@ -0,0 +1,13 @@
+<!doctype html>
+<style>
+  svg {
+    width:750px;
+    height:750px;
+    margin:2.5px;
+  }
+</style>
+
+<svg viewBox="0.5 0.5 750 750">
+  <path d="M3,6L277,6M3,12L277,12M3,18L277,18M3,24L277,24M3,30L277,30M3,36L277,36M3,42L277,42M3,48L277,48M3,54L277,54M3,60L277,60M3,66L277,66M3,72L277,72M3,78L277,78M3,84L277,84M3,90L277,90M3,96L277,96M3,102L277,102M3,108L277,108M3,114L277,114" style="stroke-width:1; stroke:black;" />
+  <path d="M6,3L6,277M12,3L12,277M18,3L18,277M24,3L24,277M30,3L30,277M36,3L36,277M42,3L42,277M48,3L48,277M54,3L54,277M60,3L60,277M66,3L66,277M72,3L72,277M78,3L78,277M84,3L84,277M90,3L90,277M96,3L96,277M102,3L102,277M108,3L108,277M114,3L114,277" style="stroke-width:1; stroke:black;" />
+</svg>
--- a/layout/reftests/w3c-css/failures.list
+++ b/layout/reftests/w3c-css/failures.list
@@ -253,16 +253,18 @@ fuzzy(0-225,0-2529) css-multicol/multico
 fuzzy(0-225,0-2529) css-multicol/multicol-nested-margin-005.xht
 fuzzy(0-135,0-142) css-multicol/multicol-overflow-000.xht
 fuzzy(0-204,0-1844) fuzzy-if(skiaContent,0-208,0-1844) css-multicol/multicol-overflowing-001.xht
 fuzzy-if(OSX,0-61,0-2) fuzzy-if(skiaContent,0-64,0-2) css-multicol/multicol-reduce-000.xht
 fuzzy-if(OSX,0-11,0-20) css-multicol/multicol-rule-000.xht
 fuzzy(0-135,0-1584) css-multicol/multicol-rule-001.xht
 fails-if(!OSX) random-if(OSX) css-multicol/multicol-rule-002.xht
 css-multicol/multicol-rule-003.xht
+# Bug 1548100
+pref(layout.css.column-span.enabled,true) fails css-multicol/multicol-rule-004.xht
 css-multicol/multicol-rule-color-001.xht
 fuzzy(0-106,0-354) css-multicol/multicol-rule-dashed-000.xht
 fuzzy(0-106,0-354) css-multicol/multicol-rule-dotted-000.xht
 fuzzy(0-106,0-354) css-multicol/multicol-rule-double-000.xht
 css-multicol/multicol-rule-fraction-001.xht
 css-multicol/multicol-rule-fraction-002.xht
 fuzzy-if(OSX||winWidget||Android,0-113,0-792) css-multicol/multicol-rule-fraction-003.xht
 fuzzy(0-127,0-500) css-multicol/multicol-rule-groove-000.xht
--- a/layout/reftests/w3c-css/received/reftest.list
+++ b/layout/reftests/w3c-css/received/reftest.list
@@ -120,17 +120,17 @@ fuzzy(0-225,0-2529) == css-multicol/mult
 fuzzy(0-225,0-2529) == css-multicol/multicol-nested-margin-005.xht css-multicol/multicol-nested-margin-004-ref.xht
 fuzzy(0-135,0-142) == css-multicol/multicol-overflow-000.xht css-multicol/multicol-overflow-000-ref.xht
 fuzzy(0-204,0-1844) fuzzy-if(skiaContent,0-208,0-1844) == css-multicol/multicol-overflowing-001.xht css-multicol/multicol-overflowing-001-ref.xht
 fuzzy-if(OSX,0-61,0-2) fuzzy-if(skiaContent,0-64,0-2) == css-multicol/multicol-reduce-000.xht css-multicol/multicol-reduce-000-ref.xht
 fuzzy-if(OSX,0-11,0-20) == css-multicol/multicol-rule-000.xht css-multicol/multicol-rule-000-ref.xht
 fuzzy(0-135,0-1584) == css-multicol/multicol-rule-001.xht css-multicol/multicol-rule-001-ref.xht
 fails-if(!OSX) random-if(OSX) == css-multicol/multicol-rule-002.xht css-multicol/multicol-rule-ref.xht
 == css-multicol/multicol-rule-003.xht css-multicol/multicol-rule-003-ref.xht
-== css-multicol/multicol-rule-004.xht css-multicol/multicol-rule-004-ref.xht
+pref(layout.css.column-span.enabled,true) fails == css-multicol/multicol-rule-004.xht css-multicol/multicol-rule-004-ref.xht
 == css-multicol/multicol-rule-color-001.xht css-multicol/multicol-rule-color-001-ref.xht
 == css-multicol/multicol-rule-color-inherit-001.xht css-multicol/multicol-rule-color-inherit-001-ref.xht
 == css-multicol/multicol-rule-color-inherit-002.xht css-multicol/multicol-rule-color-inherit-001-ref.xht
 fuzzy(0-106,0-354) == css-multicol/multicol-rule-dashed-000.xht css-multicol/multicol-rule-dashed-000-ref.xht
 fuzzy(0-106,0-354) == css-multicol/multicol-rule-dotted-000.xht css-multicol/multicol-rule-dotted-000-ref.xht
 fuzzy(0-106,0-354) == css-multicol/multicol-rule-double-000.xht css-multicol/multicol-rule-double-000-ref.xht
 == css-multicol/multicol-rule-fraction-001.xht css-multicol/multicol-rule-fraction-001-ref.xht
 == css-multicol/multicol-rule-fraction-002.xht css-multicol/multicol-rule-fraction-002-ref.xht
--- a/layout/reftests/w3c-css/submitted/contain/reftest.list
+++ b/layout/reftests/w3c-css/submitted/contain/reftest.list
@@ -44,8 +44,17 @@ fuzzy-if(webrender&&winWidget,0-24,0-2) 
 == contain-layout-containing-block-fixed-001.html contain-paint-containing-block-fixed-001-ref.html
 == contain-layout-containing-block-absolute-001.html contain-paint-containing-block-absolute-001-ref.html
 == contain-layout-ignored-cases-ib-split-001.html contain-layout-ignored-cases-ib-split-001-ref.html
 == contain-layout-ignored-cases-no-principal-box-001.html contain-paint-ignored-cases-no-principal-box-001-ref.html
 == contain-layout-ignored-cases-no-principal-box-002.html contain-layout-ignored-cases-no-principal-box-002-ref.html
 == contain-layout-ignored-cases-no-principal-box-003.html contain-layout-ignored-cases-no-principal-box-003-ref.html
 == contain-layout-suppress-baseline-001.html contain-layout-suppress-baseline-001-ref.html
 fails == contain-layout-suppress-baseline-002.html contain-layout-suppress-baseline-002-ref.html # bug 1508441
+
+# The following lines are duplicates of other lines from further up in this
+# manifest. They're listed again here so we can re-run these tests with
+# column-span enabled. These lines can be removed once the pref becomes
+# default-enabled (Bug 1426010).
+default-preferences pref(layout.css.column-span.enabled,true)
+fails == contain-size-multicol-002.html contain-size-multicol-002-ref.html # Bug 1494100
+fails == contain-size-multicol-003.html contain-size-multicol-003-ref.html # Bug 1494100
+default-preferences
--- a/layout/style/nsStyleStruct.cpp
+++ b/layout/style/nsStyleStruct.cpp
@@ -2657,30 +2657,30 @@ static bool SizeDependsOnPositioningArea
 
   if (type == eStyleImageType_Image) {
     nsCOMPtr<imgIContainer> imgContainer;
     if (imgRequestProxy* req = aImage.GetImageData()) {
       req->GetImage(getter_AddRefs(imgContainer));
     }
     if (imgContainer) {
       CSSIntSize imageSize;
-      nsSize imageRatio;
+      AspectRatio imageRatio;
       bool hasWidth, hasHeight;
       nsLayoutUtils::ComputeSizeForDrawing(imgContainer, imageSize, imageRatio,
                                            hasWidth, hasHeight);
 
       // If the image has a fixed width and height, rendering never depends on
       // the frame size.
       if (hasWidth && hasHeight) {
         return false;
       }
 
       // If the image has an intrinsic ratio, rendering will depend on frame
       // size when background-size is all auto.
-      if (imageRatio != nsSize(0, 0)) {
+      if (imageRatio) {
         return size.width.IsAuto() == size.height.IsAuto();
       }
 
       // Otherwise, rendering depends on frame size when the image dimensions
       // and background-size don't complement each other.
       return !(hasWidth && size.width.IsLengthPercentage()) &&
              !(hasHeight && size.height.IsLengthPercentage());
     }
--- a/layout/svg/nsSVGOuterSVGFrame.cpp
+++ b/layout/svg/nsSVGOuterSVGFrame.cpp
@@ -229,69 +229,51 @@ IntrinsicSize nsSVGOuterSVGFrame::GetInt
         nsPresContext::CSSPixelsToAppUnits(height.GetAnimValue(content));
     intrinsicSize.height.emplace(std::max(val, 0));
   }
 
   return intrinsicSize;
 }
 
 /* virtual */
-nsSize nsSVGOuterSVGFrame::GetIntrinsicRatio() {
+AspectRatio nsSVGOuterSVGFrame::GetIntrinsicRatio() {
   if (StyleDisplay()->IsContainSize()) {
-    return nsSize(0, 0);
+    return AspectRatio();
   }
 
   // We only have an intrinsic size/ratio if our width and height attributes
   // are both specified and set to non-percentage values, or we have a viewBox
   // rect: http://www.w3.org/TR/SVGMobile12/coords.html#IntrinsicSizing
   // Unfortunately we have to return the ratio as two nscoords whereas what
   // we have are two floats. Using app units allows for some floating point
   // values to work but really small or large numbers will fail.
 
   SVGSVGElement* content = static_cast<SVGSVGElement*>(GetContent());
   const SVGAnimatedLength& width =
       content->mLengthAttributes[SVGSVGElement::ATTR_WIDTH];
   const SVGAnimatedLength& height =
       content->mLengthAttributes[SVGSVGElement::ATTR_HEIGHT];
 
   if (!width.IsPercentage() && !height.IsPercentage()) {
-    nsSize ratio(
-        nsPresContext::CSSPixelsToAppUnits(width.GetAnimValue(content)),
-        nsPresContext::CSSPixelsToAppUnits(height.GetAnimValue(content)));
-    if (ratio.width < 0) {
-      ratio.width = 0;
-    }
-    if (ratio.height < 0) {
-      ratio.height = 0;
-    }
-    return ratio;
+    return AspectRatio::FromSize(width.GetAnimValue(content),
+                                 height.GetAnimValue(content));
   }
 
   SVGViewElement* viewElement = content->GetCurrentViewElement();
   const SVGViewBox* viewbox = nullptr;
 
   // The logic here should match HasViewBox().
   if (viewElement && viewElement->mViewBox.HasRect()) {
     viewbox = &viewElement->mViewBox.GetAnimValue();
   } else if (content->mViewBox.HasRect()) {
     viewbox = &content->mViewBox.GetAnimValue();
   }
 
   if (viewbox) {
-    float viewBoxWidth = viewbox->width;
-    float viewBoxHeight = viewbox->height;
-
-    if (viewBoxWidth < 0.0f) {
-      viewBoxWidth = 0.0f;
-    }
-    if (viewBoxHeight < 0.0f) {
-      viewBoxHeight = 0.0f;
-    }
-    return nsSize(nsPresContext::CSSPixelsToAppUnits(viewBoxWidth),
-                  nsPresContext::CSSPixelsToAppUnits(viewBoxHeight));
+    return AspectRatio::FromSize(viewbox->width, viewbox->height);
   }
 
   return nsSVGDisplayContainerFrame::GetIntrinsicRatio();
 }
 
 /* virtual */
 LogicalSize nsSVGOuterSVGFrame::ComputeSize(
     gfxContext* aRenderingContext, WritingMode aWritingMode,
--- a/layout/svg/nsSVGOuterSVGFrame.h
+++ b/layout/svg/nsSVGOuterSVGFrame.h
@@ -45,17 +45,17 @@ class nsSVGOuterSVGFrame final : public 
   }
 #endif
 
   // nsIFrame:
   virtual nscoord GetMinISize(gfxContext* aRenderingContext) override;
   virtual nscoord GetPrefISize(gfxContext* aRenderingContext) override;
 
   virtual mozilla::IntrinsicSize GetIntrinsicSize() override;
-  virtual nsSize GetIntrinsicRatio() override;
+  virtual mozilla::AspectRatio GetIntrinsicRatio() override;
 
   virtual mozilla::LogicalSize ComputeSize(
       gfxContext* aRenderingContext, mozilla::WritingMode aWritingMode,
       const mozilla::LogicalSize& aCBSize, nscoord aAvailableISize,
       const mozilla::LogicalSize& aMargin, const mozilla::LogicalSize& aBorder,
       const mozilla::LogicalSize& aPadding, ComputeSizeFlags aFlags) override;
 
   virtual void Reflow(nsPresContext* aPresContext, ReflowOutput& aDesiredSize,
--- a/layout/xul/nsImageBoxFrame.cpp
+++ b/layout/xul/nsImageBoxFrame.cpp
@@ -465,26 +465,27 @@ nsRect nsImageBoxFrame::GetDestRect(cons
     // XXXdholbert Should we even honor these properties in this case? They only
     // apply to replaced elements, and I'm not sure we count as a replaced
     // element when our image data is determined by CSS.
     dest = clientRect;
   } else {
     // Determine dest rect based on intrinsic size & ratio, along with
     // 'object-fit' & 'object-position' properties:
     IntrinsicSize intrinsicSize;
-    nsSize intrinsicRatio;
+    AspectRatio intrinsicRatio;
     if (mIntrinsicSize.width > 0 && mIntrinsicSize.height > 0) {
       // Image has a valid size; use it as intrinsic size & ratio.
       intrinsicSize =
           IntrinsicSize(mIntrinsicSize.width, mIntrinsicSize.height);
-      intrinsicRatio = mIntrinsicSize;
+      intrinsicRatio =
+          AspectRatio::FromSize(mIntrinsicSize.width, mIntrinsicSize.height);
     } else {
       // Image doesn't have a (valid) intrinsic size.
       // Try to look up intrinsic ratio and use that at least.
-      imgCon->GetIntrinsicRatio(&intrinsicRatio);
+      intrinsicRatio = imgCon->GetIntrinsicRatio().valueOr(AspectRatio());
     }
     aAnchorPoint.emplace();
     dest = nsLayoutUtils::ComputeObjectDestRect(clientRect, intrinsicSize,
                                                 intrinsicRatio, StylePosition(),
                                                 aAnchorPoint.ptr());
   }
 
   return dest;
--- a/mobile/android/app/mobile.js
+++ b/mobile/android/app/mobile.js
@@ -545,22 +545,20 @@ pref("notification.feature.enabled", tru
 pref("dom.webnotifications.enabled", true);
 
 // prevent tooltips from showing up
 pref("browser.chrome.toolbar_tips", false);
 
 // don't allow meta-refresh when backgrounded
 pref("browser.meta_refresh_when_inactive.disabled", true);
 
-// prevent video elements from preloading too much data
-pref("media.preload.default", 1); // default to preload none
-pref("media.preload.auto", 2);    // preload metadata if preload=auto
-// On mobile we'll throttle the download once the readahead_limit is hit,
-// even if the download is slow. This is to preserve battery and data.
-pref("media.throttle-regardless-of-download-rate", true);
+// On mobile we throttle the download once the readahead_limit is hit
+// if we're using a cellular connection, even if the download is slow.
+// This is to preserve battery and data.
+pref("media.throttle-cellular-regardless-of-download-rate", true);
 
 // Number of video frames we buffer while decoding video.
 // On Android this is decided by a similar value which varies for
 // each OMX decoder |OMX_PARAM_PORTDEFINITIONTYPE::nBufferCountMin|. This
 // number must be less than the OMX equivalent or gecko will think it is
 // chronically starved of video frames. All decoders seen so far have a value
 // of at least 4.
 pref("media.video-queue.default-size", 3);
--- a/mobile/android/geckoview/src/main/java/org/mozilla/geckoview/GeckoRuntime.java
+++ b/mobile/android/geckoview/src/main/java/org/mozilla/geckoview/GeckoRuntime.java
@@ -1,16 +1,21 @@
 /* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-
  * vim: ts=4 sw=4 expandtab:
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 package org.mozilla.geckoview;
 
+import android.arch.lifecycle.ProcessLifecycleOwner;
+import android.arch.lifecycle.Lifecycle;
+import android.arch.lifecycle.LifecycleObserver;
+import android.arch.lifecycle.OnLifecycleEvent;
+
 import android.app.ActivityManager;
 import android.content.ComponentName;
 import android.content.Context;
 import android.content.Intent;
 import android.content.pm.ApplicationInfo;
 import android.content.pm.PackageManager;
 import android.content.pm.ServiceInfo;
 import android.content.res.Configuration;
@@ -21,16 +26,17 @@ import android.os.Process;
 import android.support.annotation.AnyThread;
 import android.support.annotation.NonNull;
 import android.support.annotation.Nullable;
 import android.support.annotation.UiThread;
 import android.util.Log;
 
 import org.mozilla.gecko.EventDispatcher;
 import org.mozilla.gecko.GeckoAppShell;
+import org.mozilla.gecko.GeckoNetworkManager;
 import org.mozilla.gecko.GeckoScreenOrientation;
 import org.mozilla.gecko.GeckoSystemStateListener;
 import org.mozilla.gecko.GeckoThread;
 import org.mozilla.gecko.PrefsHelper;
 import org.mozilla.gecko.util.BundleEventListener;
 import org.mozilla.gecko.util.DebugConfig;
 import org.mozilla.gecko.util.EventCallback;
 import org.mozilla.gecko.util.GeckoBundle;
@@ -88,16 +94,46 @@ public final class GeckoRuntime implemen
      * This is a key for extra data sent with {@link #ACTION_CRASHED}. The value is
      * a boolean indicating whether or not the crash was fatal or not. If true, the
      * main application process was affected by the crash. If false, only an internal
      * process used by Gecko has crashed and the application may be able to recover.
      * @see GeckoSession.ContentDelegate#onCrash(GeckoSession)
      */
     public static final String EXTRA_CRASH_FATAL = "fatal";
 
+    private final class LifecycleListener implements LifecycleObserver {
+        public LifecycleListener() {
+        }
+
+        @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
+        void onCreate() {
+            Log.d(LOGTAG, "Lifecycle: onCreate");
+        }
+
+        @OnLifecycleEvent(Lifecycle.Event.ON_START)
+        void onStart() {
+            Log.d(LOGTAG, "Lifecycle: onStart");
+        }
+
+        @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
+        void onResume() {
+            Log.d(LOGTAG, "Lifecycle: onResume");
+            // Monitor network status and send change notifications to Gecko
+            // while active.
+            GeckoNetworkManager.getInstance().start(GeckoAppShell.getApplicationContext());
+        }
+
+        @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
+        void onPause() {
+            Log.d(LOGTAG, "Lifecycle: onPause");
+            // Stop monitoring network status while inactive.
+            GeckoNetworkManager.getInstance().stop();
+        }
+    }
+
     private static GeckoRuntime sDefaultRuntime;
 
     /**
      * Get the default runtime for the given context.
      * This will create and initialize the runtime with the default settings.
      *
      * Note: Only use this for session-less apps.
      *       For regular apps, use create() instead.
@@ -261,16 +297,19 @@ public final class GeckoRuntime implemen
         // Bug 1453062 -- the EventDispatcher should really live here (or in GeckoThread)
         EventDispatcher.getInstance().registerUiThreadListener(mEventListener, "Gecko:Exited");
 
         // Attach and commit settings.
         mSettings.attachTo(this);
 
         // Initialize the system ClipboardManager by accessing it on the main thread.
         GeckoAppShell.getApplicationContext().getSystemService(Context.CLIPBOARD_SERVICE);
+
+        // Add process lifecycle listener to react to backgrounding events.
+        ProcessLifecycleOwner.get().getLifecycle().addObserver(new LifecycleListener());
         return true;
     }
 
     /* package */ void setDefaultPrefs(final GeckoBundle prefs) {
         EventDispatcher.getInstance().dispatch("GeckoView:SetDefaultPrefs", prefs);
     }
 
     /**
--- a/modules/libpref/init/StaticPrefList.h
+++ b/modules/libpref/init/StaticPrefList.h
@@ -1430,27 +1430,28 @@ VARCACHE_PREF(
 //---------------------------------------------------------------------------
 // Media prefs
 //---------------------------------------------------------------------------
 
 // These prefs use camel case instead of snake case for the getter because one
 // reviewer had an unshakeable preference for that.
 
 // File-backed MediaCache size.
-#ifdef ANDROID
-# define PREF_VALUE  32768  // Measured in KiB
-#else
-# define PREF_VALUE 512000  // Measured in KiB
-#endif
 VARCACHE_PREF(
   "media.cache_size",
    MediaCacheSize,
-  RelaxedAtomicUint32, PREF_VALUE
+  uint32_t, 512000 // Measured in KiB
 )
-#undef PREF_VALUE
+// Size of file backed MediaCache while on a connection which is cellular (3G, etc),
+// and thus assumed to be "expensive".
+VARCACHE_PREF(
+  "media.cache_size.cellular",
+   MediaCacheCellularSize,
+  uint32_t, 32768 // Measured in KiB
+)
 
 // If a resource is known to be smaller than this size (in kilobytes), a
 // memory-backed MediaCache may be used; otherwise the (single shared global)
 // file-backed MediaCache is used.
 VARCACHE_PREF(
   "media.memory_cache_max_size",
    MediaMemoryCacheMaxSize,
   uint32_t, 8192      // Measured in KiB
@@ -1469,42 +1470,40 @@ VARCACHE_PREF(
 VARCACHE_PREF(
   "media.memory_caches_combined_limit_pc_sysmem",
    MediaMemoryCachesCombinedLimitPcSysmem,
   uint32_t, 5         // A percentage
 )
 
 // When a network connection is suspended, don't resume it until the amount of
 // buffered data falls below this threshold (in seconds).
-#ifdef ANDROID
-# define PREF_VALUE 10  // Use a smaller limit to save battery.
-#else
-# define PREF_VALUE 30
-#endif
 VARCACHE_PREF(
   "media.cache_resume_threshold",
    MediaCacheResumeThreshold,
-  RelaxedAtomicInt32, PREF_VALUE
+  uint32_t, 30
 )
-#undef PREF_VALUE
+VARCACHE_PREF(
+  "media.cache_resume_threshold.cellular",
+   MediaCacheCellularResumeThreshold,
+  uint32_t, 10
+)
 
 // Stop reading ahead when our buffered data is this many seconds ahead of the
 // current playback position. This limit can stop us from using arbitrary
 // amounts of network bandwidth prefetching huge videos.
-#ifdef ANDROID
-# define PREF_VALUE 30  // Use a smaller limit to save battery.
-#else
-# define PREF_VALUE 60
-#endif
 VARCACHE_PREF(
   "media.cache_readahead_limit",
    MediaCacheReadaheadLimit,
-  RelaxedAtomicInt32, PREF_VALUE
+  uint32_t, 60
 )
-#undef PREF_VALUE
+VARCACHE_PREF(
+  "media.cache_readahead_limit.cellular",
+   MediaCacheCellularReadaheadLimit,
+  uint32_t, 30
+)
 
 // AudioSink
 VARCACHE_PREF(
   "media.resampling.enabled",
    MediaResamplingEnabled,
   RelaxedAtomicBool, false
 )
 
--- a/parser/expat/lib/xmlparse.c
+++ b/parser/expat/lib/xmlparse.c
@@ -1760,26 +1760,26 @@ XML_SetElementDeclHandler(XML_Parser par
 
 void XMLCALL
 XML_SetAttlistDeclHandler(XML_Parser parser,
                           XML_AttlistDeclHandler attdecl)
 {
   if (parser != NULL)
     attlistDeclHandler = attdecl;
 }
+#endif
+/* END MOZILLA CHANGE */
 
 void XMLCALL
 XML_SetEntityDeclHandler(XML_Parser parser,
                          XML_EntityDeclHandler handler)
 {
   if (parser != NULL)
     entityDeclHandler = handler;
 }
-#endif
-/* END MOZILLA CHANGE */
 
 void XMLCALL
 XML_SetXmlDeclHandler(XML_Parser parser,
                       XML_XmlDeclHandler handler) {
   if (parser != NULL)
     xmlDeclHandler = handler;
 }
 
--- a/parser/htmlparser/nsExpatDriver.cpp
+++ b/parser/htmlparser/nsExpatDriver.cpp
@@ -149,16 +149,28 @@ static int Driver_HandleExternalEntityRe
 
   nsExpatDriver* driver =
       static_cast<nsExpatDriver*>(aExternalEntityRefHandler);
 
   return driver->HandleExternalEntityRef(aOpenEntityNames, aBase, aSystemId,
                                          aPublicId);
 }
 
+static void Driver_HandleEntityDecl(
+    void* aUserData, const XML_Char* aEntityName, int aIsParameterEntity,
+    const XML_Char* aValue, int aValueLength, const XML_Char* aBase,
+    const XML_Char* aSystemId, const XML_Char* aPublicId,
+    const XML_Char* aNotationName) {
+  NS_ASSERTION(aUserData, "expat driver should exist");
+  if (aUserData) {
+    static_cast<nsExpatDriver*>(aUserData)->HandleEntityDecl(
+        aEntityName, aValue, aValueLength);
+  }
+}
+
 /***************************** END CALL BACKS ********************************/
 
 /***************************** CATALOG UTILS *********************************/
 
 // Initially added for bug 113400 to switch from the remote "XHTML 1.0 plus
 // MathML 2.0" DTD to the the lightweight customized version that Mozilla uses.
 // Since Mozilla is not validating, no need to fetch a *huge* file at each
 // click.
@@ -469,16 +481,29 @@ nsresult nsExpatDriver::HandleEndDoctype
     MaybeStopParser(rv);
   }
 
   mInternalSubset.Truncate();
 
   return NS_OK;
 }
 
+void nsExpatDriver::HandleEntityDecl(const char16_t* aEntityName,
+                                     const char16_t* aEntityValue,
+                                     const uint32_t aLength) {
+  MOZ_ASSERT(
+      mInInternalSubset || mInExternalDTD,
+      "Should only see entity declarations in the internal subset or in DTDs");
+  auto charLength = aLength / sizeof(char16_t);
+  nsDependentSubstring entityVal(aEntityValue, charLength);
+  if (entityVal.FindChar('<') != -1) {
+    MaybeStopParser(NS_ERROR_UNEXPECTED);
+  }
+}
+
 static nsresult ExternalDTDStreamReaderFunc(nsIUnicharInputStream* aIn,
                                             void* aClosure,
                                             const char16_t* aFromSegment,
                                             uint32_t aToOffset, uint32_t aCount,
                                             uint32_t* aWriteCount) {
   // Pass the buffer to expat for parsing.
   if (XML_Parse((XML_Parser)aClosure, (const char*)aFromSegment,
                 aCount * sizeof(char16_t), 0) == XML_STATUS_OK) {
@@ -1052,16 +1077,19 @@ nsExpatDriver::WillBuildModel(const CPar
       (XML_ExternalEntityRefHandler)Driver_HandleExternalEntityRef);
   XML_SetExternalEntityRefHandlerArg(mExpatParser, this);
   XML_SetCommentHandler(mExpatParser, Driver_HandleComment);
   XML_SetCdataSectionHandler(mExpatParser, Driver_HandleStartCdataSection,
                              Driver_HandleEndCdataSection);
 
   XML_SetParamEntityParsing(mExpatParser,
                             XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE);
+  if (doc && doc->NodePrincipal()->IsSystemPrincipal()) {
+    XML_SetEntityDeclHandler(mExpatParser, Driver_HandleEntityDecl);
+  }
   XML_SetDoctypeDeclHandler(mExpatParser, Driver_HandleStartDoctypeDecl,
                             Driver_HandleEndDoctypeDecl);
 
   // Set up the user data.
   XML_SetUserData(mExpatParser, this);
 
   return mInternalState;
 }
--- a/parser/htmlparser/nsExpatDriver.h
+++ b/parser/htmlparser/nsExpatDriver.h
@@ -44,16 +44,18 @@ class nsExpatDriver : public nsIDTD, pub
   nsresult HandleDefault(const char16_t* aData, const uint32_t aLength);
   nsresult HandleStartCdataSection();
   nsresult HandleEndCdataSection();
   nsresult HandleStartDoctypeDecl(const char16_t* aDoctypeName,
                                   const char16_t* aSysid,
                                   const char16_t* aPubid,
                                   bool aHasInternalSubset);
   nsresult HandleEndDoctypeDecl();
+  void HandleEntityDecl(const char16_t* aEntityName,
+                        const char16_t* aEntityValue, const uint32_t aLength);
 
  private:
   // Load up an external stream to get external entity information
   nsresult OpenInputStreamFromExternalDTD(const char16_t* aFPIStr,
                                           const char16_t* aURLStr,
                                           const char16_t* aBaseURL,
                                           nsIInputStream** aStream,
                                           nsAString& aAbsURL);
--- a/remote/domains/content/Runtime.jsm
+++ b/remote/domains/content/Runtime.jsm
@@ -3,21 +3,30 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 "use strict";
 
 var EXPORTED_SYMBOLS = ["Runtime"];
 
 const {ContentProcessDomain} = ChromeUtils.import("chrome://remote/content/domains/ContentProcessDomain.jsm");
 const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
+const {ExecutionContext} = ChromeUtils.import("chrome://remote/content/domains/content/runtime/ExecutionContext.jsm");
+const {addDebuggerToGlobal} = ChromeUtils.import("resource://gre/modules/jsdebugger.jsm", {});
+
+// Import the `Debugger` constructor in the current scope
+addDebuggerToGlobal(Cu.getGlobalForObject(this));
 
 class Runtime extends ContentProcessDomain {
   constructor(session) {
     super(session);
     this.enabled = false;
+
+    // Map of all the ExecutionContext instances:
+    // [Execution context id (Number) => ExecutionContext instance]
+    this.contexts = new Map();
   }
 
   destructor() {
     this.disable();
   }
 
   // commands
 
@@ -33,27 +42,17 @@ class Runtime extends ContentProcessDoma
       this.chromeEventHandler.addEventListener("pagehide", this,
         {mozSystemGroup: true});
 
       Services.obs.addObserver(this, "inner-window-destroyed");
 
       // Spin the event loop in order to send the `executionContextCreated` event right
       // after we replied to `enable` request.
       Services.tm.dispatchToMainThread(() => {
-        const frameId = this.content.windowUtils.outerWindowID;
-        const id = this.content.windowUtils.currentInnerWindowID;
-        this.emit("Runtime.executionContextCreated", {
-          context: {
-            id,
-            auxData: {
-              isDefault: true,
-              frameId,
-            },
-          },
-        });
+        this._createContext(this.content);
       });
     }
   }
 
   disable() {
     if (this.enabled) {
       this.enabled = false;
       this.chromeEventHandler.removeEventListener("DOMWindowCreated", this,
@@ -61,59 +60,111 @@ class Runtime extends ContentProcessDoma
       this.chromeEventHandler.removeEventListener("pageshow", this,
         {mozSystemGroup: true});
       this.chromeEventHandler.removeEventListener("pagehide", this,
         {mozSystemGroup: true});
       Services.obs.removeObserver(this, "inner-window-destroyed");
     }
   }
 
+  evaluate(request) {
+    const context = this.contexts.get(request.contextId);
+    if (!context) {
+      throw new Error(`Unable to find execution context with id: ${request.contextId}`);
+    }
+    if (typeof(request.expression) != "string") {
+      throw new Error(`Expecting 'expression' attribute to be a string. ` +
+        `But was: ${typeof(request.expression)}`);
+    }
+    return context.evaluate(request.expression);
+  }
+
+  get _debugger() {
+    if (this.__debugger) {
+      return this.__debugger;
+    }
+    this.__debugger = new Debugger();
+    return this.__debugger;
+  }
+
   handleEvent({type, target, persisted}) {
-    const frameId = target.defaultView.windowUtils.outerWindowID;
-    const id = target.defaultView.windowUtils.currentInnerWindowID;
+    if (target.defaultView != this.content) {
+      // Ignore iframes for now.
+      return;
+    }
     switch (type) {
     case "DOMWindowCreated":
-      this.emit("Runtime.executionContextCreated", {
-        context: {
-          id,
-          auxData: {
-            isDefault: target == this.content.document,
-            frameId,
-          },
-        },
-      });
+      this._createContext(target.defaultView);
       break;
 
     case "pageshow":
       // `persisted` is true when this is about a page being resurected from BF Cache
       if (!persisted) {
         return;
       }
-      this.emit("Runtime.executionContextCreated", {
-        context: {
-          id,
-          auxData: {
-            isDefault: target == this.content.document,
-            frameId,
-          },
-        },
-      });
+      this._createContext(target.defaultView);
       break;
 
     case "pagehide":
       // `persisted` is true when this is about a page being frozen into BF Cache
       if (!persisted) {
         return;
       }
-      this.emit("Runtime.executionContextDestroyed", {
-        executionContextId: id,
-      });
+      const id = target.defaultView.windowUtils.currentInnerWindowID;
+      this._destroyContext(id);
       break;
     }
   }
 
   observe(subject, topic, data) {
     const innerWindowID = subject.QueryInterface(Ci.nsISupportsPRUint64).data;
-    this.emit("Runtime.executionContextDestroyed", {
-      executionContextId: innerWindowID,
+    this._destroyContext(innerWindowID);
+  }
+
+  /**
+   * Helper method in order to instantiate the ExecutionContext for a given
+   * DOM Window as well as emitting the related `Runtime.executionContextCreated`
+   * event.
+   *
+   * @param {Window} window
+   *     The window object of the newly instantiated document.
+   */
+  _createContext(window) {
+    const { windowUtils } = window;
+    const id = windowUtils.currentInnerWindowID;
+    if (this.contexts.has(id)) {
+      return;
+    }
+
+    const context = new ExecutionContext(this._debugger, window);
+    this.contexts.set(id, context);
+
+    const frameId = windowUtils.outerWindowID;
+    this.emit("Runtime.executionContextCreated", {
+      context: {
+        id,
+        auxData: {
+          isDefault: window == this.content,
+          frameId,
+        },
+      },
     });
   }
+
+  /**
+   * Helper method to destroy the ExecutionContext of the given id. Also emit
+   * the related `Runtime.executionContextDestroyed` event.
+   *
+   * @param {Number} id
+   *     The execution context id to destroy.
+   */
+  _destroyContext(id) {
+    const context = this.contexts.get(id);
+
+    if (context) {
+      context.destructor();
+      this.contexts.delete(id);
+      this.emit("Runtime.executionContextDestroyed", {
+        executionContextId: id,
+      });
+    }
+  }
 }
new file mode 100644
--- /dev/null
+++ b/remote/domains/content/runtime/ExecutionContext.jsm
@@ -0,0 +1,189 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+var EXPORTED_SYMBOLS = ["ExecutionContext"];
+
+const uuidGen = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator);
+
+const TYPED_ARRAY_CLASSES = ["Uint8Array", "Uint8ClampedArray", "Uint16Array",
+                             "Uint32Array", "Int8Array", "Int16Array", "Int32Array",
+                             "Float32Array", "Float64Array"];
+function uuid() {
+  return uuidGen.generateUUID().toString().slice(1, -1);
+}
+
+/**
+ * This class represent a debuggable context onto which we can evaluate Javascript.
+ * This is typically a document, but it could also be a worker, an add-on, ... or
+ * any kind of context involving JS scripts.
+ *
+ * @param {Debugger} dbg
+ *   A Debugger instance that we can use to inspect the given global.
+ * @param {GlobalObject} debuggee
+ *   The debuggable context's global object. This is typically the document window
+ *   object. But it can also be any global object, like a worker global scope object.
+ */
+class ExecutionContext {
+  constructor(dbg, debuggee) {
+    this._debugger = dbg;
+    this._debuggee = this._debugger.addDebuggee(debuggee);
+
+    this._remoteObjects = new Map();
+  }
+
+  destructor() {
+    this._debugger.removeDebuggee(this._debuggee);
+  }
+
+  /**
+   * Evaluate a Javascript expression.
+   *
+   * @param {String} expression
+   *   The JS expression to evaluate against the JS context.
+   * @return {Object} A multi-form object depending if the execution succeed or failed.
+   *   If the expression failed to evaluate, it will return an object with an
+   *   `exceptionDetails` attribute matching the `ExceptionDetails` CDP type.
+   *   Otherwise it will return an object with `result` attribute whose type is
+   *   `RemoteObject` CDP type.
+   */
+  evaluate(expression) {
+    let rv = this._debuggee.executeInGlobal(expression);
+    if (!rv) {
+      return {
+        exceptionDetails: {
+          text: "Evaluation terminated!",
+        },
+      };
+    }
+    if (rv.throw) {
+      if (this._debuggee.executeInGlobalWithBindings("e instanceof Error", {e: rv.throw}).return) {
+        return {
+          exceptionDetails: {
+            text: this._debuggee.executeInGlobalWithBindings("e.message", {e: rv.throw}).return,
+          },
+        };
+      }
+      return {
+        exceptionDetails: {
+          exception: this._createRemoteObject(rv.throw),
+        },
+      };
+    }
+    return {
+      result: this._createRemoteObject(rv.return),
+    };
+  }
+
+  /**
+   * Convert a given `Debugger.Object` to a JSON string.
+   *
+   * @param {Debugger.Object} obj
+   *  The object to convert
+   * @return {String}
+   *  The JSON string
+   */
+  _serialize(obj) {
+    const result = this._debuggee.executeInGlobalWithBindings("JSON.stringify(e)", {e: obj});
+    if (result.throw) {
+      throw new Error("Object is not serializable");
+    }
+    return JSON.parse(result.return);
+  }
+
+  /**
+   * Given a `Debugger.Object` object, return a JSON-serializable description of it
+   * matching `RemoteObject` CDP type.
+   *
+   * @param {Debugger.Object} debuggerObj
+   *  The object to serialize
+   * @return {RemoteObject}
+   *  The serialized description of the given object
+   */
+  _createRemoteObject(debuggerObj) {
+    // First handle all non-primitive values which are going to be wrapped by the
+    // Debugger API into Debugger.Object instances
+    if (debuggerObj instanceof Debugger.Object) {
+      const objectId = uuid();
+      this._remoteObjects.set(objectId, debuggerObj);
+      const rawObj = debuggerObj.unsafeDereference();
+
+      // Map the Debugger API `class` attribute to CDP `subtype`
+      const cls = debuggerObj.class;
+      let subtype;
+      if (debuggerObj.isProxy) {
+        subtype = "proxy";
+      } else if (cls == "Array") {
+        subtype = "array";
+      } else if (cls == "RegExp") {
+        subtype = "regexp";
+      } else if (cls == "Date") {
+        subtype = "date";
+      } else if (cls == "Map") {
+        subtype = "map";
+      } else if (cls == "Set") {
+        subtype = "set";
+      } else if (cls == "WeakMap") {
+        subtype = "weakmap";
+      } else if (cls == "WeakSet") {
+        subtype = "weakset";
+      } else if (cls == "Error") {
+        subtype = "error";
+      } else if (cls == "Promise") {
+        subtype = "promise";
+      } else if (TYPED_ARRAY_CLASSES.includes(cls)) {
+        subtype = "typedarray";
+      } else if (cls == "Object" && Node.isInstance(rawObj)) {
+        subtype = "node";
+      }
+
+      const type = typeof rawObj;
+      return {objectId, type, subtype};
+    }
+
+    // Now, handle all values that Debugger API isn't wrapping into Debugger.API.
+    // This is all the primitive JS types.
+    const type = typeof debuggerObj;
+
+    // Symbol and BigInt are primitive values but aren't serializable.
+    // CDP expects them to be considered as objects, with an objectId to later inspect
+    // them.
+    if (type == "symbol" || type == "bigint") {
+      const objectId = uuid();
+      this._remoteObjects.set(objectId, debuggerObj);
+      return {objectId, type};
+    }
+
+    // A few primitive type can't be serialized and CDP has special case for them
+    let unserializableValue = undefined;
+    if (Object.is(debuggerObj, NaN))
+      unserializableValue = "NaN";
+    else if (Object.is(debuggerObj, -0))
+      unserializableValue = "-0";
+    else if (Object.is(debuggerObj, Infinity))
+      unserializableValue = "Infinity";
+    else if (Object.is(debuggerObj, -Infinity))
+      unserializableValue = "-Infinity";
+    if (unserializableValue) {
+      return {
+        unserializableValue,
+      };
+    }
+
+    // Otherwise, we serialize the primitive values as-is via `value` attribute
+
+    // null is special as it has a dedicated subtype
+    let subtype;
+    if (debuggerObj === null) {
+      subtype = "null";
+    }
+
+    return {
+      type,
+      subtype,
+      value: debuggerObj,
+    };
+  }
+}
--- a/remote/jar.mn
+++ b/remote/jar.mn
@@ -37,16 +37,17 @@ remote.jar:
   content/domains/content/DOM.jsm (domains/content/DOM.jsm)
   content/domains/content/Emulation.jsm (domains/content/Emulation.jsm)
   content/domains/content/Input.jsm (domains/content/Input.jsm)
   content/domains/content/Log.jsm (domains/content/Log.jsm)
   content/domains/content/Network.jsm (domains/content/Network.jsm)
   content/domains/content/Page.jsm (domains/content/Page.jsm)
   content/domains/content/Performance.jsm (domains/content/Performance.jsm)
   content/domains/content/Runtime.jsm (domains/content/Runtime.jsm)
+  content/domains/content/runtime/ExecutionContext.jsm (domains/content/runtime/ExecutionContext.jsm)
   content/domains/content/Security.jsm (domains/content/Security.jsm)
   content/domains/parent/Browser.jsm (domains/parent/Browser.jsm)
   content/domains/parent/Target.jsm (domains/parent/Target.jsm)
 
   # transport layer
   content/server/HTTPD.jsm (../netwerk/test/httpserver/httpd.js)
   content/server/Stream.jsm (server/Stream.jsm)
   content/server/WebSocket.jsm (server/WebSocket.jsm)
--- a/remote/test/browser/browser.ini
+++ b/remote/test/browser/browser.ini
@@ -4,12 +4,13 @@ prefs = remote.enabled=true
 support-files =
   chrome-remote-interface.js
   head.js
 skip-if = debug || asan # bug 1546945
 
 [browser_cdp.js]
 [browser_main_target.js]
 [browser_page_frameNavigated.js]
+[browser_runtime_evaluate.js]
 [browser_runtime_executionContext.js]
 skip-if = os == "mac" || (verify && os == 'win') # bug 1547961
 [browser_tabs.js]
 [browser_target.js]
new file mode 100644
--- /dev/null
+++ b/remote/test/browser/browser_runtime_evaluate.js
@@ -0,0 +1,167 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/* global getCDP */
+
+const {RemoteAgent} = ChromeUtils.import("chrome://remote/content/RemoteAgent.jsm");
+const {RemoteAgentError} = ChromeUtils.import("chrome://remote/content/Error.jsm");
+
+// Test the Runtime execution context events
+
+const TEST_URI = "data:text/html;charset=utf-8,default-test-page";
+
+add_task(async function() {
+  try {
+    await testCDP();
+  } catch (e) {
+    // Display better error message with the server side stacktrace
+    // if an error happened on the server side:
+    if (e.response) {
+      throw RemoteAgentError.fromJSON(e.response);
+    } else {
+      throw e;
+    }
+  }
+});
+
+async function testCDP() {
+  // Open a test page, to prevent debugging the random default page
+  await BrowserTestUtils.openNewForegroundTab(gBrowser, TEST_URI);
+
+  // Start the CDP server
+  RemoteAgent.init();
+  RemoteAgent.tabs.start();
+  RemoteAgent.listen(Services.io.newURI("http://localhost:9222"));
+
+  // Retrieve the chrome-remote-interface library object
+  const CDP = await getCDP();
+
+  // Connect to the server
+  const client = await CDP({
+    target(list) {
+      // Ensure debugging the right target, i.e. the one for our test tab.
+      return list.find(target => target.url == TEST_URI);
+    },
+  });
+  ok(true, "CDP client has been instantiated");
+
+  const firstContext = await testRuntimeEnable(client);
+  const contextId = firstContext.id;
+  await testEvaluate(client, contextId);
+  await testInvalidContextId(client, contextId);
+  await testPrimitiveTypes(client, contextId);
+  await testUnserializable(client, contextId);
+  await testObjectTypes(client, contextId);
+  await testThrowError(client, contextId);
+  await testThrowValue(client, contextId);
+  await testJSError(client, contextId);
+
+  await client.close();
+  ok(true, "The client is closed");
+
+  BrowserTestUtils.removeTab(gBrowser.selectedTab);
+
+  await RemoteAgent.close();
+}
+
+async function testRuntimeEnable({ Runtime }) {
+  // Enable watching for new execution context
+  await Runtime.enable();
+  ok(true, "Runtime domain has been enabled");
+
+  // Calling Runtime.enable will emit executionContextCreated for the existing contexts
+  const { context } = await Runtime.executionContextCreated();
+  ok(!!context.id, "The execution context has an id");
+  ok(context.auxData.isDefault, "The execution context is the default one");
+  ok(!!context.auxData.frameId, "The execution context has a frame id set");
+
+  return context;
+}
+
+async function testEvaluate({ Runtime }, contextId) {
+  let { result } = await Runtime.evaluate({ contextId, expression: "location.href" });
+  is(result.value, TEST_URI, "Runtime.evaluate works and is against the test page");
+}
+
+async function testInvalidContextId({ Runtime }, contextId) {
+  try {
+    await Runtime.evaluate({ contextId: -1, expression: "" });
+    ok(false, "Evaluate shouldn't pass");
+  } catch (e) {
+    ok(e.message.includes("Unable to find execution context with id: -1"),
+      "Throws with the expected error message");
+  }
+}
+
+async function testPrimitiveTypes({ Runtime }, contextId) {
+  const expressions = [42, "42", true, 4.2];
+  for (const expression of expressions) {
+    const { result } = await Runtime.evaluate({ contextId, expression: JSON.stringify(expression) });
+    is(result.value, expression, `Evaluating primitive '${expression}' works`);
+    is(result.type, typeof(expression), `${expression} type is correct`);
+  }
+
+  // undefined doesn't work with JSON.stringify, so test it independently
+  let { result } = await Runtime.evaluate({ contextId, expression: "undefined" });
+  is(result.value, undefined, "undefined works");
+  is(result.type, "undefined", "undefined type is correct");
+
+  // `null` is special as it has its own subtype, is of type 'object' but is returned as
+  // a value, without an `objectId` attribute
+  ({ result } = await Runtime.evaluate({ contextId, expression: "null" }));
+  is(result.value, null, "Evaluating 'null' works");
+  is(result.type, "object", "'null' type is correct");
+  is(result.subtype, "null", "'null' subtype is correct");
+  ok(!result.objectId, "'null' has no objectId");
+}
+
+async function testUnserializable({ Runtime }, contextId) {
+  const expressions = ["NaN", "-0", "Infinity", "-Infinity"];
+  for (const expression of expressions) {
+    const { result } = await Runtime.evaluate({ contextId, expression });
+    is(result.unserializableValue, expression, `Evaluating unserializable '${expression}' works`);
+  }
+}
+
+async function testObjectTypes({ Runtime }, contextId) {
+  const expressions = [
+    { expression: "({foo:true})", type: "object", subtype: null },
+    { expression: "Symbol('foo')", type: "symbol", subtype: null },
+    { expression: "BigInt(42)", type: "bigint", subtype: null },
+    { expression: "new Promise(()=>{})", type: "object", subtype: "promise" },
+    { expression: "new Int8Array(8)", type: "object", subtype: "typedarray" },
+    { expression: "new WeakMap()", type: "object", subtype: "weakmap" },
+    { expression: "new WeakSet()", type: "object", subtype: "weakset" },
+    { expression: "new Map()", type: "object", subtype: "map" },
+    { expression: "new Set()", type: "object", subtype: "set" },
+    { expression: "/foo/", type: "object", subtype: "regexp" },
+    { expression: "[1, 2]", type: "object", subtype: "array" },
+    { expression: "new Proxy({}, {})", type: "object", subtype: "proxy" },
+    { expression: "new Date()", type: "object", subtype: "date" },
+  ];
+
+  for (const { expression, type, subtype } of expressions) {
+    const { result } = await Runtime.evaluate({ contextId, expression });
+    is(result.subtype, subtype, `Evaluating '${expression}' has the expected subtype`);
+    is(result.type, type, "The type is correct");
+    ok(!!result.objectId, "Got an object id");
+  }
+}
+
+async function testThrowError({ Runtime }, contextId) {
+  const { exceptionDetails } = await Runtime.evaluate({ contextId, expression: "throw new Error('foo')" });
+  is(exceptionDetails.text, "foo", "Exception message is passed to the client");
+}
+
+async function testThrowValue({ Runtime }, contextId) {
+  const { exceptionDetails } = await Runtime.evaluate({ contextId, expression: "throw 'foo'" });
+  is(exceptionDetails.exception.type, "string", "Exception type is correct");
+  is(exceptionDetails.exception.value, "foo", "Exception value is passed as a RemoteObject");
+}
+
+async function testJSError({ Runtime }, contextId) {
+  const { exceptionDetails } = await Runtime.evaluate({ contextId, expression: "doesNotExists()" });
+  is(exceptionDetails.text, "doesNotExists is not defined", "Exception message is passed to the client");
+}
--- a/remote/test/browser/browser_runtime_executionContext.js
+++ b/remote/test/browser/browser_runtime_executionContext.js
@@ -42,63 +42,110 @@ async function testCDP() {
   const client = await CDP({
     target(list) {
       // Ensure debugging the right target, i.e. the one for our test tab.
       return list.find(target => target.url == TEST_URI);
     },
   });
   ok(true, "CDP client has been instantiated");
 
-  const {Page, Runtime} = client;
-
-  // turn on navigation related events, such as DOMContentLoaded et al.
-  await Runtime.enable();
-  ok(true, "Runtime domain has been enabled");
-
-  // Calling Runtime.enable will emit executionContextCreated for the existing contexts
-  const { context: context1 } = await Runtime.executionContextCreated();
-  ok(!!context1.id, "The execution context has an id");
-  ok(context1.auxData.isDefault, "The execution context is the default one");
-  ok(!!context1.auxData.frameId, "The execution context has a frame id set");
-
-  info("Navigate to a new URL");
-  const executionContextDestroyed2 = Runtime.executionContextDestroyed();
-  const executionContextCreated2 = Runtime.executionContextCreated();
-
-  const url = "data:text/html;charset=utf-8,test-page";
-  const { frameId } = await Page.navigate({ url });
-  ok(true, "A new page has been loaded");
-  is(frameId, context1.auxData.frameId, "Page.navigate returns the same frameId than executionContextCreated");
-
-  let { executionContextId } = await executionContextDestroyed2;
-  is(executionContextId, context1.id, "The destroyed event reports the previous context id");
+  const firstContext = await testRuntimeEnable(client);
+  await testEvaluate(client, firstContext);
+  const secondContext = await testNavigate(client, firstContext);
+  await testNavigateBack(client, firstContext, secondContext);
+  await testNavigateViaLocation(client, firstContext);
 
-  const { context: context2 } = await executionContextCreated2;
-  ok(!!context2.id, "The execution context has an id");
-  isnot(context1.id, context2.id, "The new execution context has a different id");
-  ok(context2.auxData.isDefault, "The execution context is the default one");
-  is(context2.auxData.frameId, frameId, "The execution context frame id is the same " +
-    "than the one returned by Page.navigate");
-
-  isnot(executionContextId, context2.id, "The destroyed id is different from the " +
-    "created one");
-
-  // Navigates back to the previous page.
-  // This should resurect the original document from the BF Cache and recreate the
-  // context for it
-  info("Navigate back to the previous document");
-  const executionContextDestroyed3 = Runtime.executionContextDestroyed();
-  const executionContextCreated3 = Runtime.executionContextCreated();
-  gBrowser.selectedBrowser.goBack();
-  const { context: context3 } = await executionContextCreated3;
-  is(context3.id, context1.id, "The new execution context should be the same than the first one");
-  ok(context3.auxData.isDefault, "The execution context is the default one");
-  is(context3.auxData.frameId, frameId, "The execution context frame id is always the same");
-
-  ({ executionContextId } = await executionContextDestroyed3);
-  is(executionContextId, context2.id, "The destroyed event reports the previous context id");
   await client.close();
   ok(true, "The client is closed");
 
   BrowserTestUtils.removeTab(gBrowser.selectedTab);
 
   await RemoteAgent.close();
 }
+
+async function testRuntimeEnable({ Runtime }) {
+  // Enable watching for new execution context
+  await Runtime.enable();
+  ok(true, "Runtime domain has been enabled");
+
+  // Calling Runtime.enable will emit executionContextCreated for the existing contexts
+  const { context } = await Runtime.executionContextCreated();
+  ok(!!context.id, "The execution context has an id");
+  ok(context.auxData.isDefault, "The execution context is the default one");
+  ok(!!context.auxData.frameId, "The execution context has a frame id set");
+
+  return context;
+}
+
+async function testEvaluate({ Runtime }, previousContext) {
+  const contextId = previousContext.id;
+
+  const { result } = await Runtime.evaluate({ contextId, expression: "location.href" });
+  is(result.value, TEST_URI, "Runtime.evaluate works and is against the test page");
+}
+
+async function testNavigate({ Runtime, Page }, previousContext) {
+  info("Navigate to a new URL");
+  const executionContextDestroyed = Runtime.executionContextDestroyed();
+  const executionContextCreated = Runtime.executionContextCreated();
+
+  const url = "data:text/html;charset=utf-8,test-page";
+  const { frameId } = await Page.navigate({ url });
+  ok(true, "A new page has been loaded");
+  is(frameId, previousContext.auxData.frameId, "Page.navigate returns the same frameId than executionContextCreated");
+
+  const { executionContextId } = await executionContextDestroyed;
+  is(executionContextId, previousContext.id, "The destroyed event reports the previous context id");
+
+  const { context } = await executionContextCreated;
+  ok(!!context.id, "The execution context has an id");
+  isnot(previousContext.id, context.id, "The new execution context has a different id");
+  ok(context.auxData.isDefault, "The execution context is the default one");
+  is(context.auxData.frameId, frameId, "The execution context frame id is the same " +
+    "than the one returned by Page.navigate");
+
+  isnot(executionContextId, context.id, "The destroyed id is different from the " +
+    "created one");
+
+  return context;
+}
+
+// Navigates back to the previous page.
+// This should resurect the original document from the BF Cache and recreate the
+// context for it
+async function testNavigateBack({ Runtime }, firstContext, previousContext) {
+  info("Navigate back to the previous document");
+  const executionContextDestroyed = Runtime.executionContextDestroyed();
+  const executionContextCreated = Runtime.executionContextCreated();
+
+  gBrowser.selectedBrowser.goBack();
+
+  const { context } = await executionContextCreated;
+  is(context.id, firstContext.id, "The new execution context should be the same than the first one");
+  ok(context.auxData.isDefault, "The execution context is the default one");
+  is(context.auxData.frameId, firstContext.auxData.frameId, "The execution context frame id is always the same");
+
+  const { executionContextId } = await executionContextDestroyed;
+  is(executionContextId, previousContext.id, "The destroyed event reports the previous context id");
+
+  const { result } = await Runtime.evaluate({ contextId: context.id, expression: "location.href" });
+  is(result.value, TEST_URI, "Runtime.evaluate works and is against the page we just navigated to");
+}
+
+async function testNavigateViaLocation({ Runtime }, previousContext) {
+  const executionContextDestroyed = Runtime.executionContextDestroyed();
+  const executionContextCreated = Runtime.executionContextCreated();
+
+  const url2 = "data:text/html;charset=utf-8,test-page-2";
+  await Runtime.evaluate({ contextId: previousContext.id, expression: `window.location = '${url2}';` });
+
+  const { executionContextId } = await executionContextDestroyed;
+  is(executionContextId, previousContext.id, "The destroyed event reports the previous context id");
+
+  const { context } = await executionContextCreated;
+  ok(!!context.id, "The execution context has an id");
+  ok(context.auxData.isDefault, "The execution context is the default one");
+  is(context.auxData.frameId, previousContext.auxData.frameId, "The execution context frame id is the same " +
+    "the one returned by Page.navigate");
+
+  isnot(executionContextId, context.id, "The destroyed id is different from the " +
+    "created one");
+}
--- a/testing/mozharness/mozharness/mozilla/testing/android.py
+++ b/testing/mozharness/mozharness/mozilla/testing/android.py
@@ -245,16 +245,22 @@ class AndroidMixin(object):
         '''
         Dump some host and android device performance-related information
         to an artifact file, to help understand task performance.
         '''
         dir = self.query_abs_dirs()['abs_blob_upload_dir']
         perf_path = os.path.join(dir, "android-performance.log")
         with open(perf_path, "w") as f:
 
+            f.write('\n\nHost cpufreq/scaling_governor:\n')
+            cpus = glob.glob('/sys/devices/system/cpu/cpu*/cpufreq/scaling_governor')
+            for cpu in cpus:
+                out = subprocess.check_output(['cat', cpu])
+                f.write("%s: %s" % (cpu, out))
+
             f.write('\n\nHost /proc/cpuinfo:\n')
             out = subprocess.check_output(['cat', '/proc/cpuinfo'])
             f.write(out)
 
             f.write('\n\nHost /proc/meminfo:\n')
             out = subprocess.check_output(['cat', '/proc/meminfo'])
             f.write(out)
 
--- a/testing/profiles/unittest-required/user.js
+++ b/testing/profiles/unittest-required/user.js
@@ -172,16 +172,17 @@ user_pref("media.hls.server.url", "http:
 // Don't block old libavcodec libraries when testing, because our test systems
 // cannot easily be upgraded.
 user_pref("media.libavcodec.allow-obsolete", true);
 user_pref("media.memory_cache_max_size", 32);
 user_pref("media.memory_caches_combined_limit_kb", 256);
 user_pref("media.openUnsupportedTypeWithExternalApp", false);
 user_pref("media.preload.auto", 3); // auto = enough
 user_pref("media.preload.default", 2); // default = metadata
+user_pref("media.preload.default.cellular", 2); // default = metadata
 user_pref("media.suspend-bkgnd-video.enabled", false);
 user_pref("media.test.dumpDebugInfo", true);
 user_pref("media.volume_scale", "0.01");
 // Enable speech synth test service, and disable built in platform services.
 user_pref("media.webspeech.synth.test", true);
 user_pref("network.http.prompt-temp-redirect", false);
 // Disable speculative connections so they aren't reported as leaking when they're hanging around.
 user_pref("network.http.speculative-parallel-limit", 0);
new file mode 100644
--- /dev/null
+++ b/testing/web-platform/meta/editing/other/exec-command-with-text-editor.tentative.html.ini
@@ -0,0 +1,198 @@
+[exec-command-with-text-editor.tentative.html]
+  [In <input>, execCommand("cut", false, null), ab\[\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <input>, execCommand("cut", false, null), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <input>, execCommand("copy", false, null), abc\[\]d): calling execCommand()]
+    expected: FAIL
+
+  [In <input>, execCommand("copy", false, null), a\[bc\]d): calling execCommand()]
+    expected: FAIL
+
+  [In <input>, execCommand("delete", false, null), ab\[\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <input>, execCommand("delete", false, null), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <input>, execCommand("forwarddelete", false, null), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <input>, execCommand("forwarddelete", false, null), a\[\]bc): calling execCommand()]
+    expected: FAIL
+
+  [In <input>, execCommand("selectall", false, null), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <input>, execCommand("undo", false, null), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <input>, execCommand("redo", false, null), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <input>, execCommand("inserthtml", false, <b>inserted</b>), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <input>, execCommand("inserttext", false, **inserted**), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <input>, execCommand("insertparagraph", false, null), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <input>, execCommand("insertlinebreak", false, null), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <textarea>, execCommand("cut", false, null), ab\[\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <textarea>, execCommand("cut", false, null), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <textarea>, execCommand("copy", false, null), abc\[\]d): calling execCommand()]
+    expected: FAIL
+
+  [In <textarea>, execCommand("copy", false, null), a\[bc\]d): calling execCommand()]
+    expected: FAIL
+
+  [In <textarea>, execCommand("delete", false, null), ab\[\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <textarea>, execCommand("delete", false, null), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <textarea>, execCommand("forwarddelete", false, null), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <textarea>, execCommand("forwarddelete", false, null), a\[\]bc): calling execCommand()]
+    expected: FAIL
+
+  [In <textarea>, execCommand("selectall", false, null), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <textarea>, execCommand("undo", false, null), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <textarea>, execCommand("redo", false, null), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <textarea>, execCommand("inserthtml", false, <b>inserted</b>), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <textarea>, execCommand("inserttext", false, **inserted**), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <textarea>, execCommand("insertparagraph", false, null), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <textarea>, execCommand("insertlinebreak", false, null), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <input> in contenteditable, execCommand("bold", false, bold), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <input> in contenteditable, execCommand("italic", false, null), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <input> in contenteditable, execCommand("underline", false, null), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <input> in contenteditable, execCommand("strikethrough", false, null), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <input> in contenteditable, execCommand("superscript", false, null), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <input> in contenteditable, execCommand("cut", false, null), ab\[\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <input> in contenteditable, execCommand("cut", false, null), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <input> in contenteditable, execCommand("copy", false, null), abc\[\]d): calling execCommand()]
+    expected: FAIL
+
+  [In <input> in contenteditable, execCommand("copy", false, null), a\[bc\]d): calling execCommand()]
+    expected: FAIL
+
+  [In <input> in contenteditable, execCommand("delete", false, null), ab\[\]c): checking value and selection after execCommand()]
+    expected: FAIL
+
+  [In <input> in contenteditable, execCommand("delete", false, null), ab\[\]c): checking input event]
+    expected: FAIL
+
+  [In <input> in contenteditable, execCommand("delete", false, null), a\[b\]c): checking value and selection after execCommand()]
+    expected: FAIL
+
+  [In <input> in contenteditable, execCommand("delete", false, null), a\[b\]c): checking input event]
+    expected: FAIL
+
+  [In <input> in contenteditable, execCommand("forwarddelete", false, null), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <input> in contenteditable, execCommand("forwarddelete", false, null), a\[\]bc): calling execCommand()]
+    expected: FAIL
+
+  [In <input> in contenteditable, execCommand("selectall", false, null), a\[b\]c): checking value and selection after execCommand()]
+    expected: FAIL
+
+  [In <input> in contenteditable, execCommand("redo", false, null), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <input> in contenteditable, execCommand("inserthtml", false, <b>inserted</b>), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <input> in contenteditable, execCommand("inserttext", false, **inserted**), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <input> in contenteditable, execCommand("insertparagraph", false, null), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <input> in contenteditable, execCommand("insertlinebreak", false, null), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <textarea> in contenteditable, execCommand("cut", false, null), ab\[\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <textarea> in contenteditable, execCommand("cut", false, null), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <textarea> in contenteditable, execCommand("copy", false, null), abc\[\]d): calling execCommand()]
+    expected: FAIL
+
+  [In <textarea> in contenteditable, execCommand("copy", false, null), a\[bc\]d): calling execCommand()]
+    expected: FAIL
+
+  [In <textarea> in contenteditable, execCommand("delete", false, null), ab\[\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <textarea> in contenteditable, execCommand("delete", false, null), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <textarea> in contenteditable, execCommand("forwarddelete", false, null), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <textarea> in contenteditable, execCommand("forwarddelete", false, null), a\[\]bc): calling execCommand()]
+    expected: FAIL
+
+  [In <textarea> in contenteditable, execCommand("selectall", false, null), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <textarea> in contenteditable, execCommand("undo", false, null), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <textarea> in contenteditable, execCommand("redo", false, null), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <textarea> in contenteditable, execCommand("inserthtml", false, <b>inserted</b>), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <textarea> in contenteditable, execCommand("inserttext", false, **inserted**), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <textarea> in contenteditable, execCommand("insertparagraph", false, null), a\[b\]c): calling execCommand()]
+    expected: FAIL
+
+  [In <textarea> in contenteditable, execCommand("insertlinebreak", false, null), a\[b\]c): calling execCommand()]
+    expected: FAIL
new file mode 100644
--- /dev/null
+++ b/testing/web-platform/tests/editing/other/exec-command-with-text-editor.tentative.html
@@ -0,0 +1,341 @@
+<!doctype html>
+<meta charset=utf-8>
+<title>Test that execCommand with &lt;input&gt; or &lt;textarea&gt;</title>
+<script src=/resources/testharness.js></script>
+<script src=/resources/testharnessreport.js></script>
+<div id="container"></div>
+<script>
+"use strict";
+
+setup({explicit_done: true});
+
+/**
+ * This test checks whether document.execCommand() does something expected or
+ * not in <input> and <textarea> with/without contenteditable parent.  Although
+ * this is not standardized even by any drafts.  So, this test uses expected
+ * values which may be expected by web developers.
+ */
+function runTests() {
+  let container = document.getElementById("container");
+  container.innerHTML = "<input id=\"target\">";
+  runTest(document.getElementById("target"), "In <input>");
+  container.innerHTML = "<textarea id=\"target\"></textarea>";
+  runTest(document.getElementById("target"), "In <textarea>");
+  container.setAttribute("contenteditable", "true");
+  container.innerHTML = "<input id=\"target\">";
+  runTest(document.getElementById("target"), "In <input> in contenteditable");
+  container.innerHTML = "<textarea id=\"target\"></textarea>";
+  runTest(document.getElementById("target"), "In <textarea> in contenteditable");
+
+  done();
+}
+
+function runTest(aTarget, aDescription) {
+  const kIsTextArea = aTarget.tagName === "TEXTAREA";
+  const kTests = [
+    /**
+     * command: command name of execCommand().
+     * param: param for the command.  i.e., the 3rd param of execCommand().
+     * value: initial value of <input> or <textarea>.  must have a pair of
+     *        "[" and "]" for specifying selection range.
+     * expectedValue: expected value of <input> or <textarea> after calling
+     *                execCommand() with command and param.  must have a
+     *                pair of "[" and "]" for specifying selection range.
+     * expectedExecCommandResult: expected bool result of execCommand().
+     * beforeinputExpected: if "beforeinput" event shouldn't be fired, set
+     *                      false.  otherwise, expected inputType value.
+     * inputExpected: if "input" event shouldn't be fired, set false.
+     *                otherwise, expected inputType value.
+     */
+    {command: "bold", param: "bold",
+     value: "a[b]c", expectedValue: "a[b]c",
+     expectedExecCommandResult: false,
+     beforeinputExpected: false, inputExpected: false,
+    },
+    {command: "italic", param: null,
+     value: "a[b]c", expectedValue: "a[b]c",
+     expectedExecCommandResult: false,
+     beforeinputExpected: false, inputExpected: false,
+    },
+    {command: "underline", param: null,
+     value: "a[b]c", expectedValue: "a[b]c",
+     expectedExecCommandResult: false,
+     beforeinputExpected: false, inputExpected: false,
+    },
+    {command: "strikethrough", param: null,
+     value: "a[b]c", expectedValue: "a[b]c",
+     expectedExecCommandResult: false,
+     beforeinputExpected: false, inputExpected: false,
+    },
+    {command: "superscript", param: null,
+     value: "a[b]c", expectedValue: "a[b]c",
+     expectedExecCommandResult: false,
+     beforeinputExpected: false, inputExpected: false,
+    },
+    // Should return true for web apps implementing custom editor.
+    {command: "cut", param: null,
+     value: "ab[]c", expectedValue: "ab[]c",
+     expectedExecCommandResult: true,
+     beforeinputExpected: false, inputExpected: false,
+    },
+    {command: "cut", param: null,
+     value: "a[b]c", expectedValue: "a[]c",
+     expectedExecCommandResult: true,
+     beforeinputExpected: false, inputExpected: "deleteByCut",
+    },
+    // Should return true for web apps implementing custom editor.
+    {command: "copy", param: null,
+     value: "abc[]d", expectedValue: "abc[]d",
+     expectedExecCommandResult: true,
+     beforeinputExpected: false, inputExpected: false,
+    },
+    {command: "copy", param: null,
+     value: "a[bc]d", expectedValue: "a[bc]d",
+     expectedExecCommandResult: true,
+     beforeinputExpected: false, inputExpected: false,
+    },
+    {command: "paste", param: null,
+     value: "a[]c", expectedValue: "a[bc]c",
+     expectedExecCommandResult: true,
+     beforeinputExpected: false, inputExpected: "insertFromPaste",
+    },
+    {command: "delete", param: null,
+     value: "ab[]c", expectedValue: "a[]c",
+     expectedExecCommandResult: true,
+     beforeinputExpected: false, inputExpected: "deleteContentBackward",
+    },
+    {command: "delete", param: null,
+     value: "a[b]c", expectedValue: "a[]c",
+     expectedExecCommandResult: true,
+     beforeinputExpected: false, inputExpected: "deleteContentBackward",
+    },
+    {command: "forwarddelete", param: null,
+     value: "a[b]c", expectedValue: "a[]c",
+     expectedExecCommandResult: true,
+     beforeinputExpected: false, inputExpected: "deleteContentForward",
+    },
+    {command: "forwarddelete", param: null,
+     value: "a[]bc", expectedValue: "a[]c",
+     expectedExecCommandResult: true,
+     beforeinputExpected: false, inputExpected: "deleteContentForward",
+    },
+    {command: "selectall", param: null,
+     value: "a[b]c", expectedValue: "[abc]",
+     expectedExecCommandResult: true,
+     beforeinputExpected: false, inputExpected: false,
+    },
+    // Setting value should forget any transactions.
+    {command: "undo", param: null,
+     value: "[a]bc", expectedValue: "[a]bc",
+     expectedExecCommandResult: false,
+     beforeinputExpected: false, inputExpected: false,
+    },
+    {command: "undo", param: null,
+     value: "a[b]c", expectedValue: "a[b]c",
+     initFunc: () => {
+       document.execCommand("delete", false, null);
+     },
+     expectedExecCommandResult: true,
+     beforeinputExpected: false, inputExpected: "historyUndo",
+    },
+    // Setting value should forget any transactions.
+    {command: "redo", param: null,
+     value: "[a]bc", expectedValue: "[a]bc",
+     expectedExecCommandResult: false,
+     beforeinputExpected: false, inputExpected: false,
+    },
+    {command: "redo", param: null,
+     value: "a[b]c", expectedValue: "a[]c",
+     initFunc: () => {
+       document.execCommand("delete", false, null);
+       document.execCommand("undo", false, null);
+     },
+     expectedExecCommandResult: true,
+     beforeinputExpected: false, inputExpected: "historyRedo",
+    },
+    {command: "indent", param: null,
+     value: "a[b]c", expectedValue: "a[b]c",
+     expectedExecCommandResult: false,
+     beforeinputExpected: false, inputExpected: false,
+    },
+    {command: "outdent", param: null,
+     value: "a[b]c", expectedValue: "a[b]c",
+     expectedExecCommandResult: false,
+     beforeinputExpected: false, inputExpected: false,
+    },
+    {command: "backcolor", param: "#000000",
+     value: "a[b]c", expectedValue: "a[b]c",
+     expectedExecCommandResult: false,
+     beforeinputExpected: false, inputExpected: false,
+    },
+    {command: "forecolor", param: "#000000",
+     value: "a[b]c", expectedValue: "a[b]c",
+     expectedExecCommandResult: false,
+     beforeinputExpected: false, inputExpected: false,
+    },
+    {command: "hilitecolor", param: "#000000",
+     value: "a[b]c", expectedValue: "a[b]c",
+     expectedExecCommandResult: false,
+     beforeinputExpected: false, inputExpected: false,
+    },
+    {command: "fontname", param: "DummyFont",
+     value: "a[b]c", expectedValue: "a[b]c",
+     expectedExecCommandResult: false,
+     beforeinputExpected: false, inputExpected: false,
+    },
+    {command: "fontsize", param: "5",
+     value: "a[b]c", expectedValue: "a[b]c",
+     expectedExecCommandResult: false,
+     beforeinputExpected: false, inputExpected: false,
+    },
+    {command: "increasefontsize", param: null,
+     value: "a[b]c", expectedValue: "a[b]c",
+     expectedExecCommandResult: false,
+     beforeinputExpected: false, inputExpected: false,
+    },
+    {command: "decreasefontsize", param: null,
+     value: "a[b]c", expectedValue: "a[b]c",
+     expectedExecCommandResult: false,
+     beforeinputExpected: false, inputExpected: false,
+    },
+    {command: "inserthorizontalrule", param: null,
+     value: "a[b]c", expectedValue: "a[b]c",
+     expectedExecCommandResult: false,
+     beforeinputExpected: false, inputExpected: false,
+    },
+    {command: "createlink", param: "foo.html",
+     value: "a[b]c", expectedValue: "a[b]c",
+     expectedExecCommandResult: false,
+     beforeinputExpected: false, inputExpected: false,
+    },
+    {command: "insertimage", param: "no-image.png",
+     value: "a[b]c", expectedValue: "a[b]c",
+     expectedExecCommandResult: false,
+     beforeinputExpected: false, inputExpected: false,
+    },
+    {command: "inserthtml", param: "<b>inserted</b>",
+     value: "a[b]c", expectedValue: "ainserted[]c",
+     expectedExecCommandResult: true,
+     beforeinputExpected: false, inputExpected: "insertText",
+    },
+    {command: "inserttext", param: "**inserted**",
+     value: "a[b]c", expectedValue: "a**inserted**[]c",
+     expectedExecCommandResult: true,
+     beforeinputExpected: false, inputExpected: "insertText",
+    },
+    {command: "justifyleft", param: null,
+     value: "a[b]c", expectedValue: "a[b]c",
+     expectedExecCommandResult: false,
+     beforeinputExpected: false, inputExpected: false,
+    },
+    {command: "justifyright", param: null,
+     value: "a[b]c", expectedValue: "a[b]c",
+     expectedExecCommandResult: false,
+     beforeinputExpected: false, inputExpected: false,
+    },
+    {command: "justifycenter", param: null,
+     value: "a[b]c", expectedValue: "a[b]c",
+     expectedExecCommandResult: false,
+     beforeinputExpected: false, inputExpected: false,
+    },
+    {command: "justifyfull", param: null,
+     value: "a[b]c", expectedValue: "a[b]c",
+     expectedExecCommandResult: false,
+     beforeinputExpected: false, inputExpected: false,
+    },
+    {command: "removeformat", param: null,
+     value: "a[b]c", expectedValue: "a[b]c",
+     expectedExecCommandResult: false,
+     beforeinputExpected: false, inputExpected: false,
+    },
+    {command: "unlink", param: null,
+     value: "a[b]c", expectedValue: "a[b]c",
+     expectedExecCommandResult: false,
+     beforeinputExpected: false, inputExpected: false,
+    },
+    {command: "insertorderedlist", param: null,
+     value: "a[b]c", expectedValue: "a[b]c",
+     expectedExecCommandResult: false,
+     beforeinputExpected: false, inputExpected: false,
+    },
+    {command: "insertunorderedlist", param: null,
+     value: "a[b]c", expectedValue: "a[b]c",
+     expectedExecCommandResult: false,
+     beforeinputExpected: false, inputExpected: false,
+    },
+    {command: "insertparagraph", param: null,
+     value: "a[b]c", expectedValue: kIsTextArea ? "a\n[]c" : "a[b]c",
+     expectedExecCommandResult: true,
+     beforeinputExpected: false, inputExpected: "insertParagraph",
+    },
+    {command: "insertlinebreak", param: null,
+     value: "a[b]c", expectedValue: kIsTextArea ? "a\n[]c" : "a[b]c",
+     expectedExecCommandResult: true,
+     beforeinputExpected: false, inputExpected: "insertLineBreak",
+    },
+    {command: "formatblock", param: "div",
+     value: "a[b]c", expectedValue: "a[b]c",
+     expectedExecCommandResult: false,
+     beforeinputExpected: false, inputExpected: false,
+    },
+    {command: "heading", param: "h1",
+     value: "a[b]c", expectedValue: "a[b]c",
+     expectedExecCommandResult: false,
+     beforeinputExpected: false, inputExpected: false,
+    },
+  ];
+
+  for (const kTest of kTests) {
+    const kDescription =
+        `${aDescription}, execCommand("${kTest.command}", false, ${kTest.param}), ${kTest.value})`;
+    if (!document.queryCommandSupported(kTest.command)) {
+      continue;
+    }
+    let value = kTest.value.replace(/[\[\]]/g, "");
+    aTarget.value = value;
+    aTarget.focus();
+    aTarget.selectionStart = kTest.value.indexOf("[");
+    aTarget.selectionEnd = kTest.value.indexOf("]") - 1;
+
+    if (kTest.initFunc) {
+      kTest.initFunc();
+    }
+
+    let beforeinput = false;
+    function onBeforeinput(event) {
+      beforeinput = event.inputType;
+    }
+    window.addEventListener("beforeinput", onBeforeinput, {capture: true});
+    let input = false;
+    function onInput(event) {
+      input = event.inputType;
+    }
+    window.addEventListener("input", onInput, {capture: true});
+    let ret;
+    test(function () {
+      ret = document.execCommand(kTest.command, false, kTest.param);
+      assert_equals(ret, kTest.expectedExecCommandResult);
+    }, `${kDescription}: calling execCommand()`);
+    if (ret == kTest.expectedExecCommandResult) {
+      test(function () {
+        let value = aTarget.value.substring(0, aTarget.selectionStart) +
+                        "[" +
+                        aTarget.value.substring(aTarget.selectionStart, aTarget.selectionEnd) +
+                        "]" +
+                        aTarget.value.substring(aTarget.selectionEnd);
+        assert_equals(value, kTest.expectedValue);
+      }, `${kDescription}: checking value and selection after execCommand()`);
+      test(function () {
+        assert_equals(beforeinput, kTest.beforeinputExpected);
+      }, `${kDescription}: checking beforeinput event`);
+      test(function () {
+        assert_equals(input, kTest.inputExpected);
+      }, `${kDescription}: checking input event`);
+    }
+    window.removeEventListener("beforeinput", onBeforeinput, {capture: true});
+    window.removeEventListener("input", onInput, {capture: true});
+  }
+}
+
+window.addEventListener("load", runTests, {once: true});
+</script>
--- a/toolkit/components/passwordmgr/LoginAutoCompleteResult.jsm
+++ b/toolkit/components/passwordmgr/LoginAutoCompleteResult.jsm
@@ -1,34 +1,46 @@
 /* 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/. */
 
 /**
- * nsIAutoCompleteResult implementation for saved logins.
+ * nsIAutoCompleteResult and nsILoginAutoCompleteSearch implementations for saved logins.
  */
 
 "use strict";
 
-var EXPORTED_SYMBOLS = ["LoginAutoCompleteResult"];
+var EXPORTED_SYMBOLS = [
+  "LoginAutoComplete",
+  "LoginAutoCompleteResult",
+];
 
 const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
 const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
 
+ChromeUtils.defineModuleGetter(this, "BrowserUtils",
+                               "resource://gre/modules/BrowserUtils.jsm");
+ChromeUtils.defineModuleGetter(this, "InsecurePasswordUtils",
+                               "resource://gre/modules/InsecurePasswordUtils.jsm");
+ChromeUtils.defineModuleGetter(this, "LoginFormFactory",
+                               "resource://gre/modules/LoginFormFactory.jsm");
 ChromeUtils.defineModuleGetter(this, "LoginHelper",
                                "resource://gre/modules/LoginHelper.jsm");
+ChromeUtils.defineModuleGetter(this, "LoginManagerContent",
+                               "resource://gre/modules/LoginManagerContent.jsm");
 
 XPCOMUtils.defineLazyServiceGetter(this, "formFillController",
                                    "@mozilla.org/satchel/form-fill-controller;1",
                                    Ci.nsIFormFillController);
 
 XPCOMUtils.defineLazyGetter(this, "log", () => {
   return LoginHelper.createLogger("LoginAutoCompleteResult");
 });
 
+
 // nsIAutoCompleteResult implementation
 function LoginAutoCompleteResult(aSearchString, matchingLogins, {isSecure, messageManager, isPasswordField, hostname}) {
   function loginSort(a, b) {
     let userA = a.username.toLowerCase();
     let userB = b.username.toLowerCase();
 
     if (userA < userB) {
       return -1;
@@ -231,8 +243,113 @@ LoginAutoCompleteResult.prototype = {
         this._messageManager.sendAsyncMessage("PasswordManager:removeLogin",
                                               { login: vanilla });
       } else {
         Services.logins.removeLogin(removedLogin);
       }
     }
   },
 };
+
+function LoginAutoComplete() {}
+LoginAutoComplete.prototype = {
+  classID: Components.ID("{2bdac17c-53f1-4896-a521-682ccdeef3a8}"),
+  QueryInterface: ChromeUtils.generateQI([Ci.nsILoginAutoCompleteSearch]),
+
+  _autoCompleteLookupPromise: null,
+
+  /**
+   * Yuck. This is called directly by satchel:
+   * nsFormFillController::StartSearch()
+   * [toolkit/components/satchel/nsFormFillController.cpp]
+   *
+   * We really ought to have a simple way for code to register an
+   * auto-complete provider, and not have satchel calling pwmgr directly.
+   *
+   * @param {string} aSearchString The value typed in the field.
+   * @param {nsIAutoCompleteResult} aPreviousResult
+   * @param {HTMLInputElement} aElement
+   * @param {nsIFormAutoCompleteObserver} aCallback
+   */
+  startSearch(aSearchString, aPreviousResult, aElement, aCallback) {
+    let {isNullPrincipal} = aElement.nodePrincipal;
+    // Show the insecure login warning in the passwords field on null principal documents.
+    let isSecure = !isNullPrincipal;
+    // Avoid loading InsecurePasswordUtils.jsm in a sandboxed document (e.g. an ad. frame) if we
+    // already know it has a null principal and will therefore get the insecure autocomplete
+    // treatment.
+    // InsecurePasswordUtils doesn't handle the null principal case as not secure because we don't
+    // want the same treatment:
+    // * The web console warnings will be confusing (as they're primarily about http:) and not very
+    //   useful if the developer intentionally sandboxed the document.
+    // * The site identity insecure field warning would require LoginManagerContent being loaded and
+    //   listening to some of the DOM events we're ignoring in null principal documents. For memory
+    //   reasons it's better to not load LMC at all for these sandboxed frames. Also, if the top-
+    //   document is sandboxing a document, it probably doesn't want that sandboxed document to be
+    //   able to affect the identity icon in the address bar by adding a password field.
+    if (isSecure) {
+      let form = LoginFormFactory.createFromField(aElement);
+      isSecure = InsecurePasswordUtils.isFormSecure(form);
+    }
+    let isPasswordField = aElement.type == "password";
+    let hostname = aElement.ownerDocument.documentURIObject.host;
+
+    let completeSearch = (autoCompleteLookupPromise, { logins, messageManager }) => {
+      // If the search was canceled before we got our
+      // results, don't bother reporting them.
+      if (this._autoCompleteLookupPromise !== autoCompleteLookupPromise) {
+        return;
+      }
+
+      this._autoCompleteLookupPromise = null;
+      let results = new LoginAutoCompleteResult(aSearchString, logins, {
+        messageManager,
+        isSecure,
+        isPasswordField,
+        hostname,
+      });
+      aCallback.onSearchCompletion(results);
+    };
+
+    if (isNullPrincipal) {
+      // Don't search login storage when the field has a null principal as we don't want to fill
+      // logins for the `location` in this case.
+      let acLookupPromise = this._autoCompleteLookupPromise = Promise.resolve({ logins: [] });
+      acLookupPromise.then(completeSearch.bind(this, acLookupPromise));
+      return;
+    }
+
+    if (isPasswordField && aSearchString) {
+      // Return empty result on password fields with password already filled.
+      let acLookupPromise = this._autoCompleteLookupPromise = Promise.resolve({ logins: [] });
+      acLookupPromise.then(completeSearch.bind(this, acLookupPromise));
+      return;
+    }
+
+    if (!LoginHelper.enabled) {
+      let acLookupPromise = this._autoCompleteLookupPromise = Promise.resolve({ logins: [] });
+      acLookupPromise.then(completeSearch.bind(this, acLookupPromise));
+      return;
+    }
+
+    log.debug("AutoCompleteSearch invoked. Search is:", aSearchString);
+
+    let previousResult;
+    if (aPreviousResult) {
+      previousResult = {
+        searchString: aPreviousResult.searchString,
+        logins: aPreviousResult.wrappedJSObject.logins,
+      };
+    } else {
+      previousResult = null;
+    }
+
+    let rect = BrowserUtils.getElementBoundingScreenRect(aElement);
+    let acLookupPromise = this._autoCompleteLookupPromise =
+      LoginManagerContent._autoCompleteSearchAsync(aSearchString, previousResult,
+                                                   aElement, rect);
+    acLookupPromise.then(completeSearch.bind(this, acLookupPromise)).catch(log.error);
+  },
+
+  stopSearch() {
+    this._autoCompleteLookupPromise = null;
+  },
+};
--- a/toolkit/components/passwordmgr/LoginManager.jsm
+++ b/toolkit/components/passwordmgr/LoginManager.jsm
@@ -4,36 +4,37 @@
 
 "use strict";
 
 const PERMISSION_SAVE_LOGINS = "login-saving";
 
 const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
 const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
 
-ChromeUtils.defineModuleGetter(this, "BrowserUtils",
-                               "resource://gre/modules/BrowserUtils.jsm");
 ChromeUtils.defineModuleGetter(this, "LoginHelper",
                                "resource://gre/modules/LoginHelper.jsm");
 ChromeUtils.defineModuleGetter(this, "LoginFormFactory",
                                "resource://gre/modules/LoginFormFactory.jsm");
 ChromeUtils.defineModuleGetter(this, "LoginManagerContent",
                                "resource://gre/modules/LoginManagerContent.jsm");
-ChromeUtils.defineModuleGetter(this, "LoginAutoCompleteResult",
-                               "resource://gre/modules/LoginAutoCompleteResult.jsm");
 ChromeUtils.defineModuleGetter(this, "InsecurePasswordUtils",
                                "resource://gre/modules/InsecurePasswordUtils.jsm");
 
 XPCOMUtils.defineLazyGetter(this, "log", () => {
   let logger = LoginHelper.createLogger("nsLoginManager");
   return logger;
 });
 
 const MS_PER_DAY = 24 * 60 * 60 * 1000;
 
+if (Services.appinfo.processType !== Services.appinfo.PROCESS_TYPE_DEFAULT) {
+  throw new Error("LoginManager.jsm should only run in the parent process");
+}
+
+
 function LoginManager() {
   this.init();
 }
 
 LoginManager.prototype = {
 
   classID: Components.ID("{cb9e0de8-3598-4ed7-857b-827f011ad5d8}"),
   QueryInterface: ChromeUtils.generateQI([Ci.nsILoginManager,
@@ -51,43 +52,34 @@ LoginManager.prototype = {
     }
 
     throw new Components.Exception("Interface not available", Cr.NS_ERROR_NO_INTERFACE);
   },
 
 
   /* ---------- private members ---------- */
 
-
-
   _storage: null, // Storage component which contains the saved logins
 
 
   /**
    * Initialize the Login Manager. Automatically called when service
    * is created.
    *
-   * Note: Service created in /browser/base/content/browser.js,
-   *       delayedStartup()
+   * Note: Service created in BrowserGlue#_scheduleStartupIdleTasks()
    */
   init() {
     // Cache references to current |this| in utility objects
     this._observer._pwmgr            = this;
-    this._autoCompleteLookupPromise = null;
-
-    // Form submit observer checks forms for new logins and pw changes.
-    Services.obs.addObserver(this._observer, "xpcom-shutdown");
 
-    if (Services.appinfo.processType ===
-        Services.appinfo.PROCESS_TYPE_DEFAULT) {
-      Services.obs.addObserver(this._observer, "passwordmgr-storage-replace");
+    Services.obs.addObserver(this._observer, "xpcom-shutdown");
+    Services.obs.addObserver(this._observer, "passwordmgr-storage-replace");
 
-      // Initialize storage so that asynchronous data loading can start.
-      this._initStorage();
-    }
+    // Initialize storage so that asynchronous data loading can start.
+    this._initStorage();
 
     Services.obs.addObserver(this._observer, "gather-telemetry");
   },
 
   _initStorage() {
     this._storage = Cc["@mozilla.org/login-manager/storage/default;1"]
                     .createInstance(Ci.nsILoginManagerStorage);
     this.initializationPromise = this._storage.initialize();
@@ -459,106 +451,11 @@ LoginManager.prototype = {
       Services.perms.remove(uri, PERMISSION_SAVE_LOGINS);
     } else {
       Services.perms.add(uri, PERMISSION_SAVE_LOGINS, Services.perms.DENY_ACTION);
     }
 
     log.debug("Login saving for", origin, "now enabled?", enabled);
     LoginHelper.notifyStorageChanged(enabled ? "hostSavingEnabled" : "hostSavingDisabled", origin);
   },
-
-  /**
-   * Yuck. This is called directly by satchel:
-   * nsFormFillController::StartSearch()
-   * [toolkit/components/satchel/nsFormFillController.cpp]
-   *
-   * We really ought to have a simple way for code to register an
-   * auto-complete provider, and not have satchel calling pwmgr directly.
-   */
-  autoCompleteSearchAsync(aSearchString, aPreviousResult,
-                          aElement, aCallback) {
-    // aPreviousResult is an nsIAutoCompleteResult, aElement is
-    // HTMLInputElement
-
-    let {isNullPrincipal} = aElement.nodePrincipal;
-    // Show the insecure login warning in the passwords field on null principal documents.
-    let isSecure = !isNullPrincipal;
-    // Avoid loading InsecurePasswordUtils.jsm in a sandboxed document (e.g. an ad. frame) if we
-    // already know it has a null principal and will therefore get the insecure autocomplete
-    // treatment.
-    // InsecurePasswordUtils doesn't handle the null principal case as not secure because we don't
-    // want the same treatment:
-    // * The web console warnings will be confusing (as they're primarily about http:) and not very
-    //   useful if the developer intentionally sandboxed the document.
-    // * The site identity insecure field warning would require LoginManagerContent being loaded and
-    //   listening to some of the DOM events we're ignoring in null principal documents. For memory
-    //   reasons it's better to not load LMC at all for these sandboxed frames. Also, if the top-
-    //   document is sandboxing a document, it probably doesn't want that sandboxed document to be
-    //   able to affect the identity icon in the address bar by adding a password field.
-    if (isSecure) {
-      let form = LoginFormFactory.createFromField(aElement);
-      isSecure = InsecurePasswordUtils.isFormSecure(form);
-    }
-    let isPasswordField = aElement.type == "password";
-    let hostname = aElement.ownerDocument.documentURIObject.host;
-
-    let completeSearch = (autoCompleteLookupPromise, { logins, messageManager }) => {
-      // If the search was canceled before we got our
-      // results, don't bother reporting them.
-      if (this._autoCompleteLookupPromise !== autoCompleteLookupPromise) {
-        return;
-      }
-
-      this._autoCompleteLookupPromise = null;
-      let results = new LoginAutoCompleteResult(aSearchString, logins, {
-        messageManager,
-        isSecure,
-        isPasswordField,
-        hostname,
-      });
-      aCallback.onSearchCompletion(results);
-    };
-
-    if (isNullPrincipal) {
-      // Don't search login storage when the field has a null principal as we don't want to fill
-      // logins for the `location` in this case.
-      let acLookupPromise = this._autoCompleteLookupPromise = Promise.resolve({ logins: [] });
-      acLookupPromise.then(completeSearch.bind(this, acLookupPromise));
-      return;
-    }
-
-    if (isPasswordField && aSearchString) {
-      // Return empty result on password fields with password already filled.
-      let acLookupPromise = this._autoCompleteLookupPromise = Promise.resolve({ logins: [] });
-      acLookupPromise.then(completeSearch.bind(this, acLookupPromise));
-      return;
-    }
-
-    if (!LoginHelper.enabled) {
-      let acLookupPromise = this._autoCompleteLookupPromise = Promise.resolve({ logins: [] });
-      acLookupPromise.then(completeSearch.bind(this, acLookupPromise));
-      return;
-    }
-
-    log.debug("AutoCompleteSearch invoked. Search is:", aSearchString);
-
-    let previousResult;
-    if (aPreviousResult) {
-      previousResult = { searchString: aPreviousResult.searchString,
-                         logins: aPreviousResult.wrappedJSObject.logins };
-    } else {
-      previousResult = null;
-    }
-
-    let rect = BrowserUtils.getElementBoundingScreenRect(aElement);
-    let acLookupPromise = this._autoCompleteLookupPromise =
-      LoginManagerContent._autoCompleteSearchAsync(aSearchString, previousResult,
-                                                   aElement, rect);
-    acLookupPromise.then(completeSearch.bind(this, acLookupPromise))
-                             .catch(Cu.reportError);
-  },
-
-  stopSearch() {
-    this._autoCompleteLookupPromise = null;
-  },
 }; // end of LoginManager implementation
 
 var EXPORTED_SYMBOLS = ["LoginManager"];
--- a/toolkit/components/passwordmgr/components.conf
+++ b/toolkit/components/passwordmgr/components.conf
@@ -13,16 +13,22 @@ Classes = [
     },
     {
         'cid': '{749e62f4-60ae-4569-a8a2-de78b649660e}',
         'contract_ids': ['@mozilla.org/passwordmanager/authpromptfactory;1'],
         'jsm': 'resource://gre/modules/LoginManagerPrompter.jsm',
         'constructor': 'LoginManagerPromptFactory',
     },
     {
+        'cid': '{2bdac17c-53f1-4896-a521-682ccdeef3a8}',
+        'contract_ids': ['@mozilla.org/login-manager/autocompletesearch;1'],
+        'jsm': 'resource://gre/modules/LoginAutoCompleteResult.jsm',
+        'constructor': 'LoginAutoComplete',
+    },
+    {
         'cid': '{8aa66d77-1bbb-45a6-991e-b8f47751c291}',
         'contract_ids': ['@mozilla.org/login-manager/prompter;1'],
         'jsm': 'resource://gre/modules/LoginManagerPrompter.jsm',
         'constructor': 'LoginManagerPrompter',
     },
     {
         'cid': '{0f2f347c-1e4f-40cc-8efd-792dea70a85e}',
         'contract_ids': ['@mozilla.org/login-manager/loginInfo;1'],
--- a/toolkit/components/passwordmgr/moz.build
+++ b/toolkit/components/passwordmgr/moz.build
@@ -13,16 +13,17 @@ XPCSHELL_TESTS_MANIFESTS += ['test/unit/
 
 TESTING_JS_MODULES += [
     # Make this file available from the "resource:" URI of the test environment.
     'test/browser/form_basic.html',
     'test/LoginTestUtils.jsm',
 ]
 
 XPIDL_SOURCES += [
+    'nsILoginAutoCompleteSearch.idl',
     'nsILoginInfo.idl',
     'nsILoginManager.idl',
     'nsILoginManagerCrypto.idl',
     'nsILoginManagerPrompter.idl',
     'nsILoginManagerStorage.idl',
     'nsILoginMetaInfo.idl',
 ]
 
copy from toolkit/components/passwordmgr/nsILoginManager.idl
copy to toolkit/components/passwordmgr/nsILoginAutoCompleteSearch.idl
--- a/toolkit/components/passwordmgr/nsILoginManager.idl
+++ b/toolkit/components/passwordmgr/nsILoginAutoCompleteSearch.idl
@@ -1,276 +1,31 @@
 /* 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"
 
-interface nsIURI;
-interface nsILoginInfo;
 interface nsIAutoCompleteResult;
 interface nsIFormAutoCompleteObserver;
-interface nsIPropertyBag;
 
 webidl HTMLInputElement;
 
-[scriptable, uuid(38c7f6af-7df9-49c7-b558-2776b24e6cc1)]
-interface nsILoginManager : nsISupports {
-  /**
-   * This promise is resolved when initialization is complete, and is rejected
-   * in case initialization failed.  This includes the initial loading of the
-   * login data as well as any migration from previous versions.
-   *
-   * Calling any method of nsILoginManager before this promise is resolved
-   * might trigger the synchronous initialization fallback.
-   */
-  readonly attribute jsval initializationPromise;
-
-
-  /**
-   * Store a new login in the login manager.
-   *
-   * @param aLogin
-   *        The login to be added.
-   * @return a clone of the login info with the guid set (even if it was not provided)
-   *
-   * Default values for the login's nsILoginMetaInfo properties will be
-   * created. However, if the caller specifies non-default values, they will
-   * be used instead.
-   */
-  nsILoginInfo addLogin(in nsILoginInfo aLogin);
-
-
-  /**
-   * Like addLogin, but asynchronous and for many logins.
-   *
-   * @param aLogins
-   *        A JS Array of nsILoginInfos to add.
-   * @return A promise which resolves with a JS Array of cloned logins with
-   *         the guids set.
-   *
-   * Default values for each login's nsILoginMetaInfo properties will be
-   * created. However, if the caller specifies non-default values, they will
-   * be used instead.
-   */
-  jsval addLogins(in jsval aLogins);
-
-  /**
-   * Remove a login from the login manager.
-   *
-   * @param aLogin
-   *        The login to be removed.
-   *
-   * The specified login must exactly match a stored login. However, the
-   * values of any nsILoginMetaInfo properties are ignored.
-   */
-  void removeLogin(in nsILoginInfo aLogin);
-
-
-  /**
-   * Modify an existing login in the login manager.
-   *
-   * @param oldLogin
-   *        The login to be modified.
-   * @param newLoginData
-   *        The new login values (either a nsILoginInfo or nsIProperyBag)
-   *
-   * If newLoginData is a nsILoginInfo, all of the old login's nsILoginInfo
-   * properties are changed to the values from newLoginData (but the old
-   * login's nsILoginMetaInfo properties are unmodified).
-   *
-   * If newLoginData is a nsIPropertyBag, only the specified properties
-   * will be changed. The nsILoginMetaInfo properties of oldLogin can be
-   * changed in this manner.
-   *
-   * If the propertybag contains an item named "timesUsedIncrement", the
-   * login's timesUsed property will be incremented by the item's value.
-   */
-  void modifyLogin(in nsILoginInfo oldLogin, in nsISupports newLoginData);
-
-
-  /**
-   * Remove all logins known to login manager.
-   *
-   * The browser sanitization feature allows the user to clear any stored
-   * passwords. This interface allows that to be done without getting each
-   * login first (which might require knowing the master password).
-   *
-   */
-  void removeAllLogins();
-
-
+[scriptable, uuid(2bdac17c-53f1-4896-a521-682ccdeef3a8)]
+interface nsILoginAutoCompleteSearch : nsISupports {
   /**
-   * Fetch all logins in the login manager. An array is always returned;
-   * if there are no logins the array is empty.
-   *
-   * @param count
-   *        The number of elements in the array. JS callers can simply use
-   *        the array's .length property and omit this param.
-   * @param logins
-   *        An array of nsILoginInfo objects.
-   *
-   * NOTE: This can be called from JS as:
-   *       var logins = pwmgr.getAllLogins();
-   *       (|logins| is an array).
-   */
-  void getAllLogins([optional] out unsigned long count,
-                    [retval, array, size_is(count)] out nsILoginInfo logins);
-
-
-  /**
-   * Obtain a list of all hosts for which password saving is disabled.
-   *
-   * @param count
-   *        The number of elements in the array. JS callers can simply use
-   *        the array's .length property and omit this param.
-   * @param hostnames
-   *        An array of hostname strings, in origin URL format without a
-   *        pathname. For example: "https://www.site.com".
-   *
-   * NOTE: This can be called from JS as:
-   *       var logins = pwmgr.getDisabledAllLogins();
-   */
-  void getAllDisabledHosts([optional] out unsigned long count,
-                    [retval, array, size_is(count)] out wstring hostnames);
-
-
-  /**
-   * Check to see if saving logins has been disabled for a host.
-   *
-   * @param aHost
-   *        The hostname to check. This argument should be in the origin
-   *        URL format, without a pathname. For example: "http://foo.com".
-   */
-  boolean getLoginSavingEnabled(in AString aHost);
-
-
-  /**
-   * Disable (or enable) storing logins for the specified host. When
-   * disabled, the login manager will not prompt to store logins for
-   * that host. Existing logins are not affected.
-   *
-   * @param aHost
-   *        The hostname to set. This argument should be in the origin
-   *        URL format, without a pathname. For example: "http://foo.com".
-   * @param isEnabled
-   *        Specify if saving logins should be enabled (true) or
-   *        disabled (false)
-   */
-  void setLoginSavingEnabled(in AString aHost, in boolean isEnabled);
-
-
-  /**
-   * Search for logins matching the specified criteria. Called when looking
-   * for logins that might be applicable to a form or authentication request.
-   *
-   * @param count
-   *        The number of elements in the array. JS callers can simply use
-   *        the array's .length property, and supply an dummy object for
-   *        this out param. For example: |findLogins({}, hostname, ...)|
-   * @param aHostname
-   *        The hostname to restrict searches to, in URL format. For
-   *        example: "http://www.site.com".
-   *        To find logins for a given nsIURI, you would typically pass in
-   *        its prePath.
-   * @param aActionURL
-   *        For form logins, this argument should be the URL to which the
-   *        form will be submitted. For protocol logins, specify null.
-   *        An empty string ("") will match any value (except null).
-   * @param aHttpRealm
-   *        For protocol logins, this argument should be the HTTP Realm
-   *        for which the login applies. This is obtained from the
-   *        WWW-Authenticate header. See RFC2617. For form logins,
-   *        specify null.
-   *        An empty string ("") will match any value (except null).
-   * @param logins
-   *        An array of nsILoginInfo objects.
-   *
-   * NOTE: This can be called from JS as:
-   *       var logins = pwmgr.findLogins({}, hostname, ...);
-   *
-   */
-  void findLogins(out unsigned long count, in AString aHostname,
-                  in AString aActionURL,   in AString aHttpRealm,
-                  [retval, array, size_is(count)] out nsILoginInfo logins);
-
-
-  /**
-   * Search for logins matching the specified criteria, as with
-   * findLogins(). This interface only returns the number of matching
-   * logins (and not the logins themselves), which allows a caller to
-   * check for logins without causing the user to be prompted for a master
-   * password to decrypt the logins.
-   *
-   * @param aHostname
-   *        The hostname to restrict searches to. Specify an empty string
-   *        to match all hosts. A null value will not match any logins, and
-   *        will thus always return a count of 0.
-   * @param aActionURL
-   *        The URL to which a form login will be submitted. To match any
-   *        form login, specify an empty string. To not match any form
-   *        login, specify null.
-   * @param aHttpRealm
-   *        The HTTP Realm for which the login applies. To match logins for
-   *        any realm, specify an empty string. To not match logins for any
-   *        realm, specify null.
-   */
-  unsigned long countLogins(in AString aHostname, in AString aActionURL,
-                            in AString aHttpRealm);
-
-
-  /**
-   * Generate results for a userfield autocomplete menu.
+   * Generate results for a login field autocomplete menu.
    *
    * NOTE: This interface is provided for use only by the FormFillController,
    *       which calls it directly. This isn't really ideal, it should
    *       probably be callback registered through the FFC.
+   * NOTE: This API is different than nsIAutoCompleteSearch.
    */
-  void autoCompleteSearchAsync(in AString aSearchString,
-                               in nsIAutoCompleteResult aPreviousResult,
-                               in HTMLInputElement aElement,
-                               in nsIFormAutoCompleteObserver aListener);
-
-  /**
-   * Stop a previously-started async search.
-   */
-  void stopSearch();
+  void startSearch(in AString aSearchString,
+                   in nsIAutoCompleteResult aPreviousResult,
+                   in HTMLInputElement aElement,
+                   in nsIFormAutoCompleteObserver aListener);
 
   /**
-   * Search for logins in the login manager. An array is always returned;
-   * if there are no logins the array is empty.
-   *
-   * @param count
-   *        The number of elements in the array. JS callers can simply use
-   *        the array's .length property, and supply an dummy object for
-   *        this out param. For example: |searchLogins({}, matchData)|
-   * @param matchData
-   *        The data used to search. This does not follow the same
-   *        requirements as findLogins for those fields. Wildcard matches are
-   *        simply not specified.
-   * @param logins
-   *        An array of nsILoginInfo objects.
-   *
-   * NOTE: This can be called from JS as:
-   *       var logins = pwmgr.searchLogins({}, matchData);
-   *       (|logins| is an array).
+   * Stop a previously-started search.
    */
-  void searchLogins(out unsigned long count, in nsIPropertyBag matchData,
-                    [retval, array, size_is(count)] out nsILoginInfo logins);
-
- /**
-  * True when a master password prompt is being displayed.
-  */
-  readonly attribute boolean uiBusy;
-
- /**
-  * True when the master password has already been entered, and so a caller
-  * can ask for decrypted logins without triggering a prompt.
-  */
-  readonly attribute boolean isLoggedIn;
+  void stopSearch();
 };
-
-%{C++
-
-#define NS_LOGINMANAGER_CONTRACTID "@mozilla.org/login-manager;1"
-
-%}
--- a/toolkit/components/passwordmgr/nsILoginManager.idl
+++ b/toolkit/components/passwordmgr/nsILoginManager.idl
@@ -1,23 +1,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/. */
 
-
 #include "nsISupports.idl"
 
-interface nsIURI;
 interface nsILoginInfo;
-interface nsIAutoCompleteResult;
-interface nsIFormAutoCompleteObserver;
 interface nsIPropertyBag;
 
-webidl HTMLInputElement;
-
 [scriptable, uuid(38c7f6af-7df9-49c7-b558-2776b24e6cc1)]
 interface nsILoginManager : nsISupports {
   /**
    * This promise is resolved when initialization is complete, and is rejected
    * in case initialization failed.  This includes the initial loading of the
    * login data as well as any migration from previous versions.
    *
    * Calling any method of nsILoginManager before this promise is resolved
@@ -212,34 +206,16 @@ interface nsILoginManager : nsISupports 
    * @param aHttpRealm
    *        The HTTP Realm for which the login applies. To match logins for
    *        any realm, specify an empty string. To not match logins for any
    *        realm, specify null.
    */
   unsigned long countLogins(in AString aHostname, in AString aActionURL,
                             in AString aHttpRealm);
 
-
-  /**
-   * Generate results for a userfield autocomplete menu.
-   *
-   * NOTE: This interface is provided for use only by the FormFillController,
-   *       which calls it directly. This isn't really ideal, it should
-   *       probably be callback registered through the FFC.
-   */
-  void autoCompleteSearchAsync(in AString aSearchString,
-                               in nsIAutoCompleteResult aPreviousResult,
-                               in HTMLInputElement aElement,
-                               in nsIFormAutoCompleteObserver aListener);
-
-  /**
-   * Stop a previously-started async search.
-   */
-  void stopSearch();
-
   /**
    * Search for logins in the login manager. An array is always returned;
    * if there are no logins the array is empty.
    *
    * @param count
    *        The number of elements in the array. JS callers can simply use
    *        the array's .length property, and supply an dummy object for
    *        this out param. For example: |searchLogins({}, matchData)|
--- a/toolkit/components/satchel/AutoCompletePopup.jsm
+++ b/toolkit/components/satchel/AutoCompletePopup.jsm
@@ -145,20 +145,16 @@ this.AutoCompletePopup = {
         this.weakBrowser = null;
         evt.target.removeEventListener("popuphidden", this);
         evt.target.removeEventListener("popupshowing", this);
         break;
       }
     }
   },
 
-  // Along with being called internally by the receiveMessage handler,
-  // this function is also called directly by the login manager, which
-  // uses a single message to fill in the autocomplete results. See
-  // "PasswordManager:autoCompleteLogins".
   showPopupWithResults({ browser, rect, dir, results }) {
     if (!results.length || this.openedPopup) {
       // We shouldn't ever be showing an empty popup, and if we
       // already have a popup open, the old one needs to close before
       // we consider opening a new one.
       return;
     }
 
--- a/toolkit/components/satchel/nsFormFillController.cpp
+++ b/toolkit/components/satchel/nsFormFillController.cpp
@@ -28,17 +28,17 @@
 #include "nsIInterfaceRequestor.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsIDocShellTreeItem.h"
 #include "nsPIDOMWindow.h"
 #include "nsIWebNavigation.h"
 #include "nsIContentViewer.h"
 #include "nsIContent.h"
 #include "nsRect.h"
-#include "nsILoginManager.h"
+#include "nsILoginAutoCompleteSearch.h"
 #include "nsToolkitCompsCID.h"
 #include "nsEmbedCID.h"
 #include "nsContentUtils.h"
 #include "nsGenericHTMLElement.h"
 #include "nsILoadContext.h"
 #include "nsIFrame.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsFocusManager.h"
@@ -60,17 +60,17 @@ static nsIFormAutoComplete* GetFormAutoC
     if (NS_SUCCEEDED(rv)) {
       ClearOnShutdown(&sInstance);
       sInitialized = true;
     }
   }
   return sInstance;
 }
 
-NS_IMPL_CYCLE_COLLECTION(nsFormFillController, mController, mLoginManager,
+NS_IMPL_CYCLE_COLLECTION(nsFormFillController, mController, mLoginManagerAC,
                          mLoginReputationService, mFocusedPopup, mDocShells,
                          mPopups, mLastListener, mLastFormAutoComplete)
 
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsFormFillController)
   NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIFormFillController)
   NS_INTERFACE_MAP_ENTRY(nsIFormFillController)
   NS_INTERFACE_MAP_ENTRY(nsIAutoCompleteInput)
   NS_INTERFACE_MAP_ENTRY(nsIAutoCompleteSearch)
@@ -293,18 +293,18 @@ nsFormFillController::MarkAsLoginManager
     nsCOMPtr<nsIContent> focusedContent = fm->GetFocusedElement();
     if (focusedContent == aInput) {
       if (!mFocusedInput) {
         MaybeStartControllingInput(aInput);
       }
     }
   }
 
-  if (!mLoginManager) {
-    mLoginManager = do_GetService("@mozilla.org/login-manager;1");
+  if (!mLoginManagerAC) {
+    mLoginManagerAC = do_GetService("@mozilla.org/login-manager/autocompletesearch;1");
   }
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsFormFillController::MarkAsAutofillField(HTMLInputElement* aInput) {
   /*
@@ -702,29 +702,28 @@ nsFormFillController::StartSearch(const 
   if (mFocusedInput &&
       (mPwmgrInputs.Get(mFocusedInput) ||
        mFocusedInput->ControlType() == NS_FORM_INPUT_PASSWORD)) {
     MOZ_LOG(sLogger, LogLevel::Debug, ("StartSearch: login field"));
 
     // Handle the case where a password field is focused but
     // MarkAsLoginManagerField wasn't called because password manager is
     // disabled.
-    if (!mLoginManager) {
-      mLoginManager = do_GetService("@mozilla.org/login-manager;1");
+    if (!mLoginManagerAC) {
+      mLoginManagerAC = do_GetService("@mozilla.org/login-manager/autocompletesearch;1");
     }
 
-    if (NS_WARN_IF(!mLoginManager)) {
+    if (NS_WARN_IF(!mLoginManagerAC)) {
       return NS_ERROR_FAILURE;
     }
 
     // XXX aPreviousResult shouldn't ever be a historyResult type, since we're
     // not letting satchel manage the field?
     mLastListener = aListener;
-    rv = mLoginManager->AutoCompleteSearchAsync(aSearchString, aPreviousResult,
-                                                mFocusedInput, this);
+    rv = mLoginManagerAC->StartSearch(aSearchString, aPreviousResult, mFocusedInput, this);
     NS_ENSURE_SUCCESS(rv, rv);
   } else {
     MOZ_LOG(sLogger, LogLevel::Debug, ("StartSearch: non-login field"));
     mLastListener = aListener;
 
     nsCOMPtr<nsIAutoCompleteResult> datalistResult;
     if (mFocusedInput) {
       rv = PerformInputListAutoComplete(aSearchString,
@@ -795,18 +794,18 @@ void nsFormFillController::RevalidateDat
 
 NS_IMETHODIMP
 nsFormFillController::StopSearch() {
   // Make sure to stop and clear this, otherwise the controller will prevent
   // mLastFormAutoComplete from being deleted.
   if (mLastFormAutoComplete) {
     mLastFormAutoComplete->StopAutoCompleteSearch();
     mLastFormAutoComplete = nullptr;
-  } else if (mLoginManager) {
-    mLoginManager->StopSearch();
+  } else if (mLoginManagerAC) {
+    mLoginManagerAC->StopSearch();
   }
   return NS_OK;
 }
 
 nsresult nsFormFillController::StartQueryLoginReputation(
     HTMLInputElement* aInput) {
   return NS_OK;
 }
--- a/toolkit/components/satchel/nsFormFillController.h
+++ b/toolkit/components/satchel/nsFormFillController.h
@@ -11,17 +11,17 @@
 #include "nsIAutoCompleteSearch.h"
 #include "nsIAutoCompleteController.h"
 #include "nsIAutoCompletePopup.h"
 #include "nsIFormAutoComplete.h"
 #include "nsIDOMEventListener.h"
 #include "nsCOMPtr.h"
 #include "nsDataHashtable.h"
 #include "nsIDocShell.h"
-#include "nsILoginManager.h"
+#include "nsILoginAutoCompleteSearch.h"
 #include "nsIMutationObserver.h"
 #include "nsTArray.h"
 #include "nsCycleCollectionParticipant.h"
 #include "nsILoginReputation.h"
 
 // X.h defines KeyPress
 #ifdef KeyPress
 #  undef KeyPress
@@ -105,17 +105,17 @@ class nsFormFillController final : publi
 
   bool IsTextControl(nsINode* aNode);
 
   nsresult StartQueryLoginReputation(mozilla::dom::HTMLInputElement* aInput);
 
   // members //////////////////////////////////////////
 
   nsCOMPtr<nsIAutoCompleteController> mController;
-  nsCOMPtr<nsILoginManager> mLoginManager;
+  nsCOMPtr<nsILoginAutoCompleteSearch> mLoginManagerAC;
   nsCOMPtr<nsILoginReputationService> mLoginReputationService;
   mozilla::dom::HTMLInputElement* mFocusedInput;
 
   // mListNode is a <datalist> element which, is set, has the form fill
   // controller as a mutation observer for it.
   nsINode* mListNode;
   nsCOMPtr<nsIAutoCompletePopup> mFocusedPopup;
 
--- a/tools/tryselect/docs/index.rst
+++ b/tools/tryselect/docs/index.rst
@@ -49,16 +49,17 @@ You can choose to use a different defaul
 
 .. toctree::
   :caption: Table of Contents
   :maxdepth: 2
 
   configuration
   selectors/index
   presets
+  tasks
 
 
 .. rubric:: Indices and tables
 
 * :ref:`genindex`
 * :ref:`modindex`
 * :ref:`search`
 
--- a/tools/tryselect/docs/selectors/fuzzy.rst
+++ b/tools/tryselect/docs/selectors/fuzzy.rst
@@ -29,17 +29,17 @@ Notice you can type a query, select some
 notice they get listed on the right. This is the preview pane, it is a view of what will get
 scheduled when you're done. When you are satisfied with your selection, press ``Enter`` and all the
 tasks in the preview pane will be pushed to try. If you changed your mind you can press ``Esc`` or
 ``Ctrl-C`` to exit the interface without pushing anything to try.
 
 Unlike the ``syntax`` selector, the ``fuzzy`` selector doesn't use the commit message to pass
 information up to taskcluster. Instead, it uses a file that lives at the root of the repository
 called ``try_task_config.json``. You can read more information in the :doc:`taskcluster docs
-<taskcluster/try>`.
+</taskcluster/taskcluster/try>`.
 
 Extended Search
 ---------------
 
 When typing in search terms, you can separate terms by spaces. These terms will be joined by the AND
 operator. For example the query:
 
 .. code-block:: text
new file mode 100644
--- /dev/null
+++ b/tools/tryselect/docs/tasks.rst
@@ -0,0 +1,125 @@
+Task Generation
+===============
+
+Many selectors (including ``chooser``, ``coverage`` and ``fuzzy``) source their available tasks
+directly from the :doc:`taskgraph </taskcluster/taskcluster/index>` module by building the taskgraph
+locally. This means that the list of available tasks will never be stale. While this is very
+powerful, it comes with a large enough performance cost to get annoying (around twenty seconds).
+
+The result of the taskgraph generation will be cached, so this penalty will only be incurred
+whenever a file in the ``/taskcluster`` directory is modified. Unfortunately this directory changes
+pretty frequently, so developers can expect to rebuild the cache each time they pull in
+``mozilla-central``. Developers who regularly work on ``/taskcluster`` can expect to rebuild even
+more frequently.
+
+
+Configuring Watchman
+--------------------
+
+It's possible to bypass this penalty completely by using the file watching service `watchman`_. If
+you use the ``fsmonitor`` mercurial extension, you already have ``watchman`` installed.
+
+.. note::
+
+    If you aren't using `fsmonitor`_ but end up installng watchman anyway, you
+    might as well enable it for a faster Mercurial experience.
+
+Otherwise, `install watchman`_. If using Linux you'll likely run into the `inotify limits`_ outlined
+on that page due to the size of ``mozilla-central``. You can `read this page`_ for more information
+on how to bump the limits permanently.
+
+Next run the following commands:
+
+.. code-block:: shell
+
+    $ cd path/to/mozilla-central
+    $ watchman -j < tools/tryselect/watchman.json
+
+You should see output like:
+
+.. code-block:: json
+
+    {
+        "version": "4.9.0",
+        "triggerid": "rebuild-taskgraph-cache",
+        "disposition": "created"
+    }
+
+That's it. Now anytime a file under ``/taskcluster`` is modified (either by your editor, or by
+updating version control), the taskgraph cache will be rebuilt in the background, allowing you to
+skip the wait the next time you run ``mach try``.
+
+.. note::
+
+    Watchman triggers are persistent and don't need to be added more than once.
+    See `Managing Triggers`_ for how to remove a trigger.
+
+You can test that everything is working by running these commands:
+
+.. code-block:: shell
+
+    $ statedir=`mach python -c "from mozboot.util import get_state_dir; get_state_dir(srcdir=True)"`
+    $ rm -rf $statedir/cache/taskgraph
+    $ touch taskcluster/mach_commands.py
+    # wait a minute for generation to trigger and finish
+    $ ls $statedir/cache/taskgraph
+
+If the ``target_task_set`` file exists, you are good to go. If not you can look at the ``watchman``
+log to see if there were any errors. This typically lives somewhere like
+``/usr/local/var/run/watchman/<user>-state/log``. In this case please file a bug under ``Firefox
+Build System :: Try`` and include the relevant portion of the log.
+
+
+Running Watchman on Startup
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Watchman is both a client and a service all in one. When running a ``watchman`` command, the client
+binary will start the service in the background if it isn't running. This means on reboot the
+service won't be running and you'll need to start the service each time by invoking the client
+binary (e.g by running ``watchman version``).
+
+If you'd like this to happen automatically, you can use your favourite platform specific way of
+running commands at startup (``crontab``, ``rc.local``, etc.). But the easiest way is likely just to
+add ``watchman version > /dev/null 2>&1`` to your ``.bash_profile`` or equivalent.
+
+For more control, you can also take a look at `this hint`_ on how to setup
+``watchman`` as a ``systemd`` service.
+
+
+Managing Triggers
+~~~~~~~~~~~~~~~~~
+
+When adding a trigger watchman writes it to disk. Typically it'll be a path similar to
+``/usr/local/var/run/<user>-state/state``. While editing that file by hand would work, the watchman
+binary provides an interface for managing your triggers.
+
+To see all directories you are currently watching:
+
+.. code-block:: shell
+
+    $ watchman watch-list
+
+To view triggers that are active in a specified watch:
+
+.. code-block:: shell
+
+    $ watchman trigger-list <path>
+
+To delete a trigger from a specified watch:
+
+.. code-block:: shell
+
+    $ watchman trigger-del <path> <name>
+
+In the above two examples, replace ``<path>`` with the path of the watch, presumably
+``mozilla-central``. Using ``.`` works as well if that is already your working directory. For more
+information on managing triggers and a reference of other commands, see the `official docs`_.
+
+
+.. _watchman: https://facebook.github.io/watchman/
+.. _fsmonitor: https://www.mercurial-scm.org/wiki/FsMonitorExtension
+.. _install watchman: https://facebook.github.io/watchman/docs/install.html
+.. _inotify limits: https://facebook.github.io/watchman/docs/install.html#linux-inotify-limits
+.. _read this page: https://github.com/guard/listen/wiki/Increasing-the-amount-of-inotify-watchers
+.. _this hint: https://github.com/facebook/watchman/commit/2985377eaf8c8538b28fae9add061b67991a87c2
+.. _official docs: https://facebook.github.io/watchman/docs/cmd/trigger.html
--- a/tools/tryselect/selectors/chooser/__init__.py
+++ b/tools/tryselect/selectors/chooser/__init__.py
@@ -5,17 +5,17 @@
 from __future__ import absolute_import, print_function, unicode_literals
 
 import os
 import webbrowser
 from threading import Timer
 
 from tryselect.cli import BaseTryParser
 from tryselect.tasks import generate_tasks
-from tryselect.push import check_working_directory, push_to_try, vcs
+from tryselect.push import check_working_directory, push_to_try
 
 here = os.path.abspath(os.path.dirname(__file__))
 
 
 class ChooserParser(BaseTryParser):
     name = 'chooser'
     arguments = []
     common_groups = ['push', 'task']
@@ -23,17 +23,17 @@ class ChooserParser(BaseTryParser):
 
 
 def run(update=False, query=None, templates=None, full=False, parameters=None,
         save=False, preset=None, mod_presets=False, push=True, message='{msg}',
         closed_tree=False):
     from .app import create_application
     check_working_directory(push)
 
-    tg = generate_tasks(parameters, full, root=vcs.path)
+    tg = generate_tasks(parameters, full)
     app = create_application(tg)
 
     if os.environ.get('WERKZEUG_RUN_MAIN') == 'true':
         # we are in the reloader process, don't open the browser or do any try stuff
         app.run()
         return
 
     # give app a second to start before opening the browser
--- a/tools/tryselect/selectors/coverage.py
+++ b/tools/tryselect/selectors/coverage.py
@@ -347,17 +347,17 @@ def run(templates={}, full=False, parame
     download_coverage_mapping(vcs.base_ref)
 
     changed_sources = vcs.get_outgoing_files()
     test_files, test_chunks = find_tests(changed_sources)
     if not test_files and not test_chunks:
         print('ERROR Could not find any tests or chunks to run.')
         return 1
 
-    tg = generate_tasks(parameters, full, root=build.topsrcdir)
+    tg = generate_tasks(parameters, full)
     all_tasks = tg.tasks.keys()
 
     tasks_by_chunks = filter_tasks_by_chunks(all_tasks, test_chunks)
     tasks_by_path = filter_tasks_by_paths(all_tasks, test_files)
     tasks = filter(is_opt_task, set(tasks_by_path + tasks_by_chunks))
 
     if not tasks:
         print('ERROR Did not find any matching tasks after filtering.')
--- a/tools/tryselect/selectors/fuzzy.py
+++ b/tools/tryselect/selectors/fuzzy.py
@@ -11,17 +11,17 @@ import subprocess
 import sys
 from distutils.spawn import find_executable
 
 from mozboot.util import get_state_dir