Merge mozilla-central to mozilla-inbound
authorarthur.iakab <aiakab@mozilla.com>
Mon, 03 Dec 2018 00:02:03 +0200
changeset 505641 c758d2a5b8cb04b1b5e5188a309d2994ad430d80
parent 505640 d0fb1493b28bd765b60b5a34c72f3b6f1a493aee (current diff)
parent 505608 fb9b6c3665571b702d087dce1bf9e6e024c92131 (diff)
child 505642 4976cba52e47aaba70bcc69357ad33335c2a9e3a
push id10290
push userffxbld-merge
push dateMon, 03 Dec 2018 16:23:23 +0000
treeherdermozilla-beta@700bed2445e6 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone65.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
third_party/rust/quote-0.3.15/.cargo-checksum.json
third_party/rust/quote-0.3.15/Cargo.toml
third_party/rust/quote-0.3.15/LICENSE-APACHE
third_party/rust/quote-0.3.15/LICENSE-MIT
third_party/rust/quote-0.3.15/README.md
third_party/rust/quote-0.3.15/src/ident.rs
third_party/rust/quote-0.3.15/src/lib.rs
third_party/rust/quote-0.3.15/src/to_tokens.rs
third_party/rust/quote-0.3.15/src/tokens.rs
third_party/rust/quote-0.3.15/tests/test.rs
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1940,21 +1940,16 @@ dependencies = [
 
 [[package]]
 name = "quick-error"
 version = "1.2.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 
 [[package]]
 name = "quote"
-version = "0.3.15"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-
-[[package]]
-name = "quote"
 version = "0.5.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 dependencies = [
  "proc-macro2 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)",
 ]
 
 [[package]]
 name = "quote"
@@ -2321,28 +2316,29 @@ name = "string_cache"
 version = "0.7.3"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 dependencies = [
  "lazy_static 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
  "new_debug_unreachable 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
  "phf_shared 0.7.21 (registry+https://github.com/rust-lang/crates.io-index)",
  "precomputed-hash 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
  "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)",
- "string_cache_codegen 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
+ "string_cache_codegen 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)",
  "string_cache_shared 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
 ]
 
 [[package]]
 name = "string_cache_codegen"
-version = "0.4.0"
+version = "0.4.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 dependencies = [
  "phf_generator 0.7.21 (registry+https://github.com/rust-lang/crates.io-index)",
  "phf_shared 0.7.21 (registry+https://github.com/rust-lang/crates.io-index)",
- "quote 0.3.15 (registry+https://github.com/rust-lang/crates.io-index)",
+ "proc-macro2 0.4.9 (registry+https://github.com/rust-lang/crates.io-index)",
+ "quote 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)",
  "string_cache_shared 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
 ]
 
 [[package]]
 name = "string_cache_shared"
 version = "0.3.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 
@@ -3293,17 +3289,16 @@ dependencies = [
 "checksum plain 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"
 "checksum plane-split 0.13.3 (registry+https://github.com/rust-lang/crates.io-index)" = "9b1d9a84aa3bbc2dafd06856bdb1dc333eb1d442ad8987b9d596c7344b3ed969"
 "checksum podio 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "e5422a1ee1bc57cc47ae717b0137314258138f38fd5f3cea083f43a9725383a0"
 "checksum precomputed-hash 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"
 "checksum proc-macro2 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)" = "77997c53ae6edd6d187fec07ec41b207063b5ee6f33680e9fa86d405cdd313d4"
 "checksum proc-macro2 0.4.9 (registry+https://github.com/rust-lang/crates.io-index)" = "cccdc7557a98fe98453030f077df7f3a042052fae465bb61d2c2c41435cfd9b6"
 "checksum procedural-masquerade 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "9f566249236c6ca4340f7ca78968271f0ed2b0f234007a61b66f9ecd0af09260"
 "checksum quick-error 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "eda5fe9b71976e62bc81b781206aaa076401769b2143379d3eb2118388babac4"
-"checksum quote 0.3.15 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6e920b65c65f10b2ae65c831a81a073a89edd28c7cce89475bff467ab4167a"
 "checksum quote 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)" = "9949cfe66888ffe1d53e6ec9d9f3b70714083854be20fd5e271b232a017401e8"
 "checksum quote 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)" = "e44651a0dc4cdd99f71c83b561e221f714912d11af1a4dff0631f923d53af035"
 "checksum rand 0.3.22 (registry+https://github.com/rust-lang/crates.io-index)" = "15a732abf9d20f0ad8eeb6f909bf6868722d9a06e1e50802b6a70351f40b4eb1"
 "checksum rand 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)" = "8356f47b32624fef5b3301c1be97e5944ecdd595409cc5da11d05f211db6cfbd"
 "checksum rayon 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "485541959c8ecc49865526fe6c4de9653dd6e60d829d6edf0be228167b60372d"
 "checksum rayon-core 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "9d24ad214285a7729b174ed6d3bcfcb80177807f959d95fafd5bfc5c4f201ac8"
 "checksum redox_syscall 0.1.32 (registry+https://github.com/rust-lang/crates.io-index)" = "ab105df655884ede59d45b7070c8a65002d921461ee813a024558ca16030eea0"
 "checksum redox_termios 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7e891cfe48e9100a70a3b6eb652fef28920c117d366339687bd5576160db0f76"
@@ -3337,17 +3332,17 @@ dependencies = [
 "checksum siphasher 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "2ffc669b726f2bc9a3bcff66e5e23b56ba6bf70e22a34c3d7b6d0b3450b65b84"
 "checksum slab 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "17b4fcaed89ab08ef143da37bc52adbcc04d4a69014f4c1208d6b51f0c47bc23"
 "checksum slab 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)" = "5f9776d6b986f77b35c6cf846c11ad986ff128fe0b2b63a3628e3755e8d3102d"
 "checksum smallbitvec 2.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "5c63726029f0069f88467873e47f392575f28f9f16b72ac65465263db4b3a13c"
 "checksum smallvec 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)" = "153ffa32fd170e9944f7e0838edf824a754ec4c1fc64746fcc9fe1f8fa602e5d"
 "checksum stable_deref_trait 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "15132e0e364248108c5e2c02e3ab539be8d6f5d52a01ca9bbf27ed657316f02b"
 "checksum string 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "00caf261d6f90f588f8450b8e1230fa0d5be49ee6140fdfbcb55335aff350970"
 "checksum string_cache 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)" = "25d70109977172b127fe834e5449e5ab1740b9ba49fa18a2020f509174f25423"
-"checksum string_cache_codegen 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "479cde50c3539481f33906a387f2bd17c8e87cb848c35b6021d41fb81ff9b4d7"
+"checksum string_cache_codegen 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "1eea1eee654ef80933142157fdad9dd8bc43cf7c74e999e369263496f04ff4da"
 "checksum string_cache_shared 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b1884d1bc09741d466d9b14e6d37ac89d6909cbcac41dd9ae982d4d063bbedfc"
 "checksum strsim 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b4d15c810519a91cf877e7e36e63fe068815c678181439f2f29e2562147c3694"
 "checksum strsim 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "bb4f380125926a99e52bc279241539c018323fab05ad6368b56f93d9369ff550"
 "checksum syn 0.13.1 (registry+https://github.com/rust-lang/crates.io-index)" = "91b52877572087400e83d24b9178488541e3d535259e04ff17a63df1e5ceff59"
 "checksum syn 0.14.6 (registry+https://github.com/rust-lang/crates.io-index)" = "4e4b5274d4a0a3d2749d5c158dc64d3403e60554dc61194648787ada5212473d"
 "checksum syn 0.15.7 (registry+https://github.com/rust-lang/crates.io-index)" = "455a6ec9b368f8c479b0ae5494d13b22dc00990d2f00d68c9dc6a2dc4f17f210"
 "checksum synstructure 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)" = "73687139bf99285483c96ac0add482c3776528beac1d97d444f6e91f203a2015"
 "checksum synstructure 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)" = "98cad891cd238c98e1f0aec9f7c0f620aa696e4e5f7daba56ac67b5e86a6b049"
--- a/browser/base/content/browser-contentblocking.js
+++ b/browser/base/content/browser-contentblocking.js
@@ -2,45 +2,57 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 var TrackingProtection = {
   reportBreakageLabel: "trackingprotection",
   telemetryIdentifier: "tp",
   PREF_ENABLED_GLOBALLY: "privacy.trackingprotection.enabled",
   PREF_ENABLED_IN_PRIVATE_WINDOWS: "privacy.trackingprotection.pbmode.enabled",
-  PREF_UI_ENABLED: "browser.contentblocking.trackingprotection.control-center.ui.enabled",
   PREF_TRACKING_TABLE: "urlclassifier.trackingTable",
   PREF_TRACKING_ANNOTATION_TABLE: "urlclassifier.trackingAnnotationTable",
   enabledGlobally: false,
   enabledInPrivateWindows: false,
 
   get categoryItem() {
     delete this.categoryItem;
     return this.categoryItem =
       document.getElementById("identity-popup-content-blocking-category-tracking-protection");
   },
 
+  get categoryLabel() {
+    delete this.categoryLabel;
+    return this.categoryLabel =
+      document.getElementById("identity-popup-content-blocking-tracking-protection-state-label");
+  },
+
   get subViewList() {
     delete this.subViewList;
     return this.subViewList = document.getElementById("identity-popup-trackersView-list");
   },
 
   get strictInfo() {
     delete this.strictInfo;
     return this.strictInfo = document.getElementById("identity-popup-trackersView-strict-info");
   },
 
+  strings: {
+    get subViewBlocked() {
+      delete this.subViewBlocked;
+      return this.subViewBlocked =
+        gNavigatorBundle.getString("contentBlocking.trackersView.blocked.label");
+    },
+  },
+
   init() {
     this.updateEnabled();
 
     Services.prefs.addObserver(this.PREF_ENABLED_GLOBALLY, this);
     Services.prefs.addObserver(this.PREF_ENABLED_IN_PRIVATE_WINDOWS, this);
 
-    XPCOMUtils.defineLazyPreferenceGetter(this, "visible", this.PREF_UI_ENABLED, false);
     XPCOMUtils.defineLazyPreferenceGetter(this, "trackingTable", this.PREF_TRACKING_TABLE, false);
     XPCOMUtils.defineLazyPreferenceGetter(this, "trackingAnnotationTable", this.PREF_TRACKING_ANNOTATION_TABLE, false);
   },
 
   uninit() {
     Services.prefs.removeObserver(this.PREF_ENABLED_GLOBALLY, this);
     Services.prefs.removeObserver(this.PREF_ENABLED_IN_PRIVATE_WINDOWS, this);
   },
@@ -55,24 +67,39 @@ var TrackingProtection = {
             PrivateBrowsingUtils.isWindowPrivate(window));
   },
 
   updateEnabled() {
     this.enabledGlobally =
       Services.prefs.getBoolPref(this.PREF_ENABLED_GLOBALLY);
     this.enabledInPrivateWindows =
       Services.prefs.getBoolPref(this.PREF_ENABLED_IN_PRIVATE_WINDOWS);
+    this.updateCategoryLabel();
   },
 
-  isBlockerActivated(state) {
-    return state & Ci.nsIWebProgressListener.STATE_BLOCKED_TRACKING_CONTENT;
+  updateCategoryLabel() {
+    let label;
+    if (this.enabled) {
+      label = "contentBlocking.trackers.blocked.label";
+    } else {
+      label = "contentBlocking.trackers.allowed.label";
+    }
+    this.categoryLabel.textContent = gNavigatorBundle.getString(label);
+  },
+
+  isBlocking(state) {
+    return (state & Ci.nsIWebProgressListener.STATE_BLOCKED_TRACKING_CONTENT) != 0;
   },
 
   isAllowing(state) {
-    return state & Ci.nsIWebProgressListener.STATE_LOADED_TRACKING_CONTENT;
+    return (state & Ci.nsIWebProgressListener.STATE_LOADED_TRACKING_CONTENT) != 0;
+  },
+
+  isDetected(state) {
+    return this.isBlocking(state) || this.isAllowing(state);
   },
 
   async updateSubView() {
     let previousURI = gBrowser.currentURI.spec;
     let previousWindow = gBrowser.selectedBrowser.innerWindowID;
 
     let contentBlockingLogJSON = await gBrowser.selectedBrowser.getContentBlockingLog();
     let contentBlockingLog = JSON.parse(contentBlockingLogJSON);
@@ -109,17 +136,17 @@ var TrackingProtection = {
   },
 
   async _createListItem(origin, actions) {
     // Figure out if this list entry was actually detected by TP or something else.
     let isDetected = false;
     let isAllowed = false;
     for (let [state] of actions) {
       isAllowed = isAllowed || this.isAllowing(state);
-      isDetected = isDetected || isAllowed || this.isBlockerActivated(state);
+      isDetected = isDetected || isAllowed || this.isBlocking(state);
     }
 
     if (!isDetected) {
       return null;
     }
 
     let uri = Services.io.newURI(origin);
 
@@ -127,47 +154,84 @@ var TrackingProtection = {
     // need to make sure that this is a tracker that we would actually have blocked
     // before showing it to the user.
     let isTracker = await this._isOnTrackingTable(uri);
     if (!isTracker) {
       return null;
     }
 
     let listItem = document.createXULElement("hbox");
-    listItem.className = "identity-popup-trackersView-list-item";
+    listItem.className = "identity-popup-content-blocking-list-item";
     listItem.classList.toggle("allowed", isAllowed);
+    // Repeat the host in the tooltip in case it's too long
+    // and overflows in our panel.
+    listItem.tooltipText = uri.host;
 
     let image = document.createXULElement("image");
+    image.className = "identity-popup-trackersView-icon";
+    image.classList.toggle("allowed", isAllowed);
     listItem.append(image);
 
     let label = document.createXULElement("label");
     label.value = uri.host;
+    label.className = "identity-popup-content-blocking-list-host-label";
     label.setAttribute("crop", "end");
     listItem.append(label);
 
+    if (!isAllowed) {
+      let stateLabel = document.createXULElement("label");
+      stateLabel.value = this.strings.subViewBlocked;
+      stateLabel.className = "identity-popup-content-blocking-list-state-label";
+      listItem.append(stateLabel);
+    }
+
     return listItem;
   },
 };
 
 var ThirdPartyCookies = {
   telemetryIdentifier: "cr",
   PREF_ENABLED: "network.cookie.cookieBehavior",
   PREF_REPORT_BREAKAGE_ENABLED: "browser.contentblocking.rejecttrackers.reportBreakage.enabled",
   PREF_ENABLED_VALUES: [
     // These values match the ones exposed under the Content Blocking section
     // of the Preferences UI.
     Ci.nsICookieService.BEHAVIOR_REJECT_FOREIGN,  // Block all third-party cookies
     Ci.nsICookieService.BEHAVIOR_REJECT_TRACKER,  // Block third-party cookies from trackers
   ],
-  PREF_UI_ENABLED: "browser.contentblocking.rejecttrackers.control-center.ui.enabled",
 
   get categoryItem() {
     delete this.categoryItem;
     return this.categoryItem =
-      document.getElementById("identity-popup-content-blocking-category-3rdpartycookies");
+      document.getElementById("identity-popup-content-blocking-category-cookies");
+  },
+
+  get categoryLabel() {
+    delete this.categoryLabel;
+    return this.categoryLabel =
+      document.getElementById("identity-popup-content-blocking-cookies-state-label");
+  },
+
+  get subViewList() {
+    delete this.subViewList;
+    return this.subViewList = document.getElementById("identity-popup-cookiesView-list");
+  },
+
+  strings: {
+    get subViewAllowed() {
+      delete this.subViewAllowed;
+      return this.subViewAllowed =
+        gNavigatorBundle.getString("contentBlocking.cookiesView.allowed.label");
+    },
+
+    get subViewBlocked() {
+      delete this.subViewBlocked;
+      return this.subViewBlocked =
+        gNavigatorBundle.getString("contentBlocking.cookiesView.blocked.label");
+    },
   },
 
   get reportBreakageLabel() {
     switch (this.behaviorPref) {
     case Ci.nsICookieService.BEHAVIOR_ACCEPT:
       return "nocookiesblocked";
     case Ci.nsICookieService.BEHAVIOR_REJECT_FOREIGN:
       return "allthirdpartycookiesblocked";
@@ -178,50 +242,246 @@ var ThirdPartyCookies = {
     default:
       Cu.reportError(`Error: Unknown cookieBehavior pref observed: ${this.behaviorPref}`);
       // fall through
     case Ci.nsICookieService.BEHAVIOR_REJECT_TRACKER:
       return "cookierestrictions";
     }
   },
 
-  get categoryLabelDefault() {
-    delete this.categoryLabelDefault;
-    return this.categoryLabelDefault =
-      document.getElementById("identity-popup-content-blocking-category-label-default");
-  },
-
-  get categoryLabelTrackers() {
-    delete this.categoryLabelTrackers;
-    return this.categoryLabelTrackers =
-      document.getElementById("identity-popup-content-blocking-category-label-trackers");
-  },
-
   updateCategoryLabel() {
-    let rejectTrackers = this.behaviorPref == Ci.nsICookieService.BEHAVIOR_REJECT_TRACKER;
-    this.categoryLabelDefault.hidden = rejectTrackers;
-    this.categoryLabelTrackers.hidden = !rejectTrackers;
+    let label;
+    switch (this.behaviorPref) {
+    case Ci.nsICookieService.BEHAVIOR_REJECT_FOREIGN:
+      label = "contentBlocking.cookies.3rdPartyBlocked.label";
+      break;
+    case Ci.nsICookieService.BEHAVIOR_REJECT:
+      label = "contentBlocking.cookies.allBlocked.label";
+      break;
+    case Ci.nsICookieService.BEHAVIOR_LIMIT_FOREIGN:
+      label = "contentBlocking.cookies.unvisitedBlocked.label";
+      break;
+    case Ci.nsICookieService.BEHAVIOR_REJECT_TRACKER:
+      label = "contentBlocking.cookies.trackersBlocked.label";
+      break;
+    default:
+      Cu.reportError(`Error: Unknown cookieBehavior pref observed: ${this.behaviorPref}`);
+      // fall through
+    case Ci.nsICookieService.BEHAVIOR_ACCEPT:
+      label = "contentBlocking.cookies.allowed.label";
+      break;
+    }
+    this.categoryLabel.textContent = gNavigatorBundle.getString(label);
   },
 
   init() {
     XPCOMUtils.defineLazyPreferenceGetter(this, "behaviorPref", this.PREF_ENABLED,
       Ci.nsICookieService.BEHAVIOR_ACCEPT, this.updateCategoryLabel.bind(this));
-    XPCOMUtils.defineLazyPreferenceGetter(this, "visible", this.PREF_UI_ENABLED, false);
     XPCOMUtils.defineLazyPreferenceGetter(this, "reportBreakageEnabled",
       this.PREF_REPORT_BREAKAGE_ENABLED, false);
     this.updateCategoryLabel();
   },
+
   get enabled() {
     return this.PREF_ENABLED_VALUES.includes(this.behaviorPref);
   },
 
-  isBlockerActivated(state) {
+  isBlocking(state) {
     return (state & Ci.nsIWebProgressListener.STATE_COOKIES_BLOCKED_TRACKER) != 0 ||
+           (state & Ci.nsIWebProgressListener.STATE_COOKIES_BLOCKED_ALL) != 0 ||
+           (state & Ci.nsIWebProgressListener.STATE_COOKIES_BLOCKED_BY_PERMISSION) != 0 ||
            (state & Ci.nsIWebProgressListener.STATE_COOKIES_BLOCKED_FOREIGN) != 0;
   },
+
+  isDetected(state) {
+    return (state & Ci.nsIWebProgressListener.STATE_COOKIES_LOADED) != 0;
+  },
+
+  async updateSubView() {
+    let contentBlockingLogJSON = await gBrowser.selectedBrowser.getContentBlockingLog();
+    let contentBlockingLog = JSON.parse(contentBlockingLogJSON);
+
+    let categories = this._processContentBlockingLog(contentBlockingLog);
+
+    this.subViewList.textContent = "";
+
+    for (let category of ["firstParty", "trackers", "thirdParty"]) {
+      if (categories[category].length) {
+        let box = document.createXULElement("vbox");
+        let label = document.createXULElement("label");
+        label.className = "identity-popup-cookiesView-list-header";
+        label.textContent = gNavigatorBundle.getString(`contentBlocking.cookiesView.${category}.label`);
+        box.appendChild(label);
+        for (let info of categories[category]) {
+          box.appendChild(this._createListItem(info));
+        }
+        this.subViewList.appendChild(box);
+      }
+    }
+  },
+
+  _hasException(origin) {
+    for (let perm of Services.perms.getAllForPrincipal(gBrowser.contentPrincipal)) {
+      if (perm.type == "3rdPartyStorage^" + origin || perm.type.startsWith("3rdPartyStorage^" + origin + "^")) {
+        return true;
+      }
+    }
+
+    let principal = Services.scriptSecurityManager.createCodebasePrincipalFromOrigin(origin);
+    // Cookie exceptions get "inherited" from parent- to sub-domain, so we need to
+    // make sure to include parent domains in the permission check for "cookies".
+    return Services.perms.testPermissionFromPrincipal(principal, "cookie") != Services.perms.UNKNOWN_ACTION;
+  },
+
+  _clearException(origin) {
+    for (let perm of Services.perms.getAllForPrincipal(gBrowser.contentPrincipal)) {
+      if (perm.type == "3rdPartyStorage^" + origin || perm.type.startsWith("3rdPartyStorage^" + origin + "^")) {
+        Services.perms.removePermission(perm);
+      }
+    }
+
+    // OAs don't matter here, so we can just use the hostname.
+    let host = Services.io.newURI(origin).host;
+
+    // Cookie exceptions get "inherited" from parent- to sub-domain, so we need to
+    // clear any cookie permissions from parent domains as well.
+    for (let perm of Services.perms.enumerator) {
+      if (perm.type == "cookie" &&
+          Services.eTLD.hasRootDomain(host, perm.principal.URI.host)) {
+        Services.perms.removePermission(perm);
+      }
+    }
+  },
+
+  // Transforms and filters cookie entries in the content blocking log
+  // so that we can categorize and display them in the UI.
+  _processContentBlockingLog(log) {
+    let newLog = {
+      firstParty: [],
+      trackers: [],
+      thirdParty: [],
+    };
+
+    let firstPartyDomain = null;
+    try {
+      firstPartyDomain = Services.eTLD.getBaseDomain(gBrowser.currentURI);
+    } catch (e) {
+      // There are nasty edge cases here where someone is trying to set a cookie
+      // on a public suffix or an IP address. Just categorize those as third party...
+      if (e.result != Cr.NS_ERROR_HOST_IS_IP_ADDRESS &&
+          e.result != Cr.NS_ERROR_INSUFFICIENT_DOMAIN_LEVELS) {
+        throw e;
+      }
+    }
+
+    for (let [origin, actions] of Object.entries(log)) {
+      if (!origin.startsWith("http")) {
+        continue;
+      }
+
+      let info = {origin, isAllowed: true, hasException: this._hasException(origin)};
+      let hasCookie = false;
+      let isTracker = false;
+
+      // Extract information from the states entries in the content blocking log.
+      // Each state will contain a single state flag from nsIWebProgressListener.
+      // Note that we are using the same helper functions that are applied to the
+      // bit map passed to onSecurityChange (which contains multiple states), thus
+      // not checking exact equality, just presence of bits.
+      for (let [state, blocked] of actions) {
+        if (this.isDetected(state)) {
+          hasCookie = true;
+        }
+        if (TrackingProtection.isAllowing(state)) {
+          isTracker = true;
+        }
+        // blocked tells us whether the resource was actually blocked
+        // (which it may not be in case of an exception).
+        if (this.isBlocking(state) && blocked) {
+          info.isAllowed = false;
+        }
+      }
+
+      if (!hasCookie) {
+        continue;
+      }
+
+      let isFirstParty = false;
+      try {
+        let uri = Services.io.newURI(origin);
+        isFirstParty = Services.eTLD.getBaseDomain(uri) == firstPartyDomain;
+      } catch (e) {
+        if (e.result != Cr.NS_ERROR_HOST_IS_IP_ADDRESS &&
+            e.result != Cr.NS_ERROR_INSUFFICIENT_DOMAIN_LEVELS) {
+          throw e;
+        }
+      }
+
+      if (isFirstParty) {
+        newLog.firstParty.push(info);
+      } else if (isTracker) {
+        newLog.trackers.push(info);
+      } else {
+        newLog.thirdParty.push(info);
+      }
+    }
+
+    return newLog;
+  },
+
+  _createListItem({origin, isAllowed, hasException}) {
+    let listItem = document.createXULElement("hbox");
+    listItem.className = "identity-popup-content-blocking-list-item";
+    listItem.classList.toggle("allowed", isAllowed);
+    // Repeat the origin in the tooltip in case it's too long
+    // and overflows in our panel.
+    listItem.tooltipText = origin;
+
+    let image = document.createXULElement("image");
+    image.className = "identity-popup-cookiesView-icon";
+    image.classList.toggle("allowed", isAllowed);
+    listItem.append(image);
+
+    let label = document.createXULElement("label");
+    label.value = origin;
+    label.className = "identity-popup-content-blocking-list-host-label";
+    label.setAttribute("crop", "end");
+    listItem.append(label);
+
+    let stateLabel;
+    if (isAllowed && hasException) {
+      stateLabel = document.createXULElement("label");
+      stateLabel.value = this.strings.subViewAllowed;
+      stateLabel.className = "identity-popup-content-blocking-list-state-label";
+      listItem.append(stateLabel);
+    } else if (!isAllowed) {
+      stateLabel = document.createXULElement("label");
+      stateLabel.value = this.strings.subViewBlocked;
+      stateLabel.className = "identity-popup-content-blocking-list-state-label";
+      listItem.append(stateLabel);
+    }
+
+    if (hasException) {
+      let removeException = document.createXULElement("button");
+      removeException.className = "identity-popup-permission-remove-button";
+      removeException.tooltipText = gNavigatorBundle.getFormattedString(
+        "contentBlocking.cookiesView.removeButton.tooltip", [origin]);
+      removeException.addEventListener("click", () => {
+        this._clearException(origin);
+        // Just flip the display based on what state we had previously.
+        stateLabel.value = isAllowed ? this.strings.subViewBlocked : this.strings.subViewAllowed;
+        listItem.classList.toggle("allowed", !isAllowed);
+        image.classList.toggle("allowed", !isAllowed);
+        removeException.hidden = true;
+      });
+      listItem.append(removeException);
+    }
+
+    return listItem;
+  },
 };
 
 
 var ContentBlocking = {
   // If the user ignores the doorhanger, we stop showing it after some time.
   MAX_INTROS: 20,
   PREF_ANIMATIONS_ENABLED: "toolkit.cosmeticAnimations.enabled",
   PREF_REPORT_BREAKAGE_ENABLED: "browser.contentblocking.reportBreakage.enabled",
@@ -392,21 +652,19 @@ var ContentBlocking = {
     // Leave the ? at the end of the URL to signify that this URL had its query stripped.
     let urlWithoutQuery = this.reportURI.asciiSpec.replace(this.reportURI.query, "");
     let body = `Full URL: ${urlWithoutQuery}\n`;
     body += `userAgent: ${navigator.userAgent}\n`;
 
     body += "\n**Preferences**\n";
     body += `${TrackingProtection.PREF_ENABLED_GLOBALLY}: ${Services.prefs.getBoolPref(TrackingProtection.PREF_ENABLED_GLOBALLY)}\n`;
     body += `${TrackingProtection.PREF_ENABLED_IN_PRIVATE_WINDOWS}: ${Services.prefs.getBoolPref(TrackingProtection.PREF_ENABLED_IN_PRIVATE_WINDOWS)}\n`;
-    body += `${TrackingProtection.PREF_UI_ENABLED}: ${Services.prefs.getBoolPref(TrackingProtection.PREF_UI_ENABLED)}\n`;
     body += `urlclassifier.trackingTable: ${Services.prefs.getStringPref("urlclassifier.trackingTable")}\n`;
     body += `network.http.referer.defaultPolicy: ${Services.prefs.getIntPref("network.http.referer.defaultPolicy")}\n`;
     body += `network.http.referer.defaultPolicy.pbmode: ${Services.prefs.getIntPref("network.http.referer.defaultPolicy.pbmode")}\n`;
-    body += `${ThirdPartyCookies.PREF_UI_ENABLED}: ${Services.prefs.getBoolPref(ThirdPartyCookies.PREF_UI_ENABLED)}\n`;
     body += `${ThirdPartyCookies.PREF_ENABLED}: ${Services.prefs.getIntPref(ThirdPartyCookies.PREF_ENABLED)}\n`;
     body += `network.cookie.lifetimePolicy: ${Services.prefs.getIntPref("network.cookie.lifetimePolicy")}\n`;
     body += `privacy.restrict3rdpartystorage.expiration: ${Services.prefs.getIntPref("privacy.restrict3rdpartystorage.expiration")}\n`;
 
     let comments = document.getElementById("identity-popup-breakageReportView-collection-comments");
     body += "\n**Comments**\n" + comments.value;
 
     formData.set("body", body);
@@ -442,16 +700,21 @@ var ContentBlocking = {
     this.identityPopupMultiView.showSubView("identity-popup-breakageReportView");
   },
 
   async showTrackersSubview() {
     await TrackingProtection.updateSubView();
     this.identityPopupMultiView.showSubView("identity-popup-trackersView");
   },
 
+  async showCookiesSubview() {
+    await ThirdPartyCookies.updateSubView();
+    this.identityPopupMultiView.showSubView("identity-popup-cookiesView");
+  },
+
   shieldHistogramAdd(value) {
     if (PrivateBrowsingUtils.isWindowPrivate(window)) {
       return;
     }
     Services.telemetry.getHistogramById("TRACKING_PROTECTION_SHIELD").add(value);
   },
 
   onSecurityChange(oldState, state, webProgress, isSimulated,
@@ -468,81 +731,80 @@ var ContentBlocking = {
 
     // The user might have navigated before the shield animation
     // finished. In this case, reset the animation to be able to
     // play it in full again and avoid choppiness.
     if (webProgress.isTopLevel) {
       this.iconBox.removeAttribute("animate");
     }
 
-    let anyBlockerActivated = false;
+    let anyDetected = false;
+    let anyBlocking = false;
 
     for (let blocker of this.blockers) {
       // Store data on whether the blocker is activated in the current document for
       // reporting it using the "report breakage" dialog. Under normal circumstances this
       // dialog should only be able to open in the currently selected tab and onSecurityChange
       // runs on tab switch, so we can avoid associating the data with the document directly.
-      blocker.activated = blocker.isBlockerActivated(state);
+      blocker.activated = blocker.isBlocking(state);
       blocker.categoryItem.classList.toggle("blocked", blocker.enabled);
-      blocker.categoryItem.hidden = !blocker.visible;
-      anyBlockerActivated = anyBlockerActivated || blocker.activated;
+      let detected = blocker.isDetected(state);
+      blocker.categoryItem.hidden = !detected;
+      anyDetected = anyDetected || detected;
+      anyBlocking = anyBlocking || blocker.activated;
     }
 
-    // We consider the shield state "active" when some kind of blocking activity
-    // occurs on the page.  Note that merely allowing the loading of content that
-    // we could have blocked does not trigger the appearance of the shield.
-    // This state will be overriden later if there's an exception set for this site.
-    let active = anyBlockerActivated;
-    let isAllowing = state & Ci.nsIWebProgressListener.STATE_LOADED_TRACKING_CONTENT;
-    let detected = anyBlockerActivated || isAllowing;
-
     let isBrowserPrivate = PrivateBrowsingUtils.isBrowserPrivate(gBrowser.selectedBrowser);
 
     // Check whether the user has added an exception for this site.
     let type =  isBrowserPrivate ? "trackingprotection-pb" : "trackingprotection";
     let hasException = Services.perms.testExactPermission(baseURI, type) ==
       Services.perms.ALLOW_ACTION;
 
-    this.content.toggleAttribute("detected", detected);
+    // We consider the shield state "active" when some kind of blocking activity
+    // occurs on the page.  Note that merely allowing the loading of content that
+    // we could have blocked does not trigger the appearance of the shield.
+    // This state will be overriden later if there's an exception set for this site.
+    this.content.toggleAttribute("detected", anyDetected);
+    this.content.toggleAttribute("blocking", anyBlocking);
     this.content.toggleAttribute("hasException", hasException);
-    this.content.toggleAttribute("active", active);
 
-    this.iconBox.toggleAttribute("active", active);
+    this.iconBox.toggleAttribute("active", anyBlocking);
     this.iconBox.toggleAttribute("hasException", hasException);
 
     // For release (due to the large volume) we only want to receive reports
     // for breakage that is directly related to third party cookie blocking.
     if (this.reportBreakageEnabled ||
         (ThirdPartyCookies.reportBreakageEnabled &&
          ThirdPartyCookies.activated &&
          !TrackingProtection.activated)) {
       this.reportBreakageButton.removeAttribute("hidden");
     } else {
       this.reportBreakageButton.setAttribute("hidden", "true");
     }
 
     if (isSimulated) {
       this.iconBox.removeAttribute("animate");
-    } else if (active && webProgress.isTopLevel) {
+    } else if (anyBlocking && webProgress.isTopLevel) {
       this.iconBox.setAttribute("animate", "true");
 
       if (!isBrowserPrivate) {
         let introCount = Services.prefs.getIntPref(this.prefIntroCount);
         if (introCount < this.MAX_INTROS) {
           Services.prefs.setIntPref(this.prefIntroCount, ++introCount);
           Services.prefs.savePrefFile(null);
           this.showIntroPanel();
         }
       }
     }
 
     if (hasException) {
       this.iconBox.setAttribute("tooltiptext", this.disabledTooltipText);
       this.shieldHistogramAdd(1);
-    } else if (active) {
+    } else if (anyBlocking) {
       this.iconBox.setAttribute("tooltiptext", this.activeTooltipText);
       this.shieldHistogramAdd(2);
     } else {
       this.iconBox.removeAttribute("tooltiptext");
       this.shieldHistogramAdd(0);
     }
   },
 
--- a/browser/base/content/browser-sync.js
+++ b/browser/base/content/browser-sync.js
@@ -716,17 +716,17 @@ var gSync = {
         syncIcon.removeAttribute("tooltiptext");
         syncNow.removeAttribute("tooltiptext");
       }
     }
   },
 
   get relativeTimeFormat() {
     delete this.relativeTimeFormat;
-    return this.relativeTimeFormat = new Services.intl.RelativeTimeFormat(undefined, {style: "short"});
+    return this.relativeTimeFormat = new Services.intl.RelativeTimeFormat(undefined, {style: "long"});
   },
 
   formatLastSyncDate(date) {
     if (!date) { // Date can be null before the first sync!
       return null;
     }
     const relativeDateStr = this.relativeTimeFormat.formatBestUnit(date);
     return this.syncStrings.formatStringFromName("lastSync2.label", [relativeDateStr], 1);
--- a/browser/base/content/test/trackingUI/benignPage.html
+++ b/browser/base/content/test/trackingUI/benignPage.html
@@ -2,11 +2,17 @@
 <!-- This Source Code Form is subject to the terms of the Mozilla Public
    - License, v. 2.0. If a copy of the MPL was not distributed with this
    - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
 <html dir="ltr" xml:lang="en-US" lang="en-US">
   <head>
     <meta charset="utf8">
   </head>
   <body>
-    <iframe src="http://not-tracking.example.com/"></iframe>
+    <!--TODO: We used to have an iframe here, to double-check that benign-->
+    <!--iframes may be included in pages. However, the cookie restrictions-->
+    <!--project introduced a change that declared blockable content to be-->
+    <!--found on any page that embeds iframes, rendering this unusable for-->
+    <!--our purposes. That's not ideal and we intend to restore this iframe.-->
+    <!--(See bug 1511303 for a more detailed technical explanation.)-->
+    <!--<iframe src="http://not-tracking.example.com/"></iframe>-->
   </body>
 </html>
--- a/browser/base/content/test/trackingUI/browser.ini
+++ b/browser/base/content/test/trackingUI/browser.ini
@@ -8,20 +8,22 @@ support-files =
   trackingAPI.js
   trackingPage.html
 
 [browser_trackingUI_3.js]
 [browser_trackingUI_animation.js]
 [browser_trackingUI_animation_2.js]
 [browser_trackingUI_appMenu.js]
 [browser_trackingUI_categories.js]
+[browser_trackingUI_cookies_subview.js]
 [browser_trackingUI_fetch.js]
 support-files =
   file_trackingUI_fetch.html
   file_trackingUI_fetch.js
   file_trackingUI_fetch.js^headers^
 [browser_trackingUI_open_preferences.js]
 [browser_trackingUI_pbmode_exceptions.js]
 [browser_trackingUI_report_breakage.js]
 [browser_trackingUI_state.js]
+skip-if = serviceworker_e10s # see https://bugzilla.mozilla.org/show_bug.cgi?id=1511303#c1
 [browser_trackingUI_state_all_disabled.js]
 [browser_trackingUI_telemetry.js]
 [browser_trackingUI_trackers_subview.js]
--- a/browser/base/content/test/trackingUI/browser_trackingUI_categories.js
+++ b/browser/base/content/test/trackingUI/browser_trackingUI_categories.js
@@ -11,19 +11,17 @@ registerCleanupFunction(function() {
   Services.prefs.clearUserPref(TP_PB_PREF);
   Services.prefs.clearUserPref(TPC_PREF);
   Services.prefs.clearUserPref(TT_PREF);
   Services.prefs.clearUserPref(CAT_PREF);
 });
 
 add_task(async function testCategoryLabelsInControlPanel() {
   await BrowserTestUtils.withNewTab("http://www.example.com", async function() {
-    let promisePanelOpen = BrowserTestUtils.waitForEvent(gIdentityHandler._identityPopup, "popupshown");
-    gIdentityHandler._identityBox.click();
-    await promisePanelOpen;
+    await openIdentityPopup();
 
     let preferencesButton = document.getElementById("tracking-protection-preferences-button");
     ok(preferencesButton.label, "The preferencesButton label exists");
 
     Services.prefs.setStringPref(CAT_PREF, "strict");
     await TestUtils.waitForCondition(() => preferencesButton.label ==
       gNavigatorBundle.getString("contentBlocking.category.strict"));
     is(preferencesButton.label, gNavigatorBundle.getString("contentBlocking.category.strict"),
@@ -65,8 +63,60 @@ add_task(async function testCategoryLabe
 
     Services.prefs.setStringPref(CAT_PREF, "custom");
     await TestUtils.waitForCondition(() => appMenuCategoryLabel.value ==
       gNavigatorBundle.getString("contentBlocking.category.custom"));
     is(appMenuCategoryLabel.value, gNavigatorBundle.getString("contentBlocking.category.custom"),
       "The appMenuCategory label has been changed to custom");
   });
 });
+
+add_task(async function testSubcategoryLabels() {
+  await BrowserTestUtils.withNewTab("http://www.example.com", async function() {
+    let categoryLabel =
+      document.getElementById("identity-popup-content-blocking-tracking-protection-state-label");
+
+    Services.prefs.setBoolPref(TP_PREF, true);
+    await TestUtils.waitForCondition(() => categoryLabel.textContent ==
+      gNavigatorBundle.getString("contentBlocking.trackers.blocked.label"),
+      "The category label has updated correctly");
+    is(categoryLabel.textContent, gNavigatorBundle.getString("contentBlocking.trackers.blocked.label"));
+
+    Services.prefs.setBoolPref(TP_PREF, false);
+    await TestUtils.waitForCondition(() => categoryLabel.textContent ==
+      gNavigatorBundle.getString("contentBlocking.trackers.allowed.label"),
+      "The category label has updated correctly");
+    is(categoryLabel.textContent, gNavigatorBundle.getString("contentBlocking.trackers.allowed.label"));
+
+    categoryLabel =
+      document.getElementById("identity-popup-content-blocking-cookies-state-label");
+
+    Services.prefs.setIntPref(TPC_PREF, Ci.nsICookieService.BEHAVIOR_ACCEPT);
+    await TestUtils.waitForCondition(() => categoryLabel.textContent ==
+      gNavigatorBundle.getString("contentBlocking.cookies.allowed.label"),
+      "The category label has updated correctly");
+    is(categoryLabel.textContent, gNavigatorBundle.getString("contentBlocking.cookies.allowed.label"));
+
+    Services.prefs.setIntPref(TPC_PREF, Ci.nsICookieService.BEHAVIOR_REJECT);
+    await TestUtils.waitForCondition(() => categoryLabel.textContent ==
+      gNavigatorBundle.getString("contentBlocking.cookies.allBlocked.label"),
+      "The category label has updated correctly");
+    is(categoryLabel.textContent, gNavigatorBundle.getString("contentBlocking.cookies.allBlocked.label"));
+
+    Services.prefs.setIntPref(TPC_PREF, Ci.nsICookieService.BEHAVIOR_REJECT_FOREIGN);
+    await TestUtils.waitForCondition(() => categoryLabel.textContent ==
+      gNavigatorBundle.getString("contentBlocking.cookies.3rdPartyBlocked.label"),
+      "The category label has updated correctly");
+    is(categoryLabel.textContent, gNavigatorBundle.getString("contentBlocking.cookies.3rdPartyBlocked.label"));
+
+    Services.prefs.setIntPref(TPC_PREF, Ci.nsICookieService.BEHAVIOR_REJECT_TRACKER);
+    await TestUtils.waitForCondition(() => categoryLabel.textContent ==
+      gNavigatorBundle.getString("contentBlocking.cookies.trackersBlocked.label"),
+      "The category label has updated correctly");
+    is(categoryLabel.textContent, gNavigatorBundle.getString("contentBlocking.cookies.trackersBlocked.label"));
+
+    Services.prefs.setIntPref(TPC_PREF, Ci.nsICookieService.BEHAVIOR_LIMIT_FOREIGN);
+    await TestUtils.waitForCondition(() => categoryLabel.textContent ==
+      gNavigatorBundle.getString("contentBlocking.cookies.unvisitedBlocked.label"),
+      "The category label has updated correctly");
+    is(categoryLabel.textContent, gNavigatorBundle.getString("contentBlocking.cookies.unvisitedBlocked.label"));
+  });
+});
new file mode 100644
--- /dev/null
+++ b/browser/base/content/test/trackingUI/browser_trackingUI_cookies_subview.js
@@ -0,0 +1,190 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+/* eslint-disable mozilla/no-arbitrary-setTimeout */
+
+"use strict";
+
+const COOKIE_PAGE = "http://not-tracking.example.com/browser/browser/base/content/test/trackingUI/cookiePage.html";
+
+const TPC_PREF = "network.cookie.cookieBehavior";
+
+add_task(async function setup() {
+  // Avoid the content blocking tour interfering with our tests by popping up.
+  await SpecialPowers.pushPrefEnv({set: [[ContentBlocking.prefIntroCount, ContentBlocking.MAX_INTROS]]});
+  await UrlClassifierTestUtils.addTestTrackers();
+
+  registerCleanupFunction(() => {
+    UrlClassifierTestUtils.cleanupTestTrackers();
+  });
+});
+
+async function assertSitesListed(trackersBlocked, thirdPartyBlocked, firstPartyBlocked) {
+  await BrowserTestUtils.withNewTab(COOKIE_PAGE, async function(browser) {
+    await openIdentityPopup();
+
+    let categoryItem =
+      document.getElementById("identity-popup-content-blocking-category-cookies");
+    ok(BrowserTestUtils.is_visible(categoryItem), "TP category item is visible");
+    let cookiesView = document.getElementById("identity-popup-cookiesView");
+    let viewShown = BrowserTestUtils.waitForEvent(cookiesView, "ViewShown");
+    categoryItem.click();
+    await viewShown;
+
+    ok(true, "Cookies view was shown");
+
+    let listHeaders = cookiesView.querySelectorAll(".identity-popup-cookiesView-list-header");
+    is(listHeaders.length, 1, "We have 1 list header");
+    is(listHeaders[0].textContent,
+       gNavigatorBundle.getString(`contentBlocking.cookiesView.trackers.label`),
+       "The list header is for tracking cookies.");
+
+    let listItems = cookiesView.querySelectorAll(".identity-popup-content-blocking-list-item");
+    is(listItems.length, 1, "We have 1 cookie in the list");
+
+    let listItem = listItems[0];
+    let label = listItem.querySelector(".identity-popup-content-blocking-list-host-label");
+    is(label.value, "http://trackertest.org", "Has an item for trackertest.org");
+    ok(BrowserTestUtils.is_visible(listItem), "List item is visible");
+    is(listItem.classList.contains("allowed"), !trackersBlocked,
+      "Indicates whether the cookie was blocked or allowed");
+
+    let mainView = document.getElementById("identity-popup-mainView");
+    viewShown = BrowserTestUtils.waitForEvent(mainView, "ViewShown");
+    let backButton = cookiesView.querySelector(".subviewbutton-back");
+    backButton.click();
+    await viewShown;
+
+    ok(true, "Main view was shown");
+
+    let change = waitForSecurityChange();
+    let timeoutPromise = new Promise(resolve => setTimeout(resolve, 1000));
+
+    await ContentTask.spawn(browser, {}, function() {
+      content.postMessage("third-party-cookie", "*");
+    });
+
+    let result = await Promise.race([change, timeoutPromise]);
+    is(result, undefined, "No securityChange events should be received");
+
+    viewShown = BrowserTestUtils.waitForEvent(cookiesView, "ViewShown");
+    categoryItem.click();
+    await viewShown;
+
+    ok(true, "Cookies view was shown");
+
+    listHeaders = cookiesView.querySelectorAll(".identity-popup-cookiesView-list-header");
+    is(listHeaders.length, 2, "We now have 2 list headers");
+    is(listHeaders[1].textContent,
+       gNavigatorBundle.getString(`contentBlocking.cookiesView.thirdParty.label`),
+       "The new list header is for third party cookies.");
+
+    listItems = cookiesView.querySelectorAll(".identity-popup-content-blocking-list-item");
+    is(listItems.length, 2, "We have 2 cookies in the list");
+
+    listItem = listItems[1];
+    label = listItem.querySelector(".identity-popup-content-blocking-list-host-label");
+    is(label.value, "https://test1.example.org", "Has an item for test1.example.org");
+    ok(BrowserTestUtils.is_visible(listItem), "List item is visible");
+    is(listItem.classList.contains("allowed"), !thirdPartyBlocked,
+      "Indicates whether the cookie was blocked or allowed");
+
+    viewShown = BrowserTestUtils.waitForEvent(mainView, "ViewShown");
+    backButton.click();
+    await viewShown;
+
+    ok(true, "Main view was shown");
+
+    change = waitForSecurityChange();
+    timeoutPromise = new Promise(resolve => setTimeout(resolve, 1000));
+
+    await ContentTask.spawn(browser, {}, function() {
+      content.postMessage("first-party-cookie", "*");
+    });
+
+    result = await Promise.race([change, timeoutPromise]);
+    is(result, undefined, "No securityChange events should be received");
+
+    viewShown = BrowserTestUtils.waitForEvent(cookiesView, "ViewShown");
+    categoryItem.click();
+    await viewShown;
+
+    ok(true, "Cookies view was shown");
+
+    listHeaders = cookiesView.querySelectorAll(".identity-popup-cookiesView-list-header");
+    is(listHeaders.length, 3, "We now have 3 list headers");
+    is(listHeaders[0].textContent,
+       gNavigatorBundle.getString(`contentBlocking.cookiesView.firstParty.label`),
+       "The new list header is for first party cookies.");
+
+    listItems = cookiesView.querySelectorAll(".identity-popup-content-blocking-list-item");
+    is(listItems.length, 3, "We have 2 cookies in the list");
+
+    listItem = listItems[0];
+    label = listItem.querySelector(".identity-popup-content-blocking-list-host-label");
+    is(label.value, "http://not-tracking.example.com", "Has an item for the first party");
+    ok(BrowserTestUtils.is_visible(listItem), "List item is visible");
+    is(listItem.classList.contains("allowed"), !firstPartyBlocked,
+      "Indicates whether the cookie was blocked or allowed");
+  });
+}
+
+add_task(async function testCookiesSubView() {
+  info("Testing cookies subview with reject tracking cookies.");
+  Services.prefs.setIntPref(TPC_PREF, Ci.nsICookieService.BEHAVIOR_REJECT_TRACKER);
+  await assertSitesListed(true, false, false);
+  info("Testing cookies subview with reject third party cookies.");
+  Services.prefs.setIntPref(TPC_PREF, Ci.nsICookieService.BEHAVIOR_REJECT_FOREIGN);
+  await assertSitesListed(true, true, false);
+  info("Testing cookies subview with reject all cookies.");
+  Services.prefs.setIntPref(TPC_PREF, Ci.nsICookieService.BEHAVIOR_REJECT);
+  await assertSitesListed(true, true, true);
+  info("Testing cookies subview with accept all cookies.");
+  Services.prefs.setIntPref(TPC_PREF, Ci.nsICookieService.BEHAVIOR_ACCEPT);
+  await assertSitesListed(false, false, false);
+
+  Services.prefs.clearUserPref(TPC_PREF);
+});
+
+add_task(async function testCookiesSubViewAllowed() {
+  Services.prefs.setIntPref(TPC_PREF, Ci.nsICookieService.BEHAVIOR_REJECT_TRACKER);
+  let principal = Services.scriptSecurityManager.createCodebasePrincipalFromOrigin("http://trackertest.org/");
+  Services.perms.addFromPrincipal(principal, "cookie", Services.perms.ALLOW_ACTION);
+
+  await BrowserTestUtils.withNewTab(COOKIE_PAGE, async function(browser) {
+    await openIdentityPopup();
+
+    let categoryItem =
+      document.getElementById("identity-popup-content-blocking-category-cookies");
+    ok(BrowserTestUtils.is_visible(categoryItem), "TP category item is visible");
+    let cookiesView = document.getElementById("identity-popup-cookiesView");
+    let viewShown = BrowserTestUtils.waitForEvent(cookiesView, "ViewShown");
+    categoryItem.click();
+    await viewShown;
+
+    ok(true, "Cookies view was shown");
+
+    let listHeaders = cookiesView.querySelectorAll(".identity-popup-cookiesView-list-header");
+    is(listHeaders.length, 1, "We have 1 list header");
+    is(listHeaders[0].textContent,
+       gNavigatorBundle.getString(`contentBlocking.cookiesView.trackers.label`),
+       "The list header is for tracking cookies.");
+
+    let listItems = cookiesView.querySelectorAll(".identity-popup-content-blocking-list-item");
+    is(listItems.length, 1, "We have 1 cookie in the list");
+
+    let listItem = listItems[0];
+    let label = listItem.querySelector(".identity-popup-content-blocking-list-host-label");
+    is(label.value, "http://trackertest.org", "Has an item for trackertest.org");
+    ok(BrowserTestUtils.is_visible(listItem), "List item is visible");
+    ok(listItem.classList.contains("allowed"), "Indicates whether the cookie was blocked or allowed");
+
+    let button = listItem.querySelector(".identity-popup-permission-remove-button");
+    ok(BrowserTestUtils.is_visible(button), "Permission remove button is visible");
+    button.click();
+    is(Services.perms.testExactPermissionFromPrincipal(principal, "cookie"), Services.perms.UNKNOWN_ACTION, "Button click should remove cookie pref.");
+    ok(!listItem.classList.contains("allowed"), "Has removed the allowed class");
+  });
+
+  Services.prefs.clearUserPref(TPC_PREF);
+});
--- a/browser/base/content/test/trackingUI/browser_trackingUI_fetch.js
+++ b/browser/base/content/test/trackingUI/browser_trackingUI_fetch.js
@@ -1,27 +1,10 @@
 const URL = "http://mochi.test:8888/browser/browser/base/content/test/trackingUI/file_trackingUI_fetch.html";
 
-function waitForSecurityChange(numChanges = 1) {
-  return new Promise(resolve => {
-    let n = 0;
-    let listener = {
-      onSecurityChange() {
-        n = n + 1;
-        info("Received onSecurityChange event " + n + " of " + numChanges);
-        if (n >= numChanges) {
-          gBrowser.removeProgressListener(listener);
-          resolve();
-        }
-      },
-    };
-    gBrowser.addProgressListener(listener);
-  });
-}
-
 add_task(async function test_fetch() {
   await SpecialPowers.pushPrefEnv({ set: [
     ["privacy.trackingprotection.enabled", true],
   ]});
 
   await BrowserTestUtils.withNewTab({ gBrowser, url: URL }, async function(newTabBrowser) {
     let securityChange = waitForSecurityChange();
     await ContentTask.spawn(newTabBrowser, null, async function() {
--- a/browser/base/content/test/trackingUI/browser_trackingUI_open_preferences.js
+++ b/browser/base/content/test/trackingUI/browser_trackingUI_open_preferences.js
@@ -1,17 +1,15 @@
 /* Any copyright is dedicated to the Public Domain.
  * http://creativecommons.org/publicdomain/zero/1.0/ */
 
 "use strict";
 
 const TP_PREF = "privacy.trackingprotection.enabled";
 const TPC_PREF = "network.cookie.cookieBehavior";
-const TP_UI_PREF = "browser.contentblocking.trackingprotection.control-center.ui.enabled";
-const RT_UI_PREF = "browser.contentblocking.rejecttrackers.control-center.ui.enabled";
 const TRACKING_PAGE = "http://tracking.example.org/browser/browser/base/content/test/trackingUI/trackingPage.html";
 
 async function waitAndAssertPreferencesShown() {
   await BrowserTestUtils.waitForEvent(gIdentityHandler._identityPopup, "popuphidden");
   await TestUtils.waitForCondition(() => gBrowser.currentURI.spec == "about:preferences#privacy",
     "Should open about:preferences.");
 
   await ContentTask.spawn(gBrowser.selectedBrowser, {}, async function() {
@@ -61,18 +59,16 @@ add_task(async function testOpenPreferen
 });
 
 // Tests that clicking the contentblocking category items "add blocking" labels
 // links to about:preferences
 add_task(async function testOpenPreferencesFromAddBlockingButtons() {
   SpecialPowers.pushPrefEnv({set: [
     [TP_PREF, false],
     [TPC_PREF, Ci.nsICookieService.BEHAVIOR_ACCEPT],
-    [TP_UI_PREF, true],
-    [RT_UI_PREF, true],
   ]});
 
   await BrowserTestUtils.withNewTab(TRACKING_PAGE, async function() {
     let addBlockingButtons = document.querySelectorAll(".identity-popup-content-blocking-category-add-blocking");
     for (let button of addBlockingButtons) {
       let promisePanelOpen = BrowserTestUtils.waitForEvent(gIdentityHandler._identityPopup, "popupshown");
       gIdentityHandler._identityBox.click();
       await promisePanelOpen;
--- a/browser/base/content/test/trackingUI/browser_trackingUI_pbmode_exceptions.js
+++ b/browser/base/content/test/trackingUI/browser_trackingUI_pbmode_exceptions.js
@@ -52,22 +52,16 @@ function testTrackingPage(window) {
     ok(!hidden("#tracking-action-unblock-private"), "unblockButtonPrivate is visible");
   } else {
     ok(!hidden("#tracking-action-unblock"), "unblockButton is visible");
     ok(hidden("#tracking-action-unblock-private"), "unblockButtonPrivate is hidden");
   }
 
   ok(hidden("#identity-popup-content-blocking-not-detected"), "blocking not detected label is hidden");
   ok(!hidden("#identity-popup-content-blocking-detected"), "blocking detected label is visible");
-
-  ok(!hidden("#identity-popup-content-blocking-category-list"), "category list is visible");
-  ok(hidden("#identity-popup-content-blocking-category-tracking-protection > #identity-popup-content-blocking-tracking-protection-label-allowed"),
-    "TP category item is not showing the allowed label");
-  ok(!hidden("#identity-popup-content-blocking-category-tracking-protection > #identity-popup-content-blocking-tracking-protection-label-blocked"),
-    "TP category item is set to blocked");
 }
 
 function testTrackingPageUnblocked() {
   info("Tracking content must be white-listed and not blocked");
   ok(ContentBlocking.content.hasAttribute("detected"), "trackers are detected");
   ok(ContentBlocking.content.hasAttribute("hasException"), "content shows exception");
 
   ok(!ContentBlocking.iconBox.hasAttribute("active"), "shield is active");
@@ -76,22 +70,16 @@ function testTrackingPageUnblocked() {
      gNavigatorBundle.getString("trackingProtection.icon.disabledTooltip"), "correct tooltip");
 
   ok(BrowserTestUtils.is_visible(ContentBlocking.iconBox), "icon box is visible");
   ok(!hidden("#tracking-action-block"), "blockButton is visible");
   ok(hidden("#tracking-action-unblock"), "unblockButton is hidden");
 
   ok(hidden("#identity-popup-content-blocking-not-detected"), "blocking not detected label is hidden");
   ok(!hidden("#identity-popup-content-blocking-detected"), "blocking detected label is visible");
-
-  ok(!hidden("#identity-popup-content-blocking-category-list"), "category list is visible");
-  ok(!hidden("#identity-popup-content-blocking-category-tracking-protection > #identity-popup-content-blocking-tracking-protection-label-allowed"),
-    "TP category item is showing the allowed label");
-  ok(hidden("#identity-popup-content-blocking-category-tracking-protection > #identity-popup-content-blocking-tracking-protection-label-blocked"),
-    "TP category item is not set to blocked");
 }
 
 add_task(async function testExceptionAddition() {
   await UrlClassifierTestUtils.addTestTrackers();
   let privateWin = await BrowserTestUtils.openNewBrowserWindow({private: true});
   browser = privateWin.gBrowser;
   let tab = await BrowserTestUtils.openNewForegroundTab({ gBrowser: browser, waitForLoad: true, waitForStateStop: true });
 
--- a/browser/base/content/test/trackingUI/browser_trackingUI_report_breakage.js
+++ b/browser/base/content/test/trackingUI/browser_trackingUI_report_breakage.js
@@ -21,23 +21,16 @@ add_task(async function setup() {
   let oldCanRecord = Services.telemetry.canRecordExtended;
   Services.telemetry.canRecordExtended = true;
 
   registerCleanupFunction(() => {
     Services.telemetry.canRecordExtended = oldCanRecord;
   });
 });
 
-function openIdentityPopup() {
-  let mainView = document.getElementById("identity-popup-mainView");
-  let viewShown = BrowserTestUtils.waitForEvent(mainView, "ViewShown");
-  gIdentityHandler._identityBox.click();
-  return viewShown;
-}
-
 add_task(async function testReportBreakageVisibility() {
   let scenarios = [
     {
       url: TRACKING_PAGE,
       prefs: {
         "privacy.trackingprotection.enabled": true,
         "browser.contentblocking.reportBreakage.enabled": true,
       },
@@ -181,21 +174,19 @@ add_task(async function testReportBreaka
         let body = CommonUtils.readBytesFromInputStream(request.bodyInputStream);
         let boundary = request.getHeader("Content-Type").match(/boundary=-+([^-]*)/i)[1];
         let regex = new RegExp("-+" + boundary + "-*\\s+");
         let sections = body.split(regex);
 
         let prefs = [
           "privacy.trackingprotection.enabled",
           "privacy.trackingprotection.pbmode.enabled",
-          "browser.contentblocking.trackingprotection.control-center.ui.enabled",
           "urlclassifier.trackingTable",
           "network.http.referer.defaultPolicy",
           "network.http.referer.defaultPolicy.pbmode",
-          "browser.contentblocking.rejecttrackers.control-center.ui.enabled",
           "network.cookie.cookieBehavior",
           "network.cookie.lifetimePolicy",
           "privacy.restrict3rdpartystorage.expiration",
         ];
         let prefsBody = "";
 
         for (let pref of prefs) {
           prefsBody += `${pref}: ${Preferences.get(pref)}\r\n`;
--- a/browser/base/content/test/trackingUI/browser_trackingUI_state.js
+++ b/browser/base/content/test/trackingUI/browser_trackingUI_state.js
@@ -51,49 +51,53 @@ function clickButton(sel) {
   let el = win.document.querySelector(sel);
   el.doCommand();
 }
 
 function testBenignPage() {
   info("Non-tracking content must not be blocked");
   ok(!ContentBlocking.content.hasAttribute("detected"), "no trackers are detected");
   ok(!ContentBlocking.content.hasAttribute("hasException"), "content shows no exception");
-  ok(!ContentBlocking.content.hasAttribute("active"), "content is not active");
 
   ok(!ContentBlocking.iconBox.hasAttribute("active"), "shield is not active");
   ok(!ContentBlocking.iconBox.hasAttribute("hasException"), "icon box shows no exception");
   ok(!ContentBlocking.iconBox.hasAttribute("tooltiptext"), "icon box has no tooltip");
 
   ok(BrowserTestUtils.is_hidden(ContentBlocking.iconBox), "icon box is hidden");
   ok(hidden("#tracking-action-block"), "blockButton is hidden");
   ok(hidden("#tracking-action-unblock"), "unblockButton is hidden");
 
   ok(!hidden("#identity-popup-content-blocking-not-detected"), "blocking not detected label is visible");
   ok(hidden("#identity-popup-content-blocking-detected"), "blocking detected label is hidden");
-  ok(hidden("#identity-popup-content-blocking-category-list"), "category list is hidden");
+  ok(hidden("#identity-popup-content-blocking-category-cookies"),
+    "Not showing cookie restrictions category");
+  ok(hidden("#identity-popup-content-blocking-category-tracking-protection"),
+    "Not showing trackers category");
 }
 
 function testBenignPageWithException() {
   info("Non-tracking content must not be blocked");
   ok(!ContentBlocking.content.hasAttribute("detected"), "no trackers are detected");
   ok(ContentBlocking.content.hasAttribute("hasException"), "content shows exception");
-  ok(!ContentBlocking.content.hasAttribute("active"), "content is not active");
 
   ok(!ContentBlocking.iconBox.hasAttribute("active"), "shield is not active");
   ok(ContentBlocking.iconBox.hasAttribute("hasException"), "shield shows exception");
   is(ContentBlocking.iconBox.getAttribute("tooltiptext"),
      gNavigatorBundle.getString("trackingProtection.icon.disabledTooltip"), "correct tooltip");
 
   ok(!BrowserTestUtils.is_hidden(ContentBlocking.iconBox), "icon box is not hidden");
   ok(!hidden("#tracking-action-block"), "blockButton is visible");
   ok(hidden("#tracking-action-unblock"), "unblockButton is hidden");
 
   ok(!hidden("#identity-popup-content-blocking-not-detected"), "blocking not detected label is visible");
   ok(hidden("#identity-popup-content-blocking-detected"), "blocking detected label is hidden");
-  ok(hidden("#identity-popup-content-blocking-category-list"), "category list is hidden");
+  ok(hidden("#identity-popup-content-blocking-category-cookies"),
+    "Not showing cookie restrictions category");
+  ok(hidden("#identity-popup-content-blocking-category-tracking-protection"),
+    "Not showing trackers category");
 }
 
 function areTrackersBlocked(isPrivateBrowsing) {
   let blockedByTP = Services.prefs.getBoolPref(isPrivateBrowsing ? TP_PB_PREF : TP_PREF);
   let blockedByTPC = Services.prefs.getIntPref(TPC_PREF) == Ci.nsICookieService.BEHAVIOR_REJECT_TRACKER;
   return blockedByTP || blockedByTPC;
 }
 
@@ -101,18 +105,16 @@ function testTrackingPage(window) {
   info("Tracking content must be blocked");
   ok(ContentBlocking.content.hasAttribute("detected"), "trackers are detected");
   ok(!ContentBlocking.content.hasAttribute("hasException"), "content shows no exception");
 
   let isPrivateBrowsing = PrivateBrowsingUtils.isWindowPrivate(window);
   let blockedByTP = areTrackersBlocked(isPrivateBrowsing);
   is(BrowserTestUtils.is_visible(ContentBlocking.iconBox), blockedByTP,
      "icon box is" + (blockedByTP ? "" : " not") + " visible");
-  is(ContentBlocking.content.hasAttribute("active"), blockedByTP,
-      "content is" + (blockedByTP ? "" : " not") + " active");
   is(ContentBlocking.iconBox.hasAttribute("active"), blockedByTP,
       "shield is" + (blockedByTP ? "" : " not") + " active");
   ok(!ContentBlocking.iconBox.hasAttribute("hasException"), "icon box shows no exception");
   is(ContentBlocking.iconBox.getAttribute("tooltiptext"),
      blockedByTP ? gNavigatorBundle.getString("trackingProtection.icon.activeTooltip") : "",
      "correct tooltip");
 
   ok(hidden("#tracking-action-block"), "blockButton is hidden");
@@ -126,79 +128,43 @@ function testTrackingPage(window) {
     ok(hidden("#tracking-action-unblock-private"), "unblockButtonPrivate is hidden");
     is(!hidden("#tracking-action-unblock"), blockedByTP,
        "unblockButton is" + (blockedByTP ? "" : " not") + " visible");
   }
 
   ok(hidden("#identity-popup-content-blocking-not-detected"), "blocking not detected label is hidden");
   ok(!hidden("#identity-popup-content-blocking-detected"), "blocking detected label is visible");
 
-  ok(!hidden("#identity-popup-content-blocking-category-list"), "category list is visible");
-
-  let cookiesBlocked = Services.prefs.getIntPref(TPC_PREF) == Ci.nsICookieService.BEHAVIOR_REJECT_TRACKER;
-  if (cookiesBlocked) {
-    let category = "#identity-popup-content-blocking-category-3rdpartycookies";
-    is(hidden(category + " > .identity-popup-content-blocking-category-add-blocking"), blockedByTP,
-      "Category item is" + (blockedByTP ? " not" : "") + " showing add blocking");
-    is(hidden(category + " > .identity-popup-content-blocking-category-state-label"), !blockedByTP,
-      "Category item is" + (blockedByTP ? "" : " not") + " set to blocked");
-
-    ok(hidden("#identity-popup-content-blocking-category-label-default"),
-      "Not showing default cookie restrictions label.");
-    ok(!hidden("#identity-popup-content-blocking-category-label-trackers"),
-      "Showing trackers cookie restrictions label.");
-  } else {
-    let category = "#identity-popup-content-blocking-category-tracking-protection";
-    is(hidden(category + " > #identity-popup-content-blocking-tracking-protection-label-allowed"), blockedByTP,
-      "Category item is" + (blockedByTP ? " not" : "") + " showing the allowed label");
-    is(!hidden(category + " > #identity-popup-content-blocking-tracking-protection-label-blocked"), blockedByTP,
-      "Category item is" + (blockedByTP ? "" : " not") + " set to blocked");
-
-    ok(hidden("#identity-popup-content-blocking-category-label-trackers"),
-      "Not showing trackers cookie restrictions label.");
-    ok(!hidden("#identity-popup-content-blocking-category-label-default"),
-      "Showing default cookie restrictions label.");
-  }
+  ok(!hidden("#identity-popup-content-blocking-category-tracking-protection"),
+    "Showing trackers category");
+  ok(!hidden("#identity-popup-content-blocking-category-cookies"),
+    "Showing cookie restrictions category");
 }
 
 function testTrackingPageUnblocked(blockedByTP, window) {
   info("Tracking content must be white-listed and not blocked");
   ok(ContentBlocking.content.hasAttribute("detected"), "trackers are detected");
   ok(ContentBlocking.content.hasAttribute("hasException"), "content shows exception");
 
-  ok(!ContentBlocking.content.hasAttribute("active"), "content is not active");
   ok(!ContentBlocking.iconBox.hasAttribute("active"), "shield is not active");
   ok(ContentBlocking.iconBox.hasAttribute("hasException"), "shield shows exception");
   is(ContentBlocking.iconBox.getAttribute("tooltiptext"),
      gNavigatorBundle.getString("trackingProtection.icon.disabledTooltip"), "correct tooltip");
 
   ok(BrowserTestUtils.is_visible(ContentBlocking.iconBox), "icon box is visible");
   ok(!hidden("#tracking-action-block"), "blockButton is visible");
   ok(hidden("#tracking-action-unblock"), "unblockButton is hidden");
 
   ok(hidden("#identity-popup-content-blocking-not-detected"), "blocking not detected label is hidden");
   ok(!hidden("#identity-popup-content-blocking-detected"), "blocking detected label is visible");
 
-  ok(!hidden("#identity-popup-content-blocking-category-list"), "category list is visible");
-
-  let cookiesBlocked = Services.prefs.getIntPref(TPC_PREF) == Ci.nsICookieService.BEHAVIOR_REJECT_TRACKER;
-  if (cookiesBlocked) {
-    let category = "#identity-popup-content-blocking-category-3rdpartycookies";
-    is(hidden(category + " > .identity-popup-content-blocking-category-add-blocking"), blockedByTP,
-      "Category item is" + (blockedByTP ? " not" : "") + " showing add blocking");
-    ok(!hidden("#identity-popup-content-blocking-category-tracking-protection > #identity-popup-content-blocking-tracking-protection-label-allowed"),
-      "TP category item is showing the allowed label");
-  } else {
-    let category = "#identity-popup-content-blocking-category-tracking-protection";
-    // If there's an exception we always show the "Allowed" label.
-    ok(!hidden(category + " > #identity-popup-content-blocking-tracking-protection-label-allowed"),
-      "Category item is showing the allowed label");
-    ok(hidden(category + " > #identity-popup-content-blocking-tracking-protection-label-blocked"),
-      "Category item is not set to blocked");
-  }
+  ok(!hidden("#identity-popup-content-blocking-category-tracking-protection"),
+    "Showing trackers category");
+  ok(!hidden("#identity-popup-content-blocking-category-cookies"),
+    "Showing cookie restrictions category");
 }
 
 async function testContentBlocking(tab) {
   info("Testing with Tracking Protection ENABLED.");
 
   info("Load a test page not containing tracking elements");
   await promiseTabLoadEvent(tab, BENIGN_PAGE);
   testBenignPage();
--- a/browser/base/content/test/trackingUI/browser_trackingUI_telemetry.js
+++ b/browser/base/content/test/trackingUI/browser_trackingUI_telemetry.js
@@ -45,17 +45,17 @@ add_task(async function setup() {
 add_task(async function testShieldHistogram() {
   Services.prefs.setBoolPref(PREF, true);
   let tab = await BrowserTestUtils.openNewForegroundTab(gBrowser);
 
   // Reset these to make counting easier
   getShieldHistogram().clear();
 
   await promiseTabLoadEvent(tab, BENIGN_PAGE);
-  is(getShieldCounts()[0], 2, "Page loads without tracking");
+  is(getShieldCounts()[0], 1, "Page loads without tracking");
 
   await promiseTabLoadEvent(tab, TRACKING_PAGE);
   // Note that right now the shield histogram is not measuring what
   // you might think.  Since onSecurityChange fires twice for a tracking page,
   // the total page loads count is double counting, and the shield count
   // (which is meant to measure times when the shield wasn't shown) fires even
   // when tracking elements exist on the page.
   todo_is(getShieldCounts()[0], 1, "FIXME: TOTAL PAGE LOADS WITHOUT TRACKING IS DOUBLE COUNTING");
@@ -81,32 +81,27 @@ add_task(async function testShieldHistog
 add_task(async function testIdentityPopupEvents() {
   Services.prefs.setBoolPref(PREF, true);
   let tab = await BrowserTestUtils.openNewForegroundTab(gBrowser);
 
   await promiseTabLoadEvent(tab, BENIGN_PAGE);
 
   Services.telemetry.clearEvents();
 
-  let { gIdentityHandler } = gBrowser.ownerGlobal;
-  let promisePanelOpen = BrowserTestUtils.waitForEvent(gIdentityHandler._identityPopup, "popupshown");
-  gIdentityHandler._identityBox.click();
-  await promisePanelOpen;
+  await openIdentityPopup();
 
   let events = Services.telemetry.snapshotEvents(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, true).parent;
   let openEvents = events.filter(
     e => e[1] == "security.ui.identitypopup" && e[2] == "open" && e[3] == "identity_popup");
   is(openEvents.length, 1, "recorded telemetry for opening the identity popup");
   is(openEvents[0][4], "shield-hidden", "recorded the shield as hidden");
 
   await promiseTabLoadEvent(tab, TRACKING_PAGE);
 
-  promisePanelOpen = BrowserTestUtils.waitForEvent(gIdentityHandler._identityPopup, "popupshown");
-  gIdentityHandler._identityBox.click();
-  await promisePanelOpen;
+  await openIdentityPopup();
 
   events = Services.telemetry.snapshotEvents(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, true).parent;
   openEvents = events.filter(
     e => e[1] == "security.ui.identitypopup" && e[2] == "open" && e[3] == "identity_popup");
   is(openEvents.length, 1, "recorded telemetry for opening the identity popup");
   is(openEvents[0][4], "shield-showing", "recorded the shield as showing");
 
   info("Disable TP for the page (which reloads the page)");
--- a/browser/base/content/test/trackingUI/browser_trackingUI_trackers_subview.js
+++ b/browser/base/content/test/trackingUI/browser_trackingUI_trackers_subview.js
@@ -4,61 +4,40 @@
 
 "use strict";
 
 const TRACKING_PAGE = "http://tracking.example.org/browser/browser/base/content/test/trackingUI/trackingPage.html";
 
 const TP_PREF = "privacy.trackingprotection.enabled";
 
 add_task(async function setup() {
+  // Avoid the content blocking tour interfering with our tests by popping up.
+  await SpecialPowers.pushPrefEnv({set: [[ContentBlocking.prefIntroCount, ContentBlocking.MAX_INTROS]]});
   await UrlClassifierTestUtils.addTestTrackers();
-});
-
-function openIdentityPopup() {
-  let mainView = document.getElementById("identity-popup-mainView");
-  let viewShown = BrowserTestUtils.waitForEvent(mainView, "ViewShown");
-  gIdentityHandler._identityBox.click();
-  return viewShown;
-}
 
-function waitForSecurityChange(counter) {
-  return new Promise(resolve => {
-    let webProgressListener = {
-      onStateChange: () => {},
-      onStatusChange: () => {},
-      onLocationChange: () => {},
-      onSecurityChange: (webProgress, request, oldState, state) => {
-        if (--counter == 0) {
-          gBrowser.removeProgressListener(webProgressListener);
-          resolve(counter);
-        }
-      },
-      onProgressChange: () => {},
-      QueryInterface: ChromeUtils.generateQI([Ci.nsIWebProgressListener]),
-    };
-
-    gBrowser.addProgressListener(webProgressListener);
+  registerCleanupFunction(() => {
+    UrlClassifierTestUtils.cleanupTestTrackers();
   });
-}
+});
 
 async function assertSitesListed(blocked) {
   await BrowserTestUtils.withNewTab(TRACKING_PAGE, async function(browser) {
     await openIdentityPopup();
 
     let categoryItem =
       document.getElementById("identity-popup-content-blocking-category-tracking-protection");
     ok(BrowserTestUtils.is_visible(categoryItem), "TP category item is visible");
     let trackersView = document.getElementById("identity-popup-trackersView");
     let viewShown = BrowserTestUtils.waitForEvent(trackersView, "ViewShown");
     categoryItem.click();
     await viewShown;
 
     ok(true, "Trackers view was shown");
 
-    let listItems = document.querySelectorAll(".identity-popup-trackersView-list-item");
+    let listItems = trackersView.querySelectorAll(".identity-popup-content-blocking-list-item");
     is(listItems.length, 1, "We have 1 tracker in the list");
 
     let strictInfo = document.getElementById("identity-popup-trackersView-strict-info");
     is(BrowserTestUtils.is_hidden(strictInfo), Services.prefs.getBoolPref(TP_PREF),
       "Strict info is hidden if TP is enabled.");
 
     let mainView = document.getElementById("identity-popup-mainView");
     viewShown = BrowserTestUtils.waitForEvent(mainView, "ViewShown");
@@ -79,17 +58,17 @@ async function assertSitesListed(blocked
     is(result, undefined, "No securityChange events should be received");
 
     viewShown = BrowserTestUtils.waitForEvent(trackersView, "ViewShown");
     categoryItem.click();
     await viewShown;
 
     ok(true, "Trackers view was shown");
 
-    listItems = Array.from(document.querySelectorAll(".identity-popup-trackersView-list-item"));
+    listItems = Array.from(trackersView.querySelectorAll(".identity-popup-content-blocking-list-item"));
     is(listItems.length, 2, "We have 2 trackers in the list");
 
     let listItem = listItems.find(item => item.querySelector("label").value == "trackertest.org");
     ok(listItem, "Has an item for trackertest.org");
     ok(BrowserTestUtils.is_visible(listItem), "List item is visible");
     is(listItem.classList.contains("allowed"), !blocked,
       "Indicates whether the tracker was blocked or allowed");
 
@@ -97,24 +76,24 @@ async function assertSitesListed(blocked
     ok(listItem, "Has an item for itisatracker.org");
     ok(BrowserTestUtils.is_visible(listItem), "List item is visible");
     is(listItem.classList.contains("allowed"), !blocked,
       "Indicates whether the tracker was blocked or allowed");
   });
 }
 
 add_task(async function testTrackersSubView() {
+  info("Testing trackers subview with TP disabled.");
   Services.prefs.setBoolPref(TP_PREF, false);
   await assertSitesListed(false);
+  info("Testing trackers subview with TP enabled.");
   Services.prefs.setBoolPref(TP_PREF, true);
   await assertSitesListed(true);
+  info("Testing trackers subview with TP enabled and a CB exception.");
   let uri = Services.io.newURI("https://tracking.example.org");
   Services.perms.add(uri, "trackingprotection", Services.perms.ALLOW_ACTION);
   await assertSitesListed(false);
+  info("Testing trackers subview with TP enabled and a CB exception removed.");
   Services.perms.remove(uri, "trackingprotection");
   await assertSitesListed(true);
+
   Services.prefs.clearUserPref(TP_PREF);
 });
-
-add_task(function cleanup() {
-  Services.prefs.clearUserPref(TP_PREF);
-  UrlClassifierTestUtils.cleanupTestTrackers();
-});
--- a/browser/base/content/test/trackingUI/head.js
+++ b/browser/base/content/test/trackingUI/head.js
@@ -27,8 +27,32 @@ function promiseTabLoadEvent(tab, url) {
 
   let loaded = BrowserTestUtils.browserLoaded(tab.linkedBrowser, false, handle);
 
   if (url)
     BrowserTestUtils.loadURI(tab.linkedBrowser, url);
 
   return loaded;
 }
+
+function openIdentityPopup() {
+  let mainView = document.getElementById("identity-popup-mainView");
+  let viewShown = BrowserTestUtils.waitForEvent(mainView, "ViewShown");
+  gIdentityHandler._identityBox.click();
+  return viewShown;
+}
+
+function waitForSecurityChange(numChanges = 1) {
+  return new Promise(resolve => {
+    let n = 0;
+    let listener = {
+      onSecurityChange() {
+        n = n + 1;
+        info("Received onSecurityChange event " + n + " of " + numChanges);
+        if (n >= numChanges) {
+          gBrowser.removeProgressListener(listener);
+          resolve(n);
+        }
+      },
+    };
+    gBrowser.addProgressListener(listener);
+  });
+}
--- a/browser/base/content/test/trackingUI/trackingAPI.js
+++ b/browser/base/content/test/trackingUI/trackingAPI.js
@@ -13,10 +13,25 @@ onmessage = event => {
     }
     break;
   case "cookie": {
       let ifr = document.createElement("iframe");
       ifr.src = "https://trackertest.org/browser/browser/base/content/test/trackingUI/cookieServer.sjs";
       document.body.appendChild(ifr);
     }
     break;
+  case "first-party-cookie": {
+      // Since the content blocking log doesn't seem to get updated for
+      // top-level cookies right now, we just create an iframe with the
+      // first party domain...
+      let ifr = document.createElement("iframe");
+      ifr.src = "http://not-tracking.example.com/browser/browser/base/content/test/trackingUI/cookieServer.sjs";
+      document.body.appendChild(ifr);
+    }
+    break;
+  case "third-party-cookie": {
+      let ifr = document.createElement("iframe");
+      ifr.src = "https://test1.example.org/browser/browser/base/content/test/trackingUI/cookieServer.sjs";
+      document.body.appendChild(ifr);
+    }
+    break;
   }
 };
--- a/browser/components/controlcenter/content/panel.inc.xul
+++ b/browser/components/controlcenter/content/panel.inc.xul
@@ -69,37 +69,30 @@
 
           <description id="identity-popup-content-blocking-detected"
                        crop="end">&contentBlocking.detected;</description>
           <description id="identity-popup-content-blocking-not-detected"
                        crop="end">&contentBlocking.notDetected;</description>
 
           <vbox id="identity-popup-content-blocking-category-list">
             <toolbarbutton id="identity-popup-content-blocking-category-tracking-protection"
-                  onclick="ContentBlocking.showTrackersSubview()"
-                  class="identity-popup-content-blocking-category" align="center">
+                           onclick="ContentBlocking.showTrackersSubview()"
+                           class="identity-popup-content-blocking-category" align="center">
               <image class="identity-popup-content-blocking-category-icon tracking-protection-icon"/>
               <label flex="1" class="identity-popup-content-blocking-category-label">&contentBlocking.trackingProtection3.label;</label>
-              <label flex="1" id="identity-popup-content-blocking-tracking-protection-label-allowed"
-                     class="identity-popup-content-blocking-category-state-label">&contentBlocking.trackingProtection.allowed.label;</label>
-              <label flex="1" id="identity-popup-content-blocking-tracking-protection-label-blocked"
-                     class="identity-popup-content-blocking-category-state-label">&contentBlocking.trackingProtection.blocked.label;</label>
+              <label flex="1" id="identity-popup-content-blocking-tracking-protection-state-label" class="identity-popup-content-blocking-category-state-label"/>
             </toolbarbutton>
-            <hbox id="identity-popup-content-blocking-category-3rdpartycookies"
-                  class="identity-popup-content-blocking-category" align="center" role="group">
+            <toolbarbutton id="identity-popup-content-blocking-category-cookies"
+                           onclick="ContentBlocking.showCookiesSubview()"
+                           class="identity-popup-content-blocking-category" align="center">
               <image class="identity-popup-content-blocking-category-icon thirdpartycookies-icon"/>
               <label flex="1" id="identity-popup-content-blocking-category-label-default"
-                     class="identity-popup-content-blocking-category-label">&contentBlocking.3rdPartyCookies.label;</label>
-              <label flex="1" id="identity-popup-content-blocking-category-label-trackers"
-                     hidden="true" class="identity-popup-content-blocking-category-label">&contentBlocking.3rdPartyCookies.trackers.label;</label>
-              <label flex="1" class="identity-popup-content-blocking-category-state-label">&contentBlocking.3rdPartyCookies.blocking.label;</label>
-              <label flex="1" class="identity-popup-content-blocking-category-add-blocking text-link"
-                     id="identity-popup-3rdpartycookies-add-blocking"
-                     onclick="ContentBlocking.openPreferences('identityPopup-CB-3rdpartycookies'); gIdentityHandler.recordClick('cookies_add_blocking');">&contentBlocking.3rdPartyCookies.add.label;</label>
-            </hbox>
+                     class="identity-popup-content-blocking-category-label">&contentBlocking.cookies.label;</label>
+              <label flex="1" id="identity-popup-content-blocking-cookies-state-label" class="identity-popup-content-blocking-category-state-label"/>
+            </toolbarbutton>
           </vbox>
 
           <button id="tracking-action-unblock"
                   class="panel-button tracking-protection-button"
                   label="&trackingProtection.unblock5.label;"
                   accesskey="&trackingProtection.unblock5.accesskey;"
                   oncommand="ContentBlocking.disableForCurrentPage(); gIdentityHandler.recordClick('unblock');" />
           <button id="tracking-action-unblock-private"
@@ -241,30 +234,45 @@
 
     </panelview>
 
     <!-- Trackers SubView -->
     <panelview id="identity-popup-trackersView"
                role="document"
                title="&contentBlocking.trackersView.label;"
                descriptionheightworkaround="true">
-        <vbox id="identity-popup-trackersView-list">
+        <vbox id="identity-popup-trackersView-list" class="identity-popup-content-blocking-list">
         </vbox>
         <hbox id="identity-popup-trackersView-strict-info">
           <image/>
           <label>&contentBlocking.trackersView.strictInfo.label;</label>
         </hbox>
         <vbox class="identity-popup-footer">
           <button id="identity-popup-trackersView-settings-button"
                   label="&contentBlocking.manageSettings.label;"
                   accesskey="&contentBlocking.manageSettings.accesskey;"
                   oncommand="ContentBlocking.openPreferences();"/>
         </vbox>
     </panelview>
 
+    <!-- Cookies SubView -->
+    <panelview id="identity-popup-cookiesView"
+               role="document"
+               title="&contentBlocking.cookiesView.label;"
+               descriptionheightworkaround="true">
+        <vbox id="identity-popup-cookiesView-list" class="identity-popup-content-blocking-list">
+        </vbox>
+        <vbox class="identity-popup-footer">
+          <button id="identity-popup-cookiesView-settings-button"
+                  label="&contentBlocking.manageSettings.label;"
+                  accesskey="&contentBlocking.manageSettings.accesskey;"
+                  oncommand="ContentBlocking.openPreferences();"/>
+        </vbox>
+    </panelview>
+
     <!-- Report Breakage SubView -->
     <panelview id="identity-popup-breakageReportView"
                title="&contentBlocking.breakageReportView.label;"
                descriptionheightworkaround="true">
         <vbox id="identity-popup-breakageReportView-heading">
           <description>&contentBlocking.breakageReportView2.description;</description>
           <label id="identity-popup-breakageReportView-learn-more"
                  class="text-link">&contentBlocking.breakageReportView.learnMore;</label>
new file mode 100644
--- /dev/null
+++ b/browser/components/urlbar/UrlbarMuxerUnifiedComplete.jsm
@@ -0,0 +1,87 @@
+/* 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";
+
+/**
+ * This module exports a component used to sort matches in a QueryContext.
+ */
+
+var EXPORTED_SYMBOLS = ["UrlbarMuxerUnifiedComplete"];
+
+ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
+XPCOMUtils.defineLazyModuleGetters(this, {
+  Log: "resource://gre/modules/Log.jsm",
+  UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm",
+  UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
+});
+
+XPCOMUtils.defineLazyGetter(this, "logger", () =>
+  Log.repository.getLogger("Places.Urlbar.UrlbarMuxerUnifiedComplete"));
+
+const MATCH_TYPE_TO_GROUP = new Map([
+  [ UrlbarUtils.MATCH_TYPE.TAB_SWITCH, UrlbarUtils.MATCH_GROUP.GENERAL ],
+  [ UrlbarUtils.MATCH_TYPE.SEARCH, UrlbarUtils.MATCH_GROUP.SUGGESTION ],
+  [ UrlbarUtils.MATCH_TYPE.URL, UrlbarUtils.MATCH_GROUP.GENERAL ],
+  [ UrlbarUtils.MATCH_TYPE.KEYWORD, UrlbarUtils.MATCH_GROUP.GENERAL ],
+  [ UrlbarUtils.MATCH_TYPE.OMNIBOX, UrlbarUtils.MATCH_GROUP.EXTENSION ],
+  [ UrlbarUtils.MATCH_TYPE.REMOTE_TAB, UrlbarUtils.MATCH_GROUP.GENERAL ],
+]);
+
+/**
+ * Class used to create a muxer.
+ * The muxer receives and sorts matches in a QueryContext.
+ */
+class MuxerUnifiedComplete {
+  constructor() {
+    // Nothing.
+  }
+
+  get name() {
+    return "MuxerUnifiedComplete";
+  }
+
+  /**
+   * Sorts matches in the given QueryContext.
+   * @param {object} context a QueryContext
+   */
+  sort(context) {
+    if (!context.results.length) {
+      return;
+    }
+    // Check the first match, if it's a preselected search match, use search buckets.
+    let firstMatch = context.results[0];
+    let buckets = context.preselected &&
+                  firstMatch.type == UrlbarUtils.MATCH_TYPE.SEARCH ?
+                    UrlbarPrefs.get("matchBucketsSearch") :
+                    UrlbarPrefs.get("matchBuckets");
+    logger.debug(`Buckets: ${buckets}`);
+    let sortedMatches = [];
+    for (let [group, count] of buckets) {
+      // Search all the available matches and fill this bucket.
+      for (let match of context.results) {
+        if (count == 0) {
+          // There's no more space in this bucket.
+          break;
+        }
+
+        // Handle the heuristic result.
+        if (group == UrlbarUtils.MATCH_GROUP.HEURISTIC &&
+            match == firstMatch && context.preselected) {
+          sortedMatches.push(match);
+          count--;
+        } else if (group == MATCH_TYPE_TO_GROUP.get(match.type)) {
+          sortedMatches.push(match);
+          count--;
+        } else {
+          let errorMsg = `Match type ${match.type} is not mapped to a match group.`;
+          logger.error(errorMsg);
+          Cu.reportError(errorMsg);
+        }
+      }
+    }
+  }
+}
+
+var UrlbarMuxerUnifiedComplete = new MuxerUnifiedComplete();
--- a/browser/components/urlbar/UrlbarProvidersManager.jsm
+++ b/browser/components/urlbar/UrlbarProvidersManager.jsm
@@ -24,16 +24,21 @@ XPCOMUtils.defineLazyGetter(this, "logge
   Log.repository.getLogger("Places.Urlbar.ProvidersManager"));
 
 // List of available local providers, each is implemented in its own jsm module
 // and will track different queries internally by queryContext.
 var localProviderModules = {
   UrlbarProviderUnifiedComplete: "resource:///modules/UrlbarProviderUnifiedComplete.jsm",
 };
 
+// List of available local muxers, each is implemented in its own jsm module.
+var localMuxerModules = {
+  UrlbarMuxerUnifiedComplete: "resource:///modules/UrlbarMuxerUnifiedComplete.jsm",
+};
+
 // To improve dataflow and reduce UI work, when a match is added by a
 // non-immediate provider, we notify it to the controller after a delay, so
 // that we can chunk matches coming in that timeframe into a single call.
 const CHUNK_MATCHES_DELAY_MS = 16;
 
 /**
  * Class used to create a manager.
  * The manager is responsible to keep a list of providers, instantiate query
@@ -54,47 +59,87 @@ class ProvidersManager {
     }
     // Tracks ongoing Query instances by queryContext.
     this.queries = new Map();
 
     // Interrupt() allows to stop any running SQL query, some provider may be
     // running a query that shouldn't be interrupted, and if so it should
     // bump this through disableInterrupt and enableInterrupt.
     this.interruptLevel = 0;
+
+    // This maps muxer names to muxers.
+    this.muxers = new Map();
+    for (let [symbol, module] of Object.entries(localMuxerModules)) {
+      let {[symbol]: muxer} = ChromeUtils.import(module, {});
+      this.registerMuxer(muxer);
+    }
   }
 
   /**
    * Registers a provider object with the manager.
    * @param {object} provider
    */
   registerProvider(provider) {
-    logger.info(`Registering provider ${provider.name}`);
+    if (!provider || !provider.name ||
+        (typeof provider.startQuery != "function") ||
+        (typeof provider.cancelQuery != "function")) {
+      throw new Error(`Trying to register an invalid provider`);
+    }
     if (!Object.values(UrlbarUtils.PROVIDER_TYPE).includes(provider.type)) {
       throw new Error(`Unknown provider type ${provider.type}`);
     }
+    logger.info(`Registering provider ${provider.name}`);
     this.providers.get(provider.type).set(provider.name, provider);
   }
 
   /**
    * Unregisters a previously registered provider object.
    * @param {object} provider
    */
   unregisterProvider(provider) {
     logger.info(`Unregistering provider ${provider.name}`);
     this.providers.get(provider.type).delete(provider.name);
   }
 
   /**
+   * Registers a muxer object with the manager.
+   * @param {object} muxer a UrlbarMuxer object
+   */
+  registerMuxer(muxer) {
+    if (!muxer || !muxer.name || (typeof muxer.sort != "function")) {
+      throw new Error(`Trying to register an invalid muxer`);
+    }
+    logger.info(`Registering muxer ${muxer.name}`);
+    this.muxers.set(muxer.name, muxer);
+  }
+
+  /**
+   * Unregisters a previously registered muxer object.
+   * @param {object} muxer a UrlbarMuxer object or name.
+   */
+  unregisterMuxer(muxer) {
+    let muxerName = typeof muxer == "string" ? muxer : muxer.name;
+    logger.info(`Unregistering muxer ${muxerName}`);
+    this.muxers.delete(muxerName);
+  }
+
+  /**
    * Starts querying.
    * @param {object} queryContext The query context object
    * @param {object} controller a UrlbarController instance
    */
   async startQuery(queryContext, controller) {
     logger.info(`Query start ${queryContext.searchString}`);
-    let query = new Query(queryContext, controller, this.providers);
+    let muxerName = queryContext.muxer || "MuxerUnifiedComplete";
+    logger.info(`Using muxer ${muxerName}`);
+    let muxer = this.muxers.get(muxerName);
+    if (!muxer) {
+      throw new Error(`Muxer with name ${muxerName} not found`);
+    }
+    let query = new Query(queryContext, controller, muxer, this.providers);
     this.queries.set(queryContext, query);
     await query.start();
   }
 
   /**
    * Cancels a running query.
    * @param {object} queryContext
    */
@@ -140,22 +185,25 @@ var UrlbarProvidersManager = new Provide
  */
 class Query {
   /**
    * Initializes the query object.
    * @param {object} queryContext
    *        The query context
    * @param {object} controller
    *        The controller to be notified
+   * @param {object} muxer
+   *        The muxer to sort matches
    * @param {object} providers
    *        Map of all the providers by type and name
    */
-  constructor(queryContext, controller, providers) {
+  constructor(queryContext, controller, muxer, providers) {
     this.context = queryContext;
     this.context.results = [];
+    this.muxer = muxer;
     this.controller = controller;
     this.providers = providers;
     this.started = false;
     this.canceled = false;
     this.complete = false;
     // Array of acceptable MATCH_SOURCE values for this query. Providers not
     // returning any of these will be skipped, as well as matches not part of
     // this subset (Note we still expect the provider to do its own internal
@@ -262,18 +310,17 @@ class Query {
 
     this.context.results.push(match);
 
     let notifyResults = () => {
       if (this._chunkTimer) {
         this._chunkTimer.cancel().catch(Cu.reportError);
         delete this._chunkTimer;
       }
-      // TODO:
-      //  * pass results to a muxer before sending them back to the controller.
+      this.muxer.sort(this.context);
       this.controller.receiveResults(this.context);
     };
 
     // If the provider is not of immediate type, chunk results, to improve the
     // dataflow and reduce UI flicker.
     if (provider.type == UrlbarUtils.PROVIDER_TYPE.IMMEDIATE) {
       notifyResults();
     } else if (!this._chunkTimer) {
--- a/browser/components/urlbar/moz.build
+++ b/browser/components/urlbar/moz.build
@@ -4,16 +4,17 @@
 
 with Files("**"):
     BUG_COMPONENT = ("Firefox", "Address Bar")
 
 EXTRA_JS_MODULES += [
     'UrlbarController.jsm',
     'UrlbarInput.jsm',
     'UrlbarMatch.jsm',
+    'UrlbarMuxerUnifiedComplete.jsm',
     'UrlbarPrefs.jsm',
     'UrlbarProviderOpenTabs.jsm',
     'UrlbarProvidersManager.jsm',
     'UrlbarProviderUnifiedComplete.jsm',
     'UrlbarTokenizer.jsm',
     'UrlbarUtils.jsm',
     'UrlbarValueFormatter.jsm',
     'UrlbarView.jsm',
--- a/browser/components/urlbar/tests/browser/browser.ini
+++ b/browser/components/urlbar/tests/browser/browser.ini
@@ -4,13 +4,13 @@
 
 [DEFAULT]
 support-files =
   head.js
 
 [browser_UrlbarInput_formatValue.js]
 [browser_UrlbarInput_overflow.js]
 [browser_UrlbarInput_tooltip.js]
-skip-if = asan # Bug 1504985
+skip-if = os == "win" # Bug 1511655
 [browser_UrlbarInput_trimURLs.js]
 subsuite = clipboard
 [browser_UrlbarInput_unit.js]
 support-files = empty.xul
--- a/browser/components/urlbar/tests/browser/browser_UrlbarInput_tooltip.js
+++ b/browser/components/urlbar/tests/browser/browser_UrlbarInput_tooltip.js
@@ -1,73 +1,77 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 "use strict";
 
 function synthesizeMouseOver(element) {
-  window.windowUtils.disableNonTestMouseEvents(true);
-
-  let promise = BrowserTestUtils.waitForEvent(gURLBar.inputField, "mouseover");
+  let promise = BrowserTestUtils.waitForEvent(element, "mouseover");
 
   EventUtils.synthesizeMouse(element, 1, 1, {type: "mouseover"});
   EventUtils.synthesizeMouse(element, 2, 2, {type: "mousemove"});
   EventUtils.synthesizeMouse(element, 3, 3, {type: "mousemove"});
   EventUtils.synthesizeMouse(element, 4, 4, {type: "mousemove"});
 
   return promise;
 }
 
 function synthesizeMouseOut(element) {
-  let promise = BrowserTestUtils.waitForEvent(gURLBar.inputField, "mouseout");
+  let promise = BrowserTestUtils.waitForEvent(element, "mouseout");
 
   EventUtils.synthesizeMouse(element, 0, 0, {type: "mouseout"});
   EventUtils.synthesizeMouseAtCenter(document.documentElement, {type: "mousemove"});
   EventUtils.synthesizeMouseAtCenter(document.documentElement, {type: "mousemove"});
   EventUtils.synthesizeMouseAtCenter(document.documentElement, {type: "mousemove"});
 
-  window.windowUtils.disableNonTestMouseEvents(false);
-
   return promise;
 }
 
 async function expectTooltip(text) {
-  ok(gURLBar.hasAttribute("textoverflow"), "Urlbar is overflowing");
+  if (!gURLBar._overflowing && !gURLBar._inOverflow) {
+    info("waiting for overflow event");
+    await BrowserTestUtils.waitForEvent(gURLBar.inputField, "overflow");
+  }
 
   let tooltip = document.getElementById("aHTMLTooltip");
   let element = gURLBar.inputField;
 
   let popupShownPromise = BrowserTestUtils.waitForEvent(tooltip, "popupshown");
   await synthesizeMouseOver(element);
   await popupShownPromise;
 
   is(element.getAttribute("title"), text, "title attribute has expected text");
   is(tooltip.textContent, text, "tooltip shows expected text");
 
   await synthesizeMouseOut(element);
 }
 
 async function expectNoTooltip() {
-  ok(!gURLBar.hasAttribute("textoverflow"), "Urlbar isn't overflowing");
+  if (gURLBar._overflowing || gURLBar._inOverflow) {
+    info("waiting for underflow event");
+    await BrowserTestUtils.waitForEvent(gURLBar.inputField, "underflow");
+  }
 
   let element = gURLBar.inputField;
   await synthesizeMouseOver(element);
 
   is(element.getAttribute("title"), null, "title attribute shouldn't be set");
 
   await synthesizeMouseOut(element);
 }
 
 add_task(async function() {
+  window.windowUtils.disableNonTestMouseEvents(true);
+  registerCleanupFunction(() => {
+    window.windowUtils.disableNonTestMouseEvents(false);
+  });
+
   // Ensure the URL bar isn't focused.
   gBrowser.selectedBrowser.focus();
 
   gURLBar.value = "short string";
   await expectNoTooltip();
 
   let longURL = "http://longurl.com/" + "foobar/".repeat(30);
-  let overflowPromise = BrowserTestUtils.waitForEvent(gURLBar.inputField, "overflow");
-  await window.promiseDocumentFlushed(() => {});
   gURLBar.value = longURL;
-  await overflowPromise;
   is(gURLBar.inputField.value, longURL.replace(/^http:\/\//, ""), "Urlbar value has http:// stripped");
   await expectTooltip(longURL);
 });
new file mode 100644
--- /dev/null
+++ b/browser/components/urlbar/tests/unit/test_muxer.js
@@ -0,0 +1,76 @@
+/* Any copyright is dedicated to the Public Domain.
+   http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+add_task(async function test_muxer() {
+  Assert.throws(() => UrlbarProvidersManager.registerMuxer(),
+                /invalid muxer/,
+                "Should throw with no arguments");
+  Assert.throws(() => UrlbarProvidersManager.registerMuxer({}),
+                /invalid muxer/,
+                "Should throw with empty object");
+  Assert.throws(() => UrlbarProvidersManager.registerMuxer({
+                  name: "",
+                }),
+                /invalid muxer/,
+                "Should throw with empty name");
+  Assert.throws(() => UrlbarProvidersManager.registerMuxer({
+                  name: "test",
+                  sort: "no",
+                }),
+                /invalid muxer/,
+                "Should throw with invalid sort");
+
+  let matches = [
+    new UrlbarMatch(UrlbarUtils.MATCH_TYPE.TAB_SWITCH,
+                    UrlbarUtils.MATCH_SOURCE.TABS,
+                    { url: "http://mozilla.org/tab/" }),
+    new UrlbarMatch(UrlbarUtils.MATCH_TYPE.URL,
+                    UrlbarUtils.MATCH_SOURCE.BOOKMARKS,
+                    { url: "http://mozilla.org/bookmark/" }),
+    new UrlbarMatch(UrlbarUtils.MATCH_TYPE.URL,
+                    UrlbarUtils.MATCH_SOURCE.HISTORY,
+                    { url: "http://mozilla.org/history/" }),
+  ];
+  registerBasicTestProvider(matches);
+
+  let context = createContext();
+  let controller = new UrlbarController({
+    browserWindow: {
+      location: {
+        href: AppConstants.BROWSER_CHROME_URL,
+      },
+    },
+  });
+  let muxer = {
+    get name() {
+      return "TestMuxer";
+    },
+    sort(queryContext) {
+      queryContext.results.sort((a, b) => {
+        if (b.source == UrlbarUtils.MATCH_SOURCE.TABS) {
+          return -1;
+        }
+        if (b.source == UrlbarUtils.MATCH_SOURCE.BOOKMARKS) {
+          return 1;
+        }
+        return a.source == UrlbarUtils.MATCH_SOURCE.BOOKMARKS ? -1 : 1;
+      });
+    },
+  };
+  UrlbarProvidersManager.registerMuxer(muxer);
+  context.muxer = "TestMuxer";
+
+  info("Check results, the order should be: bookmark, history, tab");
+  await UrlbarProvidersManager.startQuery(context, controller);
+  Assert.deepEqual(context.results, [
+    matches[1],
+    matches[2],
+    matches[0],
+  ]);
+
+  // Sanity check, should not throw.
+  UrlbarProvidersManager.unregisterMuxer(muxer);
+  UrlbarProvidersManager.unregisterMuxer("TestMuxer"); // no-op.
+});
--- a/browser/components/urlbar/tests/unit/test_providersManager.js
+++ b/browser/components/urlbar/tests/unit/test_providersManager.js
@@ -1,14 +1,39 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 "use strict";
 
 add_task(async function test_providers() {
+  Assert.throws(() => UrlbarProvidersManager.registerProvider(),
+                /invalid provider/,
+                "Should throw with no arguments");
+  Assert.throws(() => UrlbarProvidersManager.registerProvider({}),
+                /invalid provider/,
+                "Should throw with empty object");
+  Assert.throws(() => UrlbarProvidersManager.registerProvider({
+                  name: "",
+                }),
+                /invalid provider/,
+                "Should throw with empty name");
+  Assert.throws(() => UrlbarProvidersManager.registerProvider({
+                  name: "test",
+                  startQuery: "no",
+                }),
+                /invalid provider/,
+                "Should throw with invalid startQuery");
+  Assert.throws(() => UrlbarProvidersManager.registerProvider({
+                  name: "test",
+                  startQuery: () => {},
+                  cancelQuery: "no",
+                }),
+                /invalid provider/,
+                "Should throw with invalid cancelQuery");
+
   let match = new UrlbarMatch(UrlbarUtils.MATCH_TYPE.TAB_SWITCH,
                               UrlbarUtils.MATCH_SOURCE.TABS,
                               { url: "http://mozilla.org/foo/" });
   registerBasicTestProvider([match]);
 
   let context = createContext();
   let controller = new UrlbarController({
     browserWindow: {
--- a/browser/components/urlbar/tests/unit/xpcshell.ini
+++ b/browser/components/urlbar/tests/unit/xpcshell.ini
@@ -1,12 +1,13 @@
 [DEFAULT]
 head = head.js
 firefox-appdir = browser
 
+[test_muxer.js]
 [test_providerOpenTabs.js]
 [test_providersManager.js]
 [test_providersManager_filtering.js]
 [test_QueryContext.js]
 [test_tokenizer.js]
 [test_UrlbarController_unit.js]
 [test_UrlbarController_integration.js]
 [test_UrlbarUtils_addToUrlbarHistory.js]
--- a/browser/docs/AddressBar.rst
+++ b/browser/docs/AddressBar.rst
@@ -60,16 +60,20 @@ It is augmented as it progresses through
              // behavior, for example by not autofilling again when the user
              // hit backspace.
     maxResults; // {integer} The maximum number of results requested. The Model
                 // may actually return more results than expected, so that the
                 // View and the Controller can do additional filtering.
     isPrivate; // {boolean} Whether the search started in a private context.
     userContextId; // {integer} The user context ID (containers feature).
 
+    // Optional properties.
+    muxer; // Name of a registered muxer. Muxers can be registered through the
+           // UrlbarProvidersManager
+
     // Properties added by the Model.
     tokens; // {array} tokens extracted from the searchString, each token is an
             // object in the form {type, value}.
     results; // {array} list of UrlbarMatch objects.
     preselected; // {boolean} whether the first match should be preselected.
     autofill; // {boolean} whether the first match is an autofill match.
   }
 
@@ -83,19 +87,20 @@ At the core is the `UrlbarProvidersManag
 a component tracking all the available search providers, and managing searches
 across them.
 
 The *UrlbarProvidersManager* is a singleton, it registers internal providers on
 startup and can register/unregister providers on the fly.
 It can manage multiple concurrent queries, and tracks them internally as
 separate *Query* objects.
 
-The *Controller* starts and stops queries through the *ProvidersManager*. It's
-possible to wait for the promise returned by *startQuery* to know when no more
-matches will be returned, it is not mandatory though. Queries can be canceled.
+The *Controller* starts and stops queries through the *UrlbarProvidersManager*.
+It's possible to wait for the promise returned by *startQuery* to know when no
+more matches will be returned, it is not mandatory though.
+Queries can be canceled.
 
 .. note::
 
   Canceling a query will issue an interrupt() on the database connection,
   terminating any running and future SQL query, unless a query is running inside
   a *runInCriticalSection* task.
 
 The *searchString* gets tokenized by the `UrlbarTokenizer <https://dxr.mozilla.org/mozilla-central/source/browser/components/urlbar/UrlbarTokenizer.jsm>`_
@@ -109,16 +114,18 @@ used by the user to restrict the search 
   consumer may want to check the value before applying filters.
 
 .. highlight:: JavaScript
 .. code::
 
   UrlbarProvidersManager {
     registerProvider(providerObj);
     unregisterProvider(providerObj);
+    registerMuxer(muxerObj);
+    unregisterMuxer(muxerObjOrName);
     async startQuery(queryContext);
     cancelQuery(queryContext);
     // Can be used by providers to run uninterruptible queries.
     runInCriticalSection(taskFn);
   }
 
 UrlbarProvider
 --------------
@@ -155,24 +162,32 @@ implementation details may vary deeply a
     // Any cleaning/resetting task should happen here.
     cancelQuery(QueryContext);
   }
 
 UrlbarMuxer
 -----------
 
 The *Muxer* is responsible for sorting matches based on their importance and
-additional rules that depend on the QueryContext.
+additional rules that depend on the QueryContext. The muxer to use is indicated
+by the QueryContext.muxer property.
 
 .. caution
 
   The Muxer is a replaceable component, as such what is described here is a
   reference for the default View, but may not be valid for other implementations.
 
-*Content to be written*
+.. highlight:: JavaScript
+.. code:
+
+  UrlbarMuxer {
+    name; // {string} A simple name to track the provider.
+    // Invoked by the ProvidersManager to sort matches.
+    sort(queryContext);
+  }
 
 
 The Controller
 ==============
 
 `UrlbarController <https://dxr.mozilla.org/mozilla-central/source/browser/components/urlbar/UrlbarController.jsm>`_
 is the component responsible for reacting to user's input, by communicating
 proper course of action to the Model (e.g. starting/stopping a query) and the
--- a/browser/locales/en-US/chrome/browser/browser.dtd
+++ b/browser/locales/en-US/chrome/browser/browser.dtd
@@ -964,54 +964,26 @@ you can use these alternative items. Oth
 <!ENTITY getUserMedia.audioCapture.label "Audio from the tab will be shared.">
 <!ENTITY getUserMedia.allWindowsShared.message "All visible windows on your screen will be shared.">
 
 <!ENTITY contentBlocking.title "Content Blocking">
 <!ENTITY contentBlocking.detected "Blockable content detected on this site.">
 <!ENTITY contentBlocking.notDetected "No blockable content detected on this page.">
 
 <!ENTITY contentBlocking.trackingProtection3.label "Trackers">
-<!-- LOCALIZATION NOTE (contentBlocking.trackingProtection.allowed.label):
-     This label signals that this type of content blocking is turned
-     OFF and is not blocking tracker content, so this is not
-     a positive thing. It forms the end of the (imaginary) sentence
-     "Trackers [are] Allowed"-->
-<!ENTITY contentBlocking.trackingProtection.allowed.label "Allowed">
-<!-- LOCALIZATION NOTE (contentBlocking.trackingProtection.blocked.label):
-     This label signals that this type of content blocking is turned
-     ON and is successfully blocking tracker content, so this is
-     a positive thing. It forms the end of the (imaginary) sentence
-     "Trackers [are] Blocked"-->
-<!ENTITY contentBlocking.trackingProtection.blocked.label "Blocked">
-
-<!ENTITY contentBlocking.3rdPartyCookies.label "Third-Party Cookies">
-<!ENTITY contentBlocking.3rdPartyCookies.trackers.label "Tracking Cookies">
-<!-- LOCALIZATION NOTE (contentBlocking.3rdPartyCookies.blocked.label):
-     This label signals that this type of content blocking is turned
-     ON and is successfully blocking third-party cookies, so this is
-     a positive thing. It forms the end of the (imaginary) sentence
-     "Third-Party Cookies [are] Blocked"-->
-<!ENTITY contentBlocking.3rdPartyCookies.blocked.label "Blocked">
-<!-- LOCALIZATION NOTE (contentBlocking.tranckingProtection.blocking.label):
-     This label signals that this type of content blocking is turned
-     ON, so this is a positive thing. It forms the verb in the (imaginary) sentence
-     "Firefox is blocking Third-Party Cookies"-->
-<!ENTITY contentBlocking.3rdPartyCookies.blocking.label "Blocking">
-<!-- LOCALIZATION NOTE (contentBlocking.3rdPartyCookies.add.label):
-     This is displayed as a link to preferences, where the user can add
-     this specific type of content blocking. When this text is shown
-     the type of content blocking is currently not enabled. -->
-<!ENTITY contentBlocking.3rdPartyCookies.add.label "Add Blocking…">
 
 <!ENTITY contentBlocking.manageSettings.label "Manage Content Blocking">
 <!ENTITY contentBlocking.manageSettings.accesskey "M">
 
 <!ENTITY contentBlocking.trackersView.label "Trackers">
 <!ENTITY contentBlocking.trackersView.strictInfo.label "To block all trackers, set content blocking to “Strict”.">
 
+<!ENTITY contentBlocking.cookies.label "Cookies">
+<!ENTITY contentBlocking.cookiesView.label "Cookies and Site Data">
+
 <!ENTITY contentBlocking.openBreakageReportView2.label "Report a problem">
 <!ENTITY contentBlocking.breakageReportView.label "Report Problems">
 <!ENTITY contentBlocking.breakageReportView2.description "Content blocking can cause problems with some websites. When you report problems, you’ll help make &brandShortName; better for everyone. (This will send a URL as well as information about your browser settings to Mozilla.)">
 <!ENTITY contentBlocking.breakageReportView.learnMore "Learn More">
 <!ENTITY contentBlocking.breakageReportView.collection.url.label "URL">
 <!ENTITY contentBlocking.breakageReportView.collection.comments.label "What problems did you have? (Optional)">
 <!ENTITY contentBlocking.breakageReportView.sendReport.label "Send Report">
 <!ENTITY contentBlocking.breakageReportView.cancel.label "Cancel">
--- a/browser/locales/en-US/chrome/browser/browser.properties
+++ b/browser/locales/en-US/chrome/browser/browser.properties
@@ -484,16 +484,59 @@ contentBlocking.tooltip=Open Content Blo
 # The terminology used to refer to levels of Content Blocking is also used
 # in preferences and should be translated consistently.
 # LOCALIZATION NOTE (contentBlocking.category.standard):
 # "Standard" in this case is an adjective, meaning "default" or "normal"
 contentBlocking.category.standard=Standard
 contentBlocking.category.strict=Strict
 contentBlocking.category.custom=Custom
 
+# LOCALIZATION NOTE (contentBlocking.trackers.allowed.label):
+#   This label signals that this type of content blocking is turned
+#   OFF and is not blocking tracker content, so this is not
+#   a positive thing. It forms the end of the (imaginary) sentence
+#   "Trackers [are] Allowed"
+contentBlocking.trackers.allowed.label=Allowed
+# LOCALIZATION NOTE (contentBlocking.trackers.blocked.label):
+#   This label signals that this type of content blocking is turned
+#   ON and is successfully blocking tracker content, so this is
+#   a positive thing. It forms the end of the (imaginary) sentence
+#   "Trackers [are] Blocked"
+contentBlocking.trackers.blocked.label=Blocked
+
+# LOCALIZATION NOTE (contentBlocking.trackersView.blocked.label):
+#   This label is shown next to a tracker in the trackers subview.
+#   It forms the end of the (imaginary) sentence "www.example.com [was] Blocked"
+contentBlocking.trackersView.blocked.label=Blocked
+
+# LOCALIZATION NOTE (contentBlocking.cookies.allowed.label):
+#   This label signals that this type of content blocking is turned
+#   OFF and is not blocking tracker content, so this is not
+#   a positive thing. It forms the end of the (imaginary) sentence
+#   "Cookies [are] Allowed"
+contentBlocking.cookies.allowed.label=Allowed
+contentBlocking.cookies.trackersBlocked.label=Tracking Cookies Blocked
+contentBlocking.cookies.3rdPartyBlocked.label=Third-Party Cookies Blocked
+contentBlocking.cookies.unvisitedBlocked.label=Unvisited Site Cookies Blocked
+contentBlocking.cookies.allBlocked.label=All Cookies Blocked
+
+contentBlocking.cookiesView.firstParty.label=From This Site
+contentBlocking.cookiesView.trackers.label=Tracking Cookies
+contentBlocking.cookiesView.thirdParty.label=Third-Party Cookies
+# LOCALIZATION NOTE (contentBlocking.cookiesView.allowed.label):
+#   This label is shown next to a cookie origin in the cookies subview.
+#   It forms the end of the (imaginary) sentence "www.example.com [was] Allowed"
+contentBlocking.cookiesView.allowed.label=Allowed
+# LOCALIZATION NOTE (contentBlocking.cookiesView.blocked.label):
+#   This label is shown next to a cookie origin in the cookies subview.
+#   It forms the end of the (imaginary) sentence "www.example.com [was] Blocked"
+contentBlocking.cookiesView.blocked.label=Blocked
+# LOCALIZATION NOTE (contentBlocking.cookiesView.removeButton.tooltip): %S is the domain of the site.
+contentBlocking.cookiesView.removeButton.tooltip=Clear cookie exception for %S
+
 # LOCALIZATION NOTE (contentBlocking.intro.title): %S is brandShortName.
 contentBlocking.intro.title=New in %S: Content Blocking
 # LOCALIZATION NOTE (contentBlocking.v1.intro.description): %S is brandShortName.
 contentBlocking.intro.v1.description=When you see the shield, %S is blocking parts of the page that can slow your browsing or track you online.
 contentBlocking.intro.v2.description=The privacy benefits of Tracking Protection are now just one part of content blocking. When you see the shield, content blocking is on.
 # LOCALIZATION NOTE (trackingProtection.intro.step1of3): Indicates that the intro panel is step one of three in a tour.
 trackingProtection.intro.step1of3=1 of 3
 trackingProtection.intro.nextButton.label=Next
--- a/browser/themes/shared/controlcenter/panel.inc.css
+++ b/browser/themes/shared/controlcenter/panel.inc.css
@@ -160,17 +160,18 @@
 }
 
 /* CONTENT */
 
 #tracking-protection-preferences-button > .toolbarbutton-text,
 .identity-popup-footer,
 .tracking-protection-button,
 #identity-popup-trackersView-strict-info > label,
-.identity-popup-trackersView-list-item > label,
+.identity-popup-cookiesView-list-header,
+.identity-popup-content-blocking-list-item > label,
 #identity-popup-mainView-panel-header > label,
 #identity-popup-trackersView > .panel-header,
 #identity-popup-securityView > .panel-header,
 #identity-popup-breakageReportView > .panel-header,
 #identity-popup-content-blocking-report-breakage,
 .identity-popup-content-blocking-category-label,
 .identity-popup-content-blocking-category-state-label,
 .identity-popup-content-blocking-category-add-blocking,
@@ -398,76 +399,105 @@ description#identity-popup-content-verif
 #identity-popup-breakageReportView-collection-comments {
   height: 120px;
 }
 
 #identity-popup-content-blocking-content {
   background-image: url("chrome://browser/skin/controlcenter/tracking-protection.svg");
 }
 
-#identity-popup-content-blocking-category-tracking-protection {
+.identity-popup-content-blocking-category {
   /* Overwrite toolbarbutton styles */
   -moz-appearance: none;
   margin: 0;
   padding-inline-start: 0;
 }
 
-#identity-popup-content-blocking-category-tracking-protection:-moz-focusring,
-#identity-popup-content-blocking-category-tracking-protection:hover {
+.identity-popup-content-blocking-category:-moz-focusring,
+.identity-popup-content-blocking-category:hover {
   border-radius: 2px;
+  background-color: var(--arrowpanel-dimmed);
+}
+
+.identity-popup-content-blocking-category:hover:active {
   background-color: var(--arrowpanel-dimmed-further);
 }
 
-#identity-popup-content-blocking-category-tracking-protection:hover:active {
-  background-color: var(--arrowpanel-dimmed-even-further);
-}
-
-#identity-popup-content-blocking-category-tracking-protection::after {
+.identity-popup-content-blocking-category::after {
   content: url(chrome://browser/skin/back-12.svg);
   -moz-context-properties: fill, fill-opacity;
   transform: scaleX(-1) translateY(1px);
   float: right;
 }
 
-#identity-popup-content-blocking-category-tracking-protection:-moz-locale-dir(rtl)::after {
+.identity-popup-content-blocking-category:-moz-locale-dir(rtl)::after {
   transform: scaleX(1) translateY(1px);
 }
 
 /* This subview could get filled with a lot of trackers, set a maximum size
  * and allow it to scroll vertically.*/
+#identity-popup-cookiesView,
 #identity-popup-trackersView {
   max-height: 600px;
 }
 
-#identity-popup-trackersView-list {
+.identity-popup-cookiesView-list-header {
+  color: var(--panel-disabled-color);
+  margin: 5px 0;
+}
+
+.identity-popup-content-blocking-list {
   padding: 5px 20px;
   -moz-box-flex: 1;
   overflow: auto;
 }
 
-.identity-popup-trackersView-list-item {
+.identity-popup-content-blocking-list-item {
   margin: 5px 0;
   overflow: hidden;
+  -moz-box-align: center;
+}
+
+.identity-popup-content-blocking-list-item:not(.allowed) {
+  color: var(--panel-disabled-color);
 }
 
-.identity-popup-trackersView-list-item > label {
-  /* Limit to full width - container padding - icon width - icon margin */
-  max-width: calc(var(--identity-popup-width) - 40px - 16px - 10px);
+.identity-popup-content-blocking-list-host-label {
+  -moz-box-flex: 1;
 }
 
-.identity-popup-trackersView-list-item > image {
-  list-style-image: url(chrome://browser/skin/controlcenter/trackers-disabled.svg);
+.identity-popup-content-blocking-list-state-label {
+  -moz-box-flex: 1;
+  text-align: end;
+  margin-inline-start: 5px;
+  margin-inline-end: 2px;
+}
+
+.identity-popup-trackersView-icon,
+.identity-popup-cookiesView-icon {
   margin-inline-end: 10px;
   -moz-context-properties: fill, fill-opacity;
 }
 
-.identity-popup-trackersView-list-item.allowed > image {
+.identity-popup-trackersView-icon {
+  list-style-image: url(chrome://browser/skin/controlcenter/trackers-disabled.svg);
+}
+
+.identity-popup-trackersView-icon.allowed {
   list-style-image: url(chrome://browser/skin/controlcenter/trackers.svg);
 }
 
+.identity-popup-cookiesView-icon {
+  list-style-image: url(chrome://browser/skin/controlcenter/3rdpartycookies-disabled.svg);
+}
+
+.identity-popup-cookiesView-icon.allowed {
+  list-style-image: url(chrome://browser/skin/controlcenter/3rdpartycookies.svg);
+}
+
 #identity-popup-trackersView-strict-info {
   min-height: 40px;
   /* Limit to full width - margin */
   max-width: calc(var(--identity-popup-width) - 12px);
   min-width: calc(var(--identity-popup-width) - 12px);
   background-color: #45a1ff80;
   margin: 6px;
   text-align: center;
@@ -492,61 +522,30 @@ description#identity-popup-content-verif
 }
 
 /* Content Blocking categories */
 
 #identity-popup-content-blocking-category-list {
   margin-top: 10px;
 }
 
-/* Don't show the categories when no trackers were detected. */
-#identity-popup-content-blocking-content:not([detected]) > #identity-popup-content-blocking-category-list {
-  display: none;
-}
-
 /* Show the "detected"/"not detected" message depending on the content state. */
 #identity-popup-content-blocking-content:not([detected]) > #identity-popup-content-blocking-detected,
 #identity-popup-content-blocking-content[detected] > #identity-popup-content-blocking-not-detected {
   display: none;
 }
 
-.identity-popup-content-blocking-category-state-label {
-  display: none;
-}
-
-/* TODO: This will be cleaned up by bug 1501992 */
-/* Hide the state label unless we blocked something only for third party cookies */
-#identity-popup-content-blocking-content:not([hasException]) #identity-popup-content-blocking-category-3rdpartycookies.blocked .identity-popup-content-blocking-category-state-label,
-/* For trackers, either show a "blocked" or "allowed" label depending on the state. */
-#identity-popup-content-blocking-content:not([hasException]) #identity-popup-content-blocking-category-tracking-protection.blocked > #identity-popup-content-blocking-tracking-protection-label-blocked,
-#identity-popup-content-blocking-category-tracking-protection:not(.blocked) > #identity-popup-content-blocking-tracking-protection-label-allowed,
-#identity-popup-content-blocking-content[hasException] #identity-popup-content-blocking-tracking-protection-label-allowed {
-  display: -moz-box;
-}
-
-.identity-popup-content-blocking-category.blocked .identity-popup-content-blocking-category-add-blocking {
-  display: none;
-}
-
 .tracking-protection-icon {
   list-style-image: url(chrome://browser/skin/controlcenter/trackers.svg);
 }
 
-#identity-popup-content-blocking-category-tracking-protection.blocked > .tracking-protection-icon {
-  list-style-image: url(chrome://browser/skin/controlcenter/trackers-disabled.svg);
-}
-
 .thirdpartycookies-icon {
   list-style-image: url(chrome://browser/skin/controlcenter/3rdpartycookies.svg);
 }
 
-#identity-popup-content-blocking-category-3rdpartycookies.blocked > .thirdpartycookies-icon {
-  list-style-image: url(chrome://browser/skin/controlcenter/3rdpartycookies-disabled.svg);
-}
-
 /* Content Blocking action button */
 
 .tracking-protection-button {
   list-style-image: url(chrome://browser/skin/tracking-protection.svg);
   -moz-appearance: none;
   margin: 1em 0 0;
   display: none;
   height: 32px;
@@ -593,25 +592,25 @@ description#identity-popup-content-verif
 
 #identity-popup-content-blocking-report-breakage {
   margin-top: 6px;
 }
 
 /* Hide the "report breakage" button if we have not detected any trackers
  * (except if the user added an exception, in which case they might still
  * (especially!) want to report the breakage). */
-#identity-popup-content-blocking-content:not([active]):not([hasException]) #identity-popup-content-blocking-report-breakage {
+#identity-popup-content-blocking-content:not([blocking]):not([hasException]) #identity-popup-content-blocking-report-breakage {
   display: none;
 }
 
 /* Show the right action buttons depending on content state */
 /* Offer to temporarily add an exception in private mode. */
-#main-window:not([privatebrowsingmode]) #identity-popup-content-blocking-content[active]:not([hasException]) > #tracking-action-unblock,
+#main-window:not([privatebrowsingmode]) #identity-popup-content-blocking-content[blocking]:not([hasException]) > #tracking-action-unblock,
 /* Offer to permanently add an exception in normal mode. */
-#main-window[privatebrowsingmode] #identity-popup-content-blocking-content[active]:not([hasException]) > #tracking-action-unblock-private,
+#main-window[privatebrowsingmode] #identity-popup-content-blocking-content[blocking]:not([hasException]) > #tracking-action-unblock-private,
 /* If there's an exception just offer to remove the exception again. */
 #identity-popup-content-blocking-content[hasException] > #tracking-action-block {
   display: -moz-box;
 }
 
 /* PERMISSIONS */
 
 #identity-popup-permissions-content {
@@ -713,16 +712,17 @@ description#identity-popup-content-verif
   margin: 0;
   border-width: 0;
   border-radius: 50%;
   min-width: 0;
   padding: 2px;
   background-color: transparent;
   color: inherit;
   opacity: 0.6;
+  margin-inline-start: 2px;
 }
 
 .identity-popup-permission-remove-button > .button-box {
   padding: 0;
 }
 
 .identity-popup-permission-remove-button > .button-box > .button-icon {
   margin: 0;
--- a/layout/base/nsPresContext.cpp
+++ b/layout/base/nsPresContext.cpp
@@ -1749,21 +1749,16 @@ void nsPresContext::PostRebuildAllStyleD
                                                  nsRestyleHint aRestyleHint) {
   if (!mShell) {
     // We must have been torn down. Nothing to do here.
     return;
   }
   RestyleManager()->PostRebuildAllStyleDataEvent(aExtraHint, aRestyleHint);
 }
 
-struct MediaFeatureHints {
-  nsRestyleHint restyleHint;
-  nsChangeHint changeHint;
-};
-
 static bool MediaFeatureValuesChangedAllDocumentsCallback(
     nsIDocument* aDocument, void* aChange) {
   auto* change = static_cast<const MediaFeatureChange*>(aChange);
   if (nsPresContext* pc = aDocument->GetPresContext()) {
     pc->MediaFeatureValuesChangedAllDocuments(*change);
   }
   return true;
 }
deleted file mode 100644
--- a/third_party/rust/quote-0.3.15/.cargo-checksum.json
+++ /dev/null
@@ -1,1 +0,0 @@
-{"files":{"Cargo.toml":"983b4a016a497eded8adc6a23963343693ab4520826a1bc916e6f8448c9bb309","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"c9a75f18b9ab2927829a208fc6aa2cf4e63b8420887ba29cdb265d6619ae82d5","README.md":"3390fa1362c73052a268ae97a4777c5bcd8e991f866f9cce88ddde8d0963fd4d","src/ident.rs":"830077b64dce8c8ede1fb6ab664cae72f5496f4ab6be21a5b4e3b5e4e57ec425","src/lib.rs":"f799c898057a4e8e1620b32c70e13d3fee7af3a0352a5a4a1da6393942d21cc7","src/to_tokens.rs":"a871cb84506fa9e0783ac29617d686327ce5d05a9711a3a10833430b00345ccc","src/tokens.rs":"9a6010d7c0c6ccbe8b7bb1dae99722c91fc0559ea6ac6ea03ab2baafc2ec77ae","tests/test.rs":"8951d46b62d6922cc5fc130759be9723a862947738dda25cc84ff8cfdfebf729"},"package":"7a6e920b65c65f10b2ae65c831a81a073a89edd28c7cce89475bff467ab4167a"}
\ No newline at end of file
deleted file mode 100644
--- a/third_party/rust/quote-0.3.15/Cargo.toml
+++ /dev/null
@@ -1,10 +0,0 @@
-[package]
-name = "quote"
-version = "0.3.15" # don't forget to update version in readme for breaking changes
-authors = ["David Tolnay <dtolnay@gmail.com>"]
-license = "MIT/Apache-2.0"
-description = "Quasi-quoting macro quote!(...)"
-repository = "https://github.com/dtolnay/quote"
-documentation = "https://docs.rs/quote/"
-keywords = ["syn"]
-include = ["Cargo.toml", "src/**/*.rs", "tests/**/*.rs", "README.md", "LICENSE-APACHE", "LICENSE-MIT"]
deleted file mode 100644
--- a/third_party/rust/quote-0.3.15/LICENSE-APACHE
+++ /dev/null
@@ -1,201 +0,0 @@
-                              Apache License
-                        Version 2.0, January 2004
-                     http://www.apache.org/licenses/
-
-TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
-1. Definitions.
-
-   "License" shall mean the terms and conditions for use, reproduction,
-   and distribution as defined by Sections 1 through 9 of this document.
-
-   "Licensor" shall mean the copyright owner or entity authorized by
-   the copyright owner that is granting the License.
-
-   "Legal Entity" shall mean the union of the acting entity and all
-   other entities that control, are controlled by, or are under common
-   control with that entity. For the purposes of this definition,
-   "control" means (i) the power, direct or indirect, to cause the
-   direction or management of such entity, whether by contract or
-   otherwise, or (ii) ownership of fifty percent (50%) or more of the
-   outstanding shares, or (iii) beneficial ownership of such entity.
-
-   "You" (or "Your") shall mean an individual or Legal Entity
-   exercising permissions granted by this License.
-
-   "Source" form shall mean the preferred form for making modifications,
-   including but not limited to software source code, documentation
-   source, and configuration files.
-
-   "Object" form shall mean any form resulting from mechanical
-   transformation or translation of a Source form, including but
-   not limited to compiled object code, generated documentation,
-   and conversions to other media types.
-
-   "Work" shall mean the work of authorship, whether in Source or
-   Object form, made available under the License, as indicated by a
-   copyright notice that is included in or attached to the work
-   (an example is provided in the Appendix below).
-
-   "Derivative Works" shall mean any work, whether in Source or Object
-   form, that is based on (or derived from) the Work and for which the
-   editorial revisions, annotations, elaborations, or other modifications
-   represent, as a whole, an original work of authorship. For the purposes
-   of this License, Derivative Works shall not include works that remain
-   separable from, or merely link (or bind by name) to the interfaces of,
-   the Work and Derivative Works thereof.
-
-   "Contribution" shall mean any work of authorship, including
-   the original version of the Work and any modifications or additions
-   to that Work or Derivative Works thereof, that is intentionally
-   submitted to Licensor for inclusion in the Work by the copyright owner
-   or by an individual or Legal Entity authorized to submit on behalf of
-   the copyright owner. For the purposes of this definition, "submitted"
-   means any form of electronic, verbal, or written communication sent
-   to the Licensor or its representatives, including but not limited to
-   communication on electronic mailing lists, source code control systems,
-   and issue tracking systems that are managed by, or on behalf of, the
-   Licensor for the purpose of discussing and improving the Work, but
-   excluding communication that is conspicuously marked or otherwise
-   designated in writing by the copyright owner as "Not a Contribution."
-
-   "Contributor" shall mean Licensor and any individual or Legal Entity
-   on behalf of whom a Contribution has been received by Licensor and
-   subsequently incorporated within the Work.
-
-2. Grant of Copyright License. Subject to the terms and conditions of
-   this License, each Contributor hereby grants to You a perpetual,
-   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-   copyright license to reproduce, prepare Derivative Works of,
-   publicly display, publicly perform, sublicense, and distribute the
-   Work and such Derivative Works in Source or Object form.
-
-3. Grant of Patent License. Subject to the terms and conditions of
-   this License, each Contributor hereby grants to You a perpetual,
-   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-   (except as stated in this section) patent license to make, have made,
-   use, offer to sell, sell, import, and otherwise transfer the Work,
-   where such license applies only to those patent claims licensable
-   by such Contributor that are necessarily infringed by their
-   Contribution(s) alone or by combination of their Contribution(s)
-   with the Work to which such Contribution(s) was submitted. If You
-   institute patent litigation against any entity (including a
-   cross-claim or counterclaim in a lawsuit) alleging that the Work
-   or a Contribution incorporated within the Work constitutes direct
-   or contributory patent infringement, then any patent licenses
-   granted to You under this License for that Work shall terminate
-   as of the date such litigation is filed.
-
-4. Redistribution. You may reproduce and distribute copies of the
-   Work or Derivative Works thereof in any medium, with or without
-   modifications, and in Source or Object form, provided that You
-   meet the following conditions:
-
-   (a) You must give any other recipients of the Work or
-       Derivative Works a copy of this License; and
-
-   (b) You must cause any modified files to carry prominent notices
-       stating that You changed the files; and
-
-   (c) You must retain, in the Source form of any Derivative Works
-       that You distribute, all copyright, patent, trademark, and
-       attribution notices from the Source form of the Work,
-       excluding those notices that do not pertain to any part of
-       the Derivative Works; and
-
-   (d) If the Work includes a "NOTICE" text file as part of its
-       distribution, then any Derivative Works that You distribute must
-       include a readable copy of the attribution notices contained
-       within such NOTICE file, excluding those notices that do not
-       pertain to any part of the Derivative Works, in at least one
-       of the following places: within a NOTICE text file distributed
-       as part of the Derivative Works; within the Source form or
-       documentation, if provided along with the Derivative Works; or,
-       within a display generated by the Derivative Works, if and
-       wherever such third-party notices normally appear. The contents
-       of the NOTICE file are for informational purposes only and
-       do not modify the License. You may add Your own attribution
-       notices within Derivative Works that You distribute, alongside
-       or as an addendum to the NOTICE text from the Work, provided
-       that such additional attribution notices cannot be construed
-       as modifying the License.
-
-   You may add Your own copyright statement to Your modifications and
-   may provide additional or different license terms and conditions
-   for use, reproduction, or distribution of Your modifications, or
-   for any such Derivative Works as a whole, provided Your use,
-   reproduction, and distribution of the Work otherwise complies with
-   the conditions stated in this License.
-
-5. Submission of Contributions. Unless You explicitly state otherwise,
-   any Contribution intentionally submitted for inclusion in the Work
-   by You to the Licensor shall be under the terms and conditions of
-   this License, without any additional terms or conditions.
-   Notwithstanding the above, nothing herein shall supersede or modify
-   the terms of any separate license agreement you may have executed
-   with Licensor regarding such Contributions.
-
-6. Trademarks. This License does not grant permission to use the trade
-   names, trademarks, service marks, or product names of the Licensor,
-   except as required for reasonable and customary use in describing the
-   origin of the Work and reproducing the content of the NOTICE file.
-
-7. Disclaimer of Warranty. Unless required by applicable law or
-   agreed to in writing, Licensor provides the Work (and each
-   Contributor provides its Contributions) on an "AS IS" BASIS,
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-   implied, including, without limitation, any warranties or conditions
-   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
-   PARTICULAR PURPOSE. You are solely responsible for determining the
-   appropriateness of using or redistributing the Work and assume any
-   risks associated with Your exercise of permissions under this License.
-
-8. Limitation of Liability. In no event and under no legal theory,
-   whether in tort (including negligence), contract, or otherwise,
-   unless required by applicable law (such as deliberate and grossly
-   negligent acts) or agreed to in writing, shall any Contributor be
-   liable to You for damages, including any direct, indirect, special,
-   incidental, or consequential damages of any character arising as a
-   result of this License or out of the use or inability to use the
-   Work (including but not limited to damages for loss of goodwill,
-   work stoppage, computer failure or malfunction, or any and all
-   other commercial damages or losses), even if such Contributor
-   has been advised of the possibility of such damages.
-
-9. Accepting Warranty or Additional Liability. While redistributing
-   the Work or Derivative Works thereof, You may choose to offer,
-   and charge a fee for, acceptance of support, warranty, indemnity,
-   or other liability obligations and/or rights consistent with this
-   License. However, in accepting such obligations, You may act only
-   on Your own behalf and on Your sole responsibility, not on behalf
-   of any other Contributor, and only if You agree to indemnify,
-   defend, and hold each Contributor harmless for any liability
-   incurred by, or claims asserted against, such Contributor by reason
-   of your accepting any such warranty or additional liability.
-
-END OF TERMS AND CONDITIONS
-
-APPENDIX: How to apply the Apache License to your work.
-
-   To apply the Apache License to your work, attach the following
-   boilerplate notice, with the fields enclosed by brackets "[]"
-   replaced with your own identifying information. (Don't include
-   the brackets!)  The text should be enclosed in the appropriate
-   comment syntax for the file format. We also recommend that a
-   file or class name and description of purpose be included on the
-   same "printed page" as the copyright notice for easier
-   identification within third-party archives.
-
-Copyright [yyyy] [name of copyright owner]
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
-	http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
deleted file mode 100644
--- a/third_party/rust/quote-0.3.15/LICENSE-MIT
+++ /dev/null
@@ -1,25 +0,0 @@
-Copyright (c) 2016 The Rust Project Developers
-
-Permission is hereby granted, free of charge, to any
-person obtaining a copy of this software and associated
-documentation files (the "Software"), to deal in the
-Software without restriction, including without
-limitation the rights to use, copy, modify, merge,
-publish, distribute, sublicense, and/or sell copies of
-the Software, and to permit persons to whom the Software
-is furnished to do so, subject to the following
-conditions:
-
-The above copyright notice and this permission notice
-shall be included in all copies or substantial portions
-of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
-ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
-TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
-PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
-SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
-CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
-IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-DEALINGS IN THE SOFTWARE.
deleted file mode 100644
--- a/third_party/rust/quote-0.3.15/README.md
+++ /dev/null
@@ -1,104 +0,0 @@
-Rust Quasi-Quoting
-==================
-
-[![Build Status](https://api.travis-ci.org/dtolnay/quote.svg?branch=master)](https://travis-ci.org/dtolnay/quote)
-[![Latest Version](https://img.shields.io/crates/v/quote.svg)](https://crates.io/crates/quote)
-[![Rust Documentation](https://img.shields.io/badge/api-rustdoc-blue.svg)](https://docs.rs/quote/)
-
-Quasi-quoting without a Syntex dependency, intended for use with [Macros
-1.1](https://github.com/rust-lang/rfcs/blob/master/text/1681-macros-1.1.md).
-
-```toml
-[dependencies]
-quote = "0.3"
-```
-
-```rust
-#[macro_use]
-extern crate quote;
-```
-
-## What is quasi-quoting?
-
-Quasi-quoting is a way of writing code and treating it as data, similar to
-writing code inside of a double-quoted string literal except more friendly to
-your text editor or IDE. It does not get in the way of syntax highlighting,
-brace matching, indentation, or autocompletion, all of which you would lose by
-writing code inside of double quotes.
-
-Check out
-[my meetup talk](https://air.mozilla.org/rust-meetup-december-2016-12-15/)
-on the topic to learn more about the use case. Start the video at 3:00.
-
-This crate is motivated by the Macros 1.1 use case, but is a general-purpose
-Rust quasi-quoting library and is not specific to procedural macros.
-
-## Syntax
-
-The quote crate provides a `quote!` macro within which you can write Rust code
-that gets packaged into a `quote::Tokens` and can be treated as data. You should
-think of `quote::Tokens` as representing a fragment of Rust source code. Call
-`to_string()` or `as_str()` on a Tokens to get back the fragment of source code
-as a string.
-
-Within the `quote!` macro, interpolation is done with `#var`. Any type
-implementing the `quote::ToTokens` trait can be interpolated. This includes most
-Rust primitive types as well as most of the syntax tree types from
-[`syn`](https://github.com/dtolnay/syn).
-
-```rust
-let tokens = quote! {
-    struct SerializeWith #generics #where_clause {
-        value: &'a #field_ty,
-        phantom: ::std::marker::PhantomData<#item_ty>,
-    }
-
-    impl #generics serde::Serialize for SerializeWith #generics #where_clause {
-        fn serialize<S>(&self, s: &mut S) -> Result<(), S::Error>
-            where S: serde::Serializer
-        {
-            #path(self.value, s)
-        }
-    }
-
-    SerializeWith {
-        value: #value,
-        phantom: ::std::marker::PhantomData::<#item_ty>,
-    }
-};
-```
-
-Repetition is done using `#(...)*` or `#(...),*` very similar to `macro_rules!`:
-
-- `#(#var)*` - no separators
-- `#(#var),*` - the character before the asterisk is used as a separator
-- `#( struct #var; )*` - the repetition can contain other things
-- `#( #k => println!("{}", #v), )*` - even multiple interpolations
-
-Tokens can be interpolated into other quotes:
-
-```rust
-let t = quote! { /* ... */ };
-return quote! { /* ... */ #t /* ... */ };
-```
-
-The `quote!` macro relies on deep recursion so some large invocations may fail
-with "recursion limit reached" when you compile. If it fails, bump up the
-recursion limit by adding `#![recursion_limit = "128"]` to your crate. An even
-higher limit may be necessary for especially large invocations. You don't need
-this unless the compiler tells you that you need it.
-
-## License
-
-Licensed under either of
-
- * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
- * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
-
-at your option.
-
-### Contribution
-
-Unless you explicitly state otherwise, any contribution intentionally submitted
-for inclusion in this crate by you, as defined in the Apache-2.0 license, shall
-be dual licensed as above, without any additional terms or conditions.
deleted file mode 100644
--- a/third_party/rust/quote-0.3.15/src/ident.rs
+++ /dev/null
@@ -1,57 +0,0 @@
-use {Tokens, ToTokens};
-use std::borrow::Cow;
-use std::fmt;
-
-/// An identifier that should be interpolated without quotes.
-#[derive(Debug, Clone, Eq, Hash)]
-pub struct Ident(String);
-
-impl Ident {
-    pub fn new<T: Into<Ident>>(t: T) -> Self {
-        t.into()
-    }
-}
-
-impl<'a> From<&'a str> for Ident {
-    fn from(s: &str) -> Self {
-        Ident(s.to_owned())
-    }
-}
-
-impl<'a> From<Cow<'a, str>> for Ident {
-    fn from(s: Cow<'a, str>) -> Self {
-        Ident(s.into_owned())
-    }
-}
-
-impl From<String> for Ident {
-    fn from(s: String) -> Self {
-        Ident(s)
-    }
-}
-
-impl AsRef<str> for Ident {
-    fn as_ref(&self) -> &str {
-        &self.0
-    }
-}
-
-impl fmt::Display for Ident {
-    fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
-        self.0.fmt(formatter)
-    }
-}
-
-impl<T: ?Sized> PartialEq<T> for Ident
-    where T: AsRef<str>
-{
-    fn eq(&self, other: &T) -> bool {
-        self.0 == other.as_ref()
-    }
-}
-
-impl ToTokens for Ident {
-    fn to_tokens(&self, tokens: &mut Tokens) {
-        tokens.append(self.as_ref())
-    }
-}
deleted file mode 100644
--- a/third_party/rust/quote-0.3.15/src/lib.rs
+++ /dev/null
@@ -1,252 +0,0 @@
-//! Quasi-quoting without a Syntex dependency, intended for use with [Macros
-//! 1.1](https://github.com/rust-lang/rfcs/blob/master/text/1681-macros-1.1.md).
-//!
-//! ```toml
-//! [dependencies]
-//! quote = "0.3"
-//! ```
-//!
-//! ```rust,ignore
-//! #[macro_use]
-//! extern crate quote;
-//! ```
-//!
-//! Interpolation is done with `#var`:
-//!
-//! ```text
-//! let tokens = quote! {
-//!     struct SerializeWith #generics #where_clause {
-//!         value: &'a #field_ty,
-//!         phantom: ::std::marker::PhantomData<#item_ty>,
-//!     }
-//!
-//!     impl #generics serde::Serialize for SerializeWith #generics #where_clause {
-//!         fn serialize<S>(&self, s: &mut S) -> Result<(), S::Error>
-//!             where S: serde::Serializer
-//!         {
-//!             #path(self.value, s)
-//!         }
-//!     }
-//!
-//!     SerializeWith {
-//!         value: #value,
-//!         phantom: ::std::marker::PhantomData::<#item_ty>,
-//!     }
-//! };
-//! ```
-//!
-//! Repetition is done using `#(...)*` or `#(...),*` very similar to `macro_rules!`:
-//!
-//! - `#(#var)*` - no separators
-//! - `#(#var),*` - the character before the asterisk is used as a separator
-//! - `#( struct #var; )*` - the repetition can contain other things
-//! - `#( #k => println!("{}", #v), )*` - even multiple interpolations
-//!
-//! The return type of `quote!` is `quote::Tokens`. Tokens can be interpolated into
-//! other quotes:
-//!
-//! ```text
-//! let t = quote! { /* ... */ };
-//! return quote! { /* ... */ #t /* ... */ };
-//! ```
-//!
-//! Call `to_string()` or `as_str()` on a Tokens to get a `String` or `&str` of Rust
-//! code.
-//!
-//! The `quote!` macro relies on deep recursion so some large invocations may fail
-//! with "recursion limit reached" when you compile. If it fails, bump up the
-//! recursion limit by adding `#![recursion_limit = "128"]` to your crate. An even
-//! higher limit may be necessary for especially large invocations.
-
-mod tokens;
-pub use tokens::Tokens;
-
-mod to_tokens;
-pub use to_tokens::{ToTokens, ByteStr, Hex};
-
-mod ident;
-pub use ident::Ident;
-
-/// The whole point.
-#[macro_export]
-macro_rules! quote {
-    () => {
-        $crate::Tokens::new()
-    };
-
-    ($($tt:tt)+) => {
-        {
-            let mut _s = $crate::Tokens::new();
-            quote_each_token!(_s $($tt)*);
-            _s
-        }
-    };
-}
-
-// Extract the names of all #metavariables and pass them to the $finish macro.
-//
-// in:   pounded_var_names!(then () a #b c #( #d )* #e)
-// out:  then!(() b d e)
-#[macro_export]
-#[doc(hidden)]
-macro_rules! pounded_var_names {
-    ($finish:ident ($($found:ident)*) # ( $($inner:tt)* ) $($rest:tt)*) => {
-        pounded_var_names!($finish ($($found)*) $($inner)* $($rest)*)
-    };
-
-    ($finish:ident ($($found:ident)*) # [ $($inner:tt)* ] $($rest:tt)*) => {
-        pounded_var_names!($finish ($($found)*) $($inner)* $($rest)*)
-    };
-
-    ($finish:ident ($($found:ident)*) # { $($inner:tt)* } $($rest:tt)*) => {
-        pounded_var_names!($finish ($($found)*) $($inner)* $($rest)*)
-    };
-
-    ($finish:ident ($($found:ident)*) # $first:ident $($rest:tt)*) => {
-        pounded_var_names!($finish ($($found)* $first) $($rest)*)
-    };
-
-    ($finish:ident ($($found:ident)*) ( $($inner:tt)* ) $($rest:tt)*) => {
-        pounded_var_names!($finish ($($found)*) $($inner)* $($rest)*)
-    };
-
-    ($finish:ident ($($found:ident)*) [ $($inner:tt)* ] $($rest:tt)*) => {
-        pounded_var_names!($finish ($($found)*) $($inner)* $($rest)*)
-    };
-
-    ($finish:ident ($($found:ident)*) { $($inner:tt)* } $($rest:tt)*) => {
-        pounded_var_names!($finish ($($found)*) $($inner)* $($rest)*)
-    };
-
-    ($finish:ident ($($found:ident)*) $ignore:tt $($rest:tt)*) => {
-        pounded_var_names!($finish ($($found)*) $($rest)*)
-    };
-
-    ($finish:ident ($($found:ident)*)) => {
-        $finish!(() $($found)*)
-    };
-}
-
-// in:   nested_tuples_pat!(() a b c d e)
-// out:  ((((a b) c) d) e)
-//
-// in:   nested_tuples_pat!(() a)
-// out:  a
-#[macro_export]
-#[doc(hidden)]
-macro_rules! nested_tuples_pat {
-    (()) => {
-        &()
-    };
-
-    (() $first:ident $($rest:ident)*) => {
-        nested_tuples_pat!(($first) $($rest)*)
-    };
-
-    (($pat:pat) $first:ident $($rest:ident)*) => {
-        nested_tuples_pat!((($pat, $first)) $($rest)*)
-    };
-
-    (($done:pat)) => {
-        $done
-    };
-}
-
-// in:   multi_zip_expr!(() a b c d e)
-// out:  a.into_iter().zip(b).zip(c).zip(d).zip(e)
-//
-// in:   multi_zip_iter!(() a)
-// out:  a
-#[macro_export]
-#[doc(hidden)]
-macro_rules! multi_zip_expr {
-    (()) => {
-        &[]
-    };
-
-    (() $single:ident) => {
-        $single
-    };
-
-    (() $first:ident $($rest:ident)*) => {
-        multi_zip_expr!(($first.into_iter()) $($rest)*)
-    };
-
-    (($zips:expr) $first:ident $($rest:ident)*) => {
-        multi_zip_expr!(($zips.zip($first)) $($rest)*)
-    };
-
-    (($done:expr)) => {
-        $done
-    };
-}
-
-#[macro_export]
-#[doc(hidden)]
-macro_rules! quote_each_token {
-    ($tokens:ident) => {};
-
-    ($tokens:ident # ! $($rest:tt)*) => {
-        $tokens.append("#");
-        $tokens.append("!");
-        quote_each_token!($tokens $($rest)*);
-    };
-
-    ($tokens:ident # ( $($inner:tt)* ) * $($rest:tt)*) => {
-        for pounded_var_names!(nested_tuples_pat () $($inner)*)
-        in pounded_var_names!(multi_zip_expr () $($inner)*) {
-            quote_each_token!($tokens $($inner)*);
-        }
-        quote_each_token!($tokens $($rest)*);
-    };
-
-    ($tokens:ident # ( $($inner:tt)* ) $sep:tt * $($rest:tt)*) => {
-        for (_i, pounded_var_names!(nested_tuples_pat () $($inner)*))
-        in pounded_var_names!(multi_zip_expr () $($inner)*).into_iter().enumerate() {
-            if _i > 0 {
-                $tokens.append(stringify!($sep));
-            }
-            quote_each_token!($tokens $($inner)*);
-        }
-        quote_each_token!($tokens $($rest)*);
-    };
-
-    ($tokens:ident # [ $($inner:tt)* ] $($rest:tt)*) => {
-        $tokens.append("#");
-        $tokens.append("[");
-        quote_each_token!($tokens $($inner)*);
-        $tokens.append("]");
-        quote_each_token!($tokens $($rest)*);
-    };
-
-    ($tokens:ident # $first:ident $($rest:tt)*) => {
-        $crate::ToTokens::to_tokens(&$first, &mut $tokens);
-        quote_each_token!($tokens $($rest)*);
-    };
-
-    ($tokens:ident ( $($first:tt)* ) $($rest:tt)*) => {
-        $tokens.append("(");
-        quote_each_token!($tokens $($first)*);
-        $tokens.append(")");
-        quote_each_token!($tokens $($rest)*);
-    };
-
-    ($tokens:ident [ $($first:tt)* ] $($rest:tt)*) => {
-        $tokens.append("[");
-        quote_each_token!($tokens $($first)*);
-        $tokens.append("]");
-        quote_each_token!($tokens $($rest)*);
-    };
-
-    ($tokens:ident { $($first:tt)* } $($rest:tt)*) => {
-        $tokens.append("{");
-        quote_each_token!($tokens $($first)*);
-        $tokens.append("}");
-        quote_each_token!($tokens $($rest)*);
-    };
-
-    ($tokens:ident $first:tt $($rest:tt)*) => {
-        $tokens.append(stringify!($first));
-        quote_each_token!($tokens $($rest)*);
-    };
-}
deleted file mode 100644
--- a/third_party/rust/quote-0.3.15/src/to_tokens.rs
+++ /dev/null
@@ -1,357 +0,0 @@
-use super::Tokens;
-
-use std::borrow::Cow;
-
-/// Types that can be interpolated inside a `quote!(...)` invocation.
-pub trait ToTokens {
-    /// Write `self` to the given `Tokens`.
-    ///
-    /// Example implementation for a struct representing Rust paths like
-    /// `std::cmp::PartialEq`:
-    ///
-    /// ```ignore
-    /// pub struct Path {
-    ///     pub global: bool,
-    ///     pub segments: Vec<PathSegment>,
-    /// }
-    ///
-    /// impl ToTokens for Path {
-    ///     fn to_tokens(&self, tokens: &mut Tokens) {
-    ///         for (i, segment) in self.segments.iter().enumerate() {
-    ///             if i > 0 || self.global {
-    ///                 tokens.append("::");
-    ///             }
-    ///             segment.to_tokens(tokens);
-    ///         }
-    ///     }
-    /// }
-    /// ```
-    fn to_tokens(&self, &mut Tokens);
-}
-
-impl<'a, T: ?Sized + ToTokens> ToTokens for &'a T {
-    fn to_tokens(&self, tokens: &mut Tokens) {
-        (**self).to_tokens(tokens);
-    }
-}
-
-impl<'a, T: ?Sized + ToOwned + ToTokens> ToTokens for Cow<'a, T> {
-    fn to_tokens(&self, tokens: &mut Tokens) {
-        (**self).to_tokens(tokens);
-    }
-}
-
-impl<T: ?Sized + ToTokens> ToTokens for Box<T> {
-    fn to_tokens(&self, tokens: &mut Tokens) {
-        (**self).to_tokens(tokens);
-    }
-}
-
-impl<T: ToTokens> ToTokens for Option<T> {
-    fn to_tokens(&self, tokens: &mut Tokens) {
-        if let Some(ref t) = *self {
-            t.to_tokens(tokens);
-        }
-    }
-}
-
-impl ToTokens for str {
-    fn to_tokens(&self, tokens: &mut Tokens) {
-        let mut escaped = "\"".to_string();
-        for ch in self.chars() {
-            match ch {
-                '\0' => escaped.push_str(r"\0"),
-                '\'' => escaped.push_str("'"),
-                _ => escaped.extend(ch.escape_default().map(|c| c as char)),
-            }
-        }
-        escaped.push('"');
-
-        tokens.append(&escaped);
-    }
-}
-
-impl ToTokens for String {
-    fn to_tokens(&self, tokens: &mut Tokens) {
-        self.as_str().to_tokens(tokens);
-    }
-}
-
-impl ToTokens for char {
-    fn to_tokens(&self, tokens: &mut Tokens) {
-        match *self {
-            '\0' => tokens.append(r"'\0'"),
-            '"' => tokens.append("'\"'"),
-            _ => tokens.append(&format!("{:?}", self)),
-        }
-    }
-}
-
-/// Wrap a `&str` so it interpolates as a byte-string: `b"abc"`.
-#[derive(Debug)]
-pub struct ByteStr<'a>(pub &'a str);
-
-impl<'a> ToTokens for ByteStr<'a> {
-    fn to_tokens(&self, tokens: &mut Tokens) {
-        let mut escaped = "b\"".to_string();
-        for b in self.0.bytes() {
-            match b {
-                b'\0' => escaped.push_str(r"\0"),
-                b'\t' => escaped.push_str(r"\t"),
-                b'\n' => escaped.push_str(r"\n"),
-                b'\r' => escaped.push_str(r"\r"),
-                b'"' => escaped.push_str("\\\""),
-                b'\\' => escaped.push_str("\\\\"),
-                b'\x20' ... b'\x7E' => escaped.push(b as char),
-                _ => escaped.push_str(&format!("\\x{:02X}", b)),
-            }
-        }
-        escaped.push('"');
-
-        tokens.append(&escaped);
-    }
-}
-
-macro_rules! impl_to_tokens_display {
-    ($ty:ty) => {
-        impl ToTokens for $ty {
-            fn to_tokens(&self, tokens: &mut Tokens) {
-                tokens.append(&self.to_string());
-            }
-        }
-    };
-}
-
-impl_to_tokens_display!(Tokens);
-impl_to_tokens_display!(bool);
-
-/// Wrap an integer so it interpolates as a hexadecimal.
-#[derive(Debug)]
-pub struct Hex<T>(pub T);
-
-macro_rules! impl_to_tokens_integer {
-    ($ty:ty) => {
-        impl ToTokens for $ty {
-            fn to_tokens(&self, tokens: &mut Tokens) {
-                tokens.append(&format!(concat!("{}", stringify!($ty)), self));
-            }
-        }
-
-        impl ToTokens for Hex<$ty> {
-            fn to_tokens(&self, tokens: &mut Tokens) {
-                tokens.append(&format!(concat!("0x{:X}", stringify!($ty)), self.0));
-            }
-        }
-    };
-}
-
-impl_to_tokens_integer!(i8);
-impl_to_tokens_integer!(i16);
-impl_to_tokens_integer!(i32);
-impl_to_tokens_integer!(i64);
-impl_to_tokens_integer!(isize);
-impl_to_tokens_integer!(u8);
-impl_to_tokens_integer!(u16);
-impl_to_tokens_integer!(u32);
-impl_to_tokens_integer!(u64);
-impl_to_tokens_integer!(usize);
-
-macro_rules! impl_to_tokens_floating {
-    ($ty:ty) => {
-        impl ToTokens for $ty {
-            fn to_tokens(&self, tokens: &mut Tokens) {
-                use std::num::FpCategory::*;
-                match self.classify() {
-                    Zero | Subnormal | Normal => {
-                        tokens.append(&format!(concat!("{}", stringify!($ty)), self));
-                    }
-                    Nan => {
-                        tokens.append("::");
-                        tokens.append("std");
-                        tokens.append("::");
-                        tokens.append(stringify!($ty));
-                        tokens.append("::");
-                        tokens.append("NAN");
-                    }
-                    Infinite => {
-                        tokens.append("::");
-                        tokens.append("std");
-                        tokens.append("::");
-                        tokens.append(stringify!($ty));
-                        tokens.append("::");
-                        if self.is_sign_positive() {
-                            tokens.append("INFINITY");
-                        } else {
-                            tokens.append("NEG_INFINITY");
-                        }
-                    }
-                }
-            }
-        }
-    };
-}
-impl_to_tokens_floating!(f32);
-impl_to_tokens_floating!(f64);
-
-impl<T: ToTokens> ToTokens for [T] {
-    fn to_tokens(&self, tokens: &mut Tokens) {
-        tokens.append("[");
-        for item in self {
-            item.to_tokens(tokens);
-            tokens.append(",");
-        }
-        tokens.append("]");
-    }
-}
-
-impl<T: ToTokens> ToTokens for Vec<T> {
-    fn to_tokens(&self, tokens: &mut Tokens) {
-        self[..].to_tokens(tokens)
-    }
-}
-
-macro_rules! array_impls {
-    ($($N:expr)+) => {
-        $(
-            impl<T: ToTokens> ToTokens for [T; $N] {
-                fn to_tokens(&self, tokens: &mut Tokens) {
-                    self[..].to_tokens(tokens)
-                }
-            }
-        )+
-    }
-}
-
-array_impls! {
-     0  1  2  3  4  5  6  7  8  9
-    10 11 12 13 14 15 16 17 18 19
-    20 21 22 23 24 25 26 27 28 29
-    30 31 32
-}
-
-macro_rules! tuple_impls {
-    ($(
-        $Tuple:ident {
-            $(($idx:tt) -> $T:ident)*
-        }
-    )+) => {
-        $(
-            impl<$($T: ToTokens),*> ToTokens for ($($T,)*) {
-                fn to_tokens(&self, tokens: &mut Tokens) {
-                    tokens.append("(");
-                    $(
-                        self.$idx.to_tokens(tokens);
-                        tokens.append(",");
-                    )*
-                    tokens.append(")");
-                }
-            }
-        )+
-    }
-}
-
-tuple_impls! {
-    Tuple0 {}
-    Tuple1 {
-        (0) -> A
-    }
-    Tuple2 {
-        (0) -> A
-        (1) -> B
-    }
-    Tuple3 {
-        (0) -> A
-        (1) -> B
-        (2) -> C
-    }
-    Tuple4 {
-        (0) -> A
-        (1) -> B
-        (2) -> C
-        (3) -> D
-    }
-    Tuple5 {
-        (0) -> A
-        (1) -> B
-        (2) -> C
-        (3) -> D
-        (4) -> E
-    }
-    Tuple6 {
-        (0) -> A
-        (1) -> B
-        (2) -> C
-        (3) -> D
-        (4) -> E
-        (5) -> F
-    }
-    Tuple7 {
-        (0) -> A
-        (1) -> B
-        (2) -> C
-        (3) -> D
-        (4) -> E
-        (5) -> F
-        (6) -> G
-    }
-    Tuple8 {
-        (0) -> A
-        (1) -> B
-        (2) -> C
-        (3) -> D
-        (4) -> E
-        (5) -> F
-        (6) -> G
-        (7) -> H
-    }
-    Tuple9 {
-        (0) -> A
-        (1) -> B
-        (2) -> C
-        (3) -> D
-        (4) -> E
-        (5) -> F
-        (6) -> G
-        (7) -> H
-        (8) -> I
-    }
-    Tuple10 {
-        (0) -> A
-        (1) -> B
-        (2) -> C
-        (3) -> D
-        (4) -> E
-        (5) -> F
-        (6) -> G
-        (7) -> H
-        (8) -> I
-        (9) -> J
-    }
-    Tuple11 {
-        (0) -> A
-        (1) -> B
-        (2) -> C
-        (3) -> D
-        (4) -> E
-        (5) -> F
-        (6) -> G
-        (7) -> H
-        (8) -> I
-        (9) -> J
-        (10) -> K
-    }
-    Tuple12 {
-        (0) -> A
-        (1) -> B
-        (2) -> C
-        (3) -> D
-        (4) -> E
-        (5) -> F
-        (6) -> G
-        (7) -> H
-        (8) -> I
-        (9) -> J
-        (10) -> K
-        (11) -> L
-    }
-}
deleted file mode 100644
--- a/third_party/rust/quote-0.3.15/src/tokens.rs
+++ /dev/null
@@ -1,156 +0,0 @@
-use super::ToTokens;
-use std::fmt::{self, Display};
-use std::str::FromStr;
-
-/// Tokens produced by a `quote!(...)` invocation.
-#[derive(Debug, Clone, Eq, PartialEq)]
-pub struct Tokens(String);
-
-impl Tokens {
-    /// Empty tokens.
-    pub fn new() -> Self {
-        Tokens(String::new())
-    }
-
-    /// For use by `ToTokens` implementations.
-    ///
-    /// ```
-    /// # #[macro_use] extern crate quote;
-    /// # use quote::{Tokens, ToTokens};
-    /// # fn main() {
-    /// struct X;
-    ///
-    /// impl ToTokens for X {
-    ///     fn to_tokens(&self, tokens: &mut Tokens) {
-    ///         tokens.append("a");
-    ///         tokens.append("b");
-    ///         tokens.append("c");
-    ///     }
-    /// }
-    ///
-    /// let tokens = quote!(#X);
-    /// assert_eq!(tokens.as_str(), "a b c");
-    /// # }
-    /// ```
-    pub fn append<T: AsRef<str>>(&mut self, token: T) {
-        if !self.0.is_empty() && !token.as_ref().is_empty() {
-            self.0.push(' ');
-        }
-        self.0.push_str(token.as_ref());
-    }
-
-    /// For use by `ToTokens` implementations.
-    ///
-    /// ```
-    /// # #[macro_use] extern crate quote;
-    /// # use quote::{Tokens, ToTokens};
-    /// # fn main() {
-    /// struct X;
-    ///
-    /// impl ToTokens for X {
-    ///     fn to_tokens(&self, tokens: &mut Tokens) {
-    ///         tokens.append_all(&[true, false]);
-    ///     }
-    /// }
-    ///
-    /// let tokens = quote!(#X);
-    /// assert_eq!(tokens.as_str(), "true false");
-    /// # }
-    /// ```
-    pub fn append_all<T, I>(&mut self, iter: I)
-        where T: ToTokens,
-              I: IntoIterator<Item = T>
-    {
-        for token in iter {
-            token.to_tokens(self);
-        }
-    }
-
-    /// For use by `ToTokens` implementations.
-    ///
-    /// ```
-    /// # #[macro_use] extern crate quote;
-    /// # use quote::{Tokens, ToTokens};
-    /// # fn main() {
-    /// struct X;
-    ///
-    /// impl ToTokens for X {
-    ///     fn to_tokens(&self, tokens: &mut Tokens) {
-    ///         tokens.append_separated(&[true, false], ",");
-    ///     }
-    /// }
-    ///
-    /// let tokens = quote!(#X);
-    /// assert_eq!(tokens.as_str(), "true , false");
-    /// # }
-    /// ```
-    pub fn append_separated<T, I, S: AsRef<str>>(&mut self, iter: I, sep: S)
-        where T: ToTokens,
-              I: IntoIterator<Item = T>
-    {
-        for (i, token) in iter.into_iter().enumerate() {
-            if i > 0 {
-                self.append(sep.as_ref());
-            }
-            token.to_tokens(self);
-        }
-    }
-
-    /// For use by `ToTokens` implementations.
-    ///
-    /// ```
-    /// # #[macro_use] extern crate quote;
-    /// # use quote::{Tokens, ToTokens};
-    /// # fn main() {
-    /// struct X;
-    ///
-    /// impl ToTokens for X {
-    ///     fn to_tokens(&self, tokens: &mut Tokens) {
-    ///         tokens.append_terminated(&[true, false], ",");
-    ///     }
-    /// }
-    ///
-    /// let tokens = quote!(#X);
-    /// assert_eq!(tokens.as_str(), "true , false ,");
-    /// # }
-    /// ```
-    pub fn append_terminated<T, I, S: AsRef<str>>(&mut self, iter: I, term: S)
-        where T: ToTokens,
-              I: IntoIterator<Item = T>
-    {
-        for token in iter {
-            token.to_tokens(self);
-            self.append(term.as_ref());
-        }
-    }
-
-    pub fn as_str(&self) -> &str {
-        &self.0
-    }
-
-    pub fn into_string(self) -> String {
-        self.0
-    }
-
-    pub fn parse<T: FromStr>(&self) -> Result<T, T::Err> {
-        FromStr::from_str(&self.0)
-    }
-}
-
-impl Default for Tokens {
-    fn default() -> Self {
-        Tokens::new()
-    }
-}
-
-impl Display for Tokens {
-    fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
-        self.0.fmt(formatter)
-    }
-}
-
-impl AsRef<str> for Tokens {
-    fn as_ref(&self) -> &str {
-        &self.0
-    }
-}
deleted file mode 100644
--- a/third_party/rust/quote-0.3.15/tests/test.rs
+++ /dev/null
@@ -1,360 +0,0 @@
-use std::{f32, f64};
-use std::borrow::Cow;
-
-#[macro_use]
-extern crate quote;
-
-struct X;
-
-impl quote::ToTokens for X {
-    fn to_tokens(&self, tokens: &mut quote::Tokens) {
-        tokens.append("X");
-    }
-}
-
-#[test]
-fn test_quote_impl() {
-    let tokens = quote!(
-        impl<'a, T: ToTokens> ToTokens for &'a T {
-            fn to_tokens(&self, tokens: &mut Tokens) {
-                (**self).to_tokens(tokens)
-            }
-        }
-    );
-
-    let expected = concat!(
-        "impl < 'a , T : ToTokens > ToTokens for & 'a T { ",
-            "fn to_tokens ( & self , tokens : & mut Tokens ) { ",
-                "( * * self ) . to_tokens ( tokens ) ",
-            "} ",
-        "}"
-    );
-
-    assert_eq!(expected, tokens.as_str());
-}
-
-#[test]
-fn test_append_tokens() {
-    let mut tokens = quote!(let x =);
-    tokens.append(quote!("Hello World!";));
-
-    let expected = "let x = \"Hello World!\" ;";
-
-    assert_eq!(expected, tokens.as_str());
-}
-
-#[test]
-fn test_substitution() {
-    let x = X;
-    let tokens = quote!(#x <#x> (#x) [#x] {#x});
-
-    let expected = "X < X > ( X ) [ X ] { X }";
-
-    assert_eq!(expected, tokens.as_str());
-}
-
-#[test]
-fn test_iter() {
-    let primes = &[X, X, X, X];
-
-    assert_eq!("X X X X", quote!(#(#primes)*).as_str());
-
-    assert_eq!("X , X , X , X ,", quote!(#(#primes,)*).as_str());
-
-    assert_eq!("X , X , X , X", quote!(#(#primes),*).as_str());
-}
-
-#[test]
-fn test_advanced() {
-    let generics = quote!( <'a, T> );
-
-    let where_clause = quote!( where T: Serialize );
-
-    let field_ty = quote!( String );
-
-    let item_ty = quote!( Cow<'a, str> );
-
-    let path = quote!( SomeTrait::serialize_with );
-
-    let value = quote!( self.x );
-
-    let tokens = quote! {
-        struct SerializeWith #generics #where_clause {
-            value: &'a #field_ty,
-            phantom: ::std::marker::PhantomData<#item_ty>,
-        }
-
-        impl #generics ::serde::Serialize for SerializeWith #generics #where_clause {
-            fn serialize<S>(&self, s: &mut S) -> Result<(), S::Error>
-                where S: ::serde::Serializer
-            {
-                #path(self.value, s)
-            }
-        }
-
-        SerializeWith {
-            value: #value,
-            phantom: ::std::marker::PhantomData::<#item_ty>,
-        }
-    };
-
-    let expected = concat!(
-        "struct SerializeWith < 'a , T > where T : Serialize { ",
-            "value : & 'a String , ",
-            "phantom : :: std :: marker :: PhantomData < Cow < 'a , str > > , ",
-        "} ",
-        "impl < 'a , T > :: serde :: Serialize for SerializeWith < 'a , T > where T : Serialize { ",
-            "fn serialize < S > ( & self , s : & mut S ) -> Result < ( ) , S :: Error > ",
-                "where S : :: serde :: Serializer ",
-            "{ ",
-                "SomeTrait :: serialize_with ( self . value , s ) ",
-            "} ",
-        "} ",
-        "SerializeWith { ",
-            "value : self . x , ",
-            "phantom : :: std :: marker :: PhantomData :: < Cow < 'a , str > > , ",
-        "}"
-    );
-
-    assert_eq!(expected, tokens.as_str());
-}
-
-#[test]
-fn test_unit() {
-    let x = ();
-    let tokens = quote!(#x);
-    let expected = "( )";
-    assert_eq!(expected, tokens.as_str());
-}
-
-#[test]
-fn test_tuple() {
-    let x = ("foo", 4_u32);
-    let tokens = quote!(#x);
-    let expected = "( \"foo\" , 4u32 , )";
-    assert_eq!(expected, tokens.as_str());
-}
-
-#[test]
-fn test_array() {
-    let x: [u32; 3] = [1, 2, 3];
-    let tokens = quote!(#x);
-    let expected = "[ 1u32 , 2u32 , 3u32 , ]";
-    assert_eq!(expected, tokens.as_str());
-}
-
-#[test]
-fn test_slice() {
-    let x: &[u32] = &[1, 2, 3];
-    let tokens = quote!(&#x);  // Note: explicit `&`
-    let expected = "& [ 1u32 , 2u32 , 3u32 , ]";
-    assert_eq!(expected, tokens.as_str());
-}
-
-#[test]
-fn test_vec() {
-    let x: Vec<u32> = vec![1, 2, 3];
-    let tokens = quote!(vec!#x);  // Note: explicit `vec!`
-    let expected = "vec ! [ 1u32 , 2u32 , 3u32 , ]";
-    assert_eq!(expected, tokens.as_str());
-}
-
-#[test]
-fn test_integer() {
-    let ii8 = -1i8;
-    let ii16 = -1i16;
-    let ii32 = -1i32;
-    let ii64 = -1i64;
-    let iisize = -1isize;
-    let uu8 = 1u8;
-    let uu16 = 1u16;
-    let uu32 = 1u32;
-    let uu64 = 1u64;
-    let uusize = 1usize;
-
-    let tokens = quote! {
-        #ii8 #ii16 #ii32 #ii64 #iisize
-        #uu8 #uu16 #uu32 #uu64 #uusize
-    };
-    let expected = "-1i8 -1i16 -1i32 -1i64 -1isize 1u8 1u16 1u32 1u64 1usize";
-    assert_eq!(expected, tokens.as_str());
-}
-
-#[test]
-fn test_hex() {
-    let hex = quote::Hex(0xFFFF_0000_u32);
-    let tokens = quote!(#hex);
-    let expected = "0xFFFF0000u32";
-    assert_eq!(expected, tokens.as_str());
-}
-
-#[test]
-fn test_floating() {
-    let e32 = 2.71828f32;
-    let nan32 = f32::NAN;
-    let inf32 = f32::INFINITY;
-    let neginf32 = f32::NEG_INFINITY;
-
-    let e64 = 2.71828f64;
-    let nan64 = f64::NAN;
-    let inf64 = f64::INFINITY;
-    let neginf64 = f64::NEG_INFINITY;
-
-    let tokens = quote! {
-        #e32 @ #nan32 @ #inf32 @ #neginf32
-        #e64 @ #nan64 @ #inf64 @ #neginf64
-    };
-    let expected = concat!(
-        "2.71828f32 @ :: std :: f32 :: NAN @ :: std :: f32 :: INFINITY @ :: std :: f32 :: NEG_INFINITY ",
-        "2.71828f64 @ :: std :: f64 :: NAN @ :: std :: f64 :: INFINITY @ :: std :: f64 :: NEG_INFINITY",
-    );
-    assert_eq!(expected, tokens.as_str());
-}
-
-#[test]
-fn test_char() {
-    let zero = '\0';
-    let pound = '#';
-    let quote = '"';
-    let apost = '\'';
-    let newline = '\n';
-    let heart = '\u{2764}';
-
-    let tokens = quote! {
-        #zero #pound #quote #apost #newline #heart
-    };
-    let expected = "'\\0' '#' '\"' '\\'' '\\n' '\u{2764}'";
-    assert_eq!(expected, tokens.as_str());
-}
-
-#[test]
-fn test_str() {
-    let s = "\0 a 'b \" c";
-    let tokens = quote!(#s);
-    let expected = "\"\\0 a 'b \\\" c\"";
-    assert_eq!(expected, tokens.as_str());
-}
-
-#[test]
-fn test_string() {
-    let s = "\0 a 'b \" c".to_string();
-    let tokens = quote!(#s);
-    let expected = "\"\\0 a 'b \\\" c\"";
-    assert_eq!(expected, tokens.as_str());
-}
-
-#[test]
-fn test_byte_str() {
-    let s = quote::ByteStr("\0 a 'b \" c");
-    let tokens = quote!(#s);
-    let expected = "b\"\\0 a 'b \\\" c\"";
-    assert_eq!(expected, tokens.as_str());
-}
-
-#[test]
-fn test_byte_str_escape() {
-    let s = quote::ByteStr("\u{3c3} \\ \" \n");
-    let tokens = quote!(#s);
-    let expected = "b\"\\xCF\\x83 \\\\ \\\" \\n\"";
-    assert_eq!(expected, tokens.as_str());
-}
-
-#[test]
-fn test_ident() {
-    let foo = quote::Ident::from("Foo");
-    let bar = quote::Ident::from(format!("Bar{}", 7));
-    let tokens = quote!(struct #foo; enum #bar {});
-    let expected = "struct Foo ; enum Bar7 { }";
-    assert_eq!(expected, tokens.as_str());
-}
-
-#[test]
-fn test_duplicate() {
-    let ch = 'x';
-
-    let tokens = quote!(#ch #ch);
-
-    let expected = "'x' 'x'";
-    assert_eq!(expected, tokens.as_str());
-}
-
-#[test]
-fn test_fancy_repetition() {
-    let foo = vec!["a", "b"];
-    let bar = vec![true, false];
-
-    let tokens = quote! {
-        #(#foo: #bar),*
-    };
-
-    let expected = r#""a" : true , "b" : false"#;
-    assert_eq!(expected, tokens.as_str());
-}
-
-#[test]
-fn test_nested_fancy_repetition() {
-    let nested = vec![vec!['a', 'b', 'c'], vec!['x', 'y', 'z']];
-
-    let tokens = quote! {
-        #(
-            #(#nested)*
-        ),*
-    };
-
-    let expected = "'a' 'b' 'c' , 'x' 'y' 'z'";
-    assert_eq!(expected, tokens.as_str());
-}
-
-#[test]
-fn test_empty_repetition() {
-    let tokens = quote!(#(a b)* #(c d),*);
-    assert_eq!("", tokens.as_str());
-}
-
-#[test]
-fn test_variable_name_conflict() {
-    // The implementation of `#(...),*` uses the variable `_i` but it should be
-    // fine, if a little confusing when debugging.
-    let _i = vec!['a', 'b'];
-    let tokens = quote! { #(#_i),* };
-    let expected = "'a' , 'b'";
-    assert_eq!(expected, tokens.as_str());
-}
-
-#[test]
-fn test_empty_quote() {
-    let tokens = quote!();
-    assert_eq!("", tokens.as_str());
-}
-
-#[test]
-fn test_box_str() {
-    let b = "str".to_owned().into_boxed_str();
-    let tokens = quote! { #b };
-    assert_eq!("\"str\"", tokens.as_str());
-}
-
-#[test]
-fn test_cow() {
-    let owned: Cow<quote::Ident> = Cow::Owned(quote::Ident::from("owned"));
-
-    let ident = quote::Ident::from("borrowed");
-    let borrowed = Cow::Borrowed(&ident);
-
-    let tokens = quote! { #owned #borrowed };
-    assert_eq!("owned borrowed", tokens.as_str());
-}
-
-#[test]
-fn test_closure() {
-    fn field_i(i: usize) -> quote::Ident {
-        quote::Ident::new(format!("__field{}", i))
-    }
-
-    let fields = (0usize..3)
-        .map(field_i as fn(_) -> _)
-        .map(|var| quote! { #var });
-
-    let tokens = quote! { #(#fields)* };
-    assert_eq!("__field0 __field1 __field2", tokens.as_str());
-}
--- a/third_party/rust/string_cache_codegen/.cargo-checksum.json
+++ b/third_party/rust/string_cache_codegen/.cargo-checksum.json
@@ -1,1 +1,1 @@
-{"files":{"Cargo.toml":"3a227982587f7b714d78032d3fee9490c289a8907aae153ef897e7f0867ff351","lib.rs":"2379ed4126b680fc8ccd20b6087f304b3797459a2b5e300cda09e982872522ff"},"package":"479cde50c3539481f33906a387f2bd17c8e87cb848c35b6021d41fb81ff9b4d7"}
\ No newline at end of file
+{"files":{"Cargo.toml":"09315a82c3590f231d29e4c2c3693f452f93c47cc0a6d140603609fc7f32c9fa","lib.rs":"f63e3706cdf6677065740e70c04685ef5bdf536e6f03165ac0fac8e43f7b0124"},"package":"1eea1eee654ef80933142157fdad9dd8bc43cf7c74e999e369263496f04ff4da"}
\ No newline at end of file
--- a/third_party/rust/string_cache_codegen/Cargo.toml
+++ b/third_party/rust/string_cache_codegen/Cargo.toml
@@ -1,19 +1,38 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g. crates.io) dependencies
+#
+# If you believe there's an error in this file please file an
+# issue against the rust-lang/cargo repository. If you're
+# editing this file be aware that the upstream Cargo.toml
+# will likely look very different (and much more reasonable)
+
 [package]
-
 name = "string_cache_codegen"
-version = "0.4.0"  # Also update ../README.md when making a semver-breaking change
-authors = [ "The Servo Project Developers" ]
+version = "0.4.2"
+authors = ["The Servo Project Developers"]
 description = "A codegen library for string-cache, developed as part of the Servo project."
+documentation = "https://docs.rs/string_cache_codegen/"
 license = "MIT / Apache-2.0"
 repository = "https://github.com/servo/string-cache"
-documentation = "https://docs.rs/string_cache_codegen/"
 
 [lib]
 name = "string_cache_codegen"
 path = "lib.rs"
+[dependencies.phf_generator]
+version = "0.7.15"
 
-[dependencies]
-string_cache_shared = {path = "../shared", version = "0.3"}
-phf_generator = "0.7.15"
-phf_shared = "0.7.4"
-quote = "0.3.9"
+[dependencies.phf_shared]
+version = "0.7.4"
+
+[dependencies.proc-macro2]
+version = "0.4"
+
+[dependencies.quote]
+version = "0.6"
+
+[dependencies.string_cache_shared]
+version = "0.3"
--- a/third_party/rust/string_cache_codegen/lib.rs
+++ b/third_party/rust/string_cache_codegen/lib.rs
@@ -1,67 +1,163 @@
 // Copyright 2016 The Servo Project Developers. See the COPYRIGHT
 // file at the top-level directory of this distribution.
 //
 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
+//! A crate to create static string caches at compiletime.
+//!
+//! # Examples
+//!
+//! With static atoms:
+//!
+//! In `Cargo.toml`:
+//!
+//! ```toml
+//! [package]
+//! build = "build.rs"
+//!
+//! [dependencies]
+//! string_cache = "0.7"
+//!
+//! [build-dependencies]
+//! string_cache_codegen = "0.4"
+//! ```
+//!
+//! In `build.rs`:
+//!
+//! ```no_run
+//! extern crate string_cache_codegen;
+//!
+//! use std::env;
+//! use std::path::Path;
+//!
+//! fn main() {
+//!     string_cache_codegen::AtomType::new("foo::FooAtom", "foo_atom!")
+//!         .atoms(&["foo", "bar"])
+//!         .write_to_file(&Path::new(&env::var("OUT_DIR").unwrap()).join("foo_atom.rs"))
+//!         .unwrap()
+//! }
+//! ```
+//!
+//! In `lib.rs`:
+//!
+//! ```ignore
+//! extern crate string_cache;
+//!
+//! mod foo {
+//!     include!(concat!(env!("OUT_DIR"), "/foo_atom.rs"));
+//! }
+//! ```
+//!
+//! The generated code will define a `FooAtom` type and a `foo_atom!` macro.
+//! The macro can be used in expression or patterns, with strings listed in `build.rs`.
+//! For example:
+//!
+//! ```ignore
+//! fn compute_something(input: &foo::FooAtom) -> u32 {
+//!     match *input {
+//!         foo_atom!("foo") => 1,
+//!         foo_atom!("bar") => 2,
+//!         _ => 3,
+//!     }
+//! }
+//! ```
+//!
 
 #![recursion_limit = "128"]
 
 extern crate phf_generator;
 extern crate phf_shared;
 extern crate string_cache_shared as shared;
 #[macro_use] extern crate quote;
+extern crate proc_macro2;
 
 use std::collections::HashSet;
 use std::fs::File;
 use std::io::{self, Write, BufWriter};
 use std::iter;
 use std::path::Path;
 
 /// A builder for a static atom set and relevant macros
 pub struct AtomType {
     path: String,
+    atom_doc: Option<String>,
+    static_set_doc: Option<String>,
     macro_name: String,
+    macro_doc: Option<String>,
     atoms: HashSet<String>,
 }
 
 impl AtomType {
     /// Constructs a new static atom set builder
     ///
     /// `path` is a path within a crate of the atom type that will be created.
     /// e.g. `"FooAtom"` at the crate root or `"foo::Atom"` if the generated code
     /// is included in a `foo` module.
     ///
     /// `macro_name` must end with `!`.
     ///
     /// For example, `AtomType::new("foo::FooAtom", "foo_atom!")` will generate:
     ///
-    /// ```rust
+    /// ```ignore
     /// pub type FooAtom = ::string_cache::Atom<FooAtomStaticSet>;
     /// pub struct FooAtomStaticSet;
     /// impl ::string_cache::StaticAtomSet for FooAtomStaticSet {
     ///     // ...
     /// }
     /// #[macro_export]
     /// macro_rules foo_atom {
     ///    // Expands to: $crate::foo::FooAtom { … }
     /// }
+    /// ```
     pub fn new(path: &str, macro_name: &str) -> Self {
-        assert!(macro_name.ends_with("!"));
+        assert!(macro_name.ends_with("!"), "`macro_name` must end with '!'");
         AtomType {
             path: path.to_owned(),
             macro_name: macro_name[..macro_name.len() - "!".len()].to_owned(),
+            atom_doc: None,
+            static_set_doc: None,
+            macro_doc: None,
             atoms: HashSet::new(),
         }
     }
 
+    /// Add some documentation to the generated Atom type alias.
+    ///
+    /// This can help the user know that the type uses interned strings.
+    ///
+    /// Note that `docs` should not contain the `///` at the front of normal docs.
+    pub fn with_atom_doc(&mut self, docs: &str) -> &mut Self {
+        self.atom_doc = Some(docs.to_owned());
+        self
+    }
+
+    /// Add some documentation to the generated static set.
+    ///
+    /// This can help the user know that this type is zero-sized and just references a static
+    /// lookup table, or point them to the `Atom` type alias for more info.
+    ///
+    /// Note that `docs` should not contain the `///` at the front of normal docs.
+    pub fn with_static_set_doc(&mut self, docs: &str) -> &mut Self {
+        self.static_set_doc = Some(docs.to_owned());
+        self
+    }
+
+    /// Add some documentation to the generated macro.
+    ///
+    /// Note that `docs` should not contain the `///` at the front of normal docs.
+    pub fn with_macro_doc(&mut self, docs: &str) -> &mut Self {
+        self.macro_doc = Some(docs.to_owned());
+        self
+    }
+
     /// Adds an atom to the builder
     pub fn atom(&mut self, s: &str) -> &mut Self {
         self.atoms.insert(s.to_owned());
         self
     }
 
     /// Adds multiple atoms to the builder
     pub fn atoms<I>(&mut self, iter: I) -> &mut Self
@@ -69,75 +165,100 @@ impl AtomType {
         self.atoms.extend(iter.into_iter().map(|s| s.as_ref().to_owned()));
         self
     }
 
     /// Write generated code to `destination`.
     pub fn write_to<W>(&mut self, mut destination: W) -> io::Result<()> where W: Write {
         destination.write_all(
             self.to_tokens()
-            .as_str()
+            .to_string()
             // Insert some newlines to make the generated code slightly easier to read.
             .replace(" [ \"", "[\n\"")
             .replace("\" , ", "\",\n")
             .replace(" ( \"", "\n( \"")
             .replace("; ", ";\n")
             .as_bytes())
     }
 
-    fn to_tokens(&mut self) -> quote::Tokens {
+    fn to_tokens(&mut self) -> proc_macro2::TokenStream {
         // `impl Default for Atom` requires the empty string to be in the static set.
         // This also makes sure the set in non-empty,
         // which would cause divisions by zero in rust-phf.
         self.atoms.insert(String::new());
 
         let atoms: Vec<&str> = self.atoms.iter().map(|s| &**s).collect();
         let hash_state = phf_generator::generate_hash(&atoms);
         let phf_generator::HashState { key, disps, map } = hash_state;
+        let (disps0, disps1): (Vec<_>, Vec<_>) = disps.into_iter().unzip();
         let atoms: Vec<&str> = map.iter().map(|&idx| atoms[idx]).collect();
+        let atoms_ref = &atoms;
         let empty_string_index = atoms.iter().position(|s| s.is_empty()).unwrap() as u32;
-        let data = (0..atoms.len()).map(|i| quote::Hex(shared::pack_static(i as u32)));
+        let data = (0..atoms.len()).map(|i| {
+            format!("0x{:X}u64", shared::pack_static(i as u32))
+                .parse::<proc_macro2::TokenStream>()
+                .unwrap()
+                .into_iter()
+                .next()
+                .unwrap()
+        });
 
         let hashes: Vec<u32> =
             atoms.iter().map(|string| {
                 let hash = phf_shared::hash(string, key);
                 ((hash >> 32) ^ hash) as u32
             }).collect();
 
         let type_name = if let Some(position) = self.path.rfind("::") {
             &self.path[position + "::".len() ..]
         } else {
             &self.path
         };
-        let static_set_name = quote::Ident::from(format!("{}StaticSet", type_name));
-        let type_name = quote::Ident::from(type_name);
-        let macro_name = quote::Ident::from(&*self.macro_name);
-        let path = iter::repeat(quote::Ident::from(&*self.path));
+        let atom_doc = match self.atom_doc {
+            Some(ref doc) => quote!(#[doc = #doc]),
+            None => quote!()
+        };
+        let static_set_doc = match self.static_set_doc {
+            Some(ref doc) => quote!(#[doc = #doc]),
+            None => quote!()
+        };
+        let macro_doc = match self.macro_doc {
+            Some(ref doc) => quote!(#[doc = #doc]),
+            None => quote!()
+        };
+        let new_term = |string: &str| proc_macro2::Ident::new(string, proc_macro2::Span::call_site());
+        let static_set_name = new_term(&format!("{}StaticSet", type_name));
+        let type_name = new_term(type_name);
+        let macro_name = new_term(&*self.macro_name);
+        let path = iter::repeat(self.path.parse::<proc_macro2::TokenStream>().unwrap());
 
         quote! {
+            #atom_doc
             pub type #type_name = ::string_cache::Atom<#static_set_name>;
+            #static_set_doc
             pub struct #static_set_name;
             impl ::string_cache::StaticAtomSet for #static_set_name {
                 fn get() -> &'static ::string_cache::PhfStrSet {
                     static SET: ::string_cache::PhfStrSet = ::string_cache::PhfStrSet {
                         key: #key,
-                        disps: &#disps,
-                        atoms: &#atoms,
-                        hashes: &#hashes
+                        disps: &[#((#disps0, #disps1)),*],
+                        atoms: &[#(#atoms_ref),*],
+                        hashes: &[#(#hashes),*]
                     };
                     &SET
                 }
                 fn empty_string_index() -> u32 {
                     #empty_string_index
                 }
             }
+            #macro_doc
             #[macro_export]
             macro_rules! #macro_name {
                 #(
-                    (#atoms) => {
+                    (#atoms_ref) => {
                         $crate::#path {
                             unsafe_data: #data,
                             phantom: ::std::marker::PhantomData,
                         }
                     };
                 )*
             }
         }
--- a/toolkit/components/extensions/parent/ext-downloads.js
+++ b/toolkit/components/extensions/parent/ext-downloads.js
@@ -261,17 +261,17 @@ const downloadQuery = query => {
     return ExtensionCommon.normalizeTime(arg).getTime();
   }
 
   const startedBefore = normalizeDownloadTime(query.startedBefore, true);
   const startedAfter = normalizeDownloadTime(query.startedAfter, false);
   // const endedBefore = normalizeDownloadTime(query.endedBefore, true);
   // const endedAfter = normalizeDownloadTime(query.endedAfter, false);
 
-  const totalBytesGreater = query.totalBytesGreater || 0;
+  const totalBytesGreater = query.totalBytesGreater;
   const totalBytesLess = query.totalBytesLess != null ? query.totalBytesLess : Number.MAX_VALUE;
 
   // Handle options for which we can have a regular expression and/or
   // an explicit value to match.
   function makeMatch(regex, value, field) {
     if (value == null && regex == null) {
       return input => true;
     }
--- a/toolkit/components/extensions/schemas/downloads.json
+++ b/toolkit/components/extensions/schemas/downloads.json
@@ -252,17 +252,18 @@
           "endedAfter": {
             "description": "Limits results to downloads that ended after the given ms since the epoch.",
             "optional": true,
             "$ref": "DownloadTime"
           },
           "totalBytesGreater": {
             "description": "Limits results to downloads whose totalBytes is greater than the given integer.",
             "optional": true,
-            "type": "number"
+            "type": "number",
+            "default": -1
           },
           "totalBytesLess": {
             "description": "Limits results to downloads whose totalBytes is less than the given integer.",
             "optional": true,
             "type": "number"
           },
           "filenameRegex": {
             "description": "Limits results to <a href='#type-DownloadItem'>DownloadItems</a> whose <code>filename</code> matches the given regular expression.",
new file mode 100644
--- a/toolkit/components/extensions/test/xpcshell/test_ext_downloads_search.js
+++ b/toolkit/components/extensions/test/xpcshell/test_ext_downloads_search.js
@@ -9,16 +9,19 @@ server.registerDirectory("/data/", do_ge
 
 const BASE = `http://localhost:${server.identity.primaryPort}/data`;
 const TXT_FILE = "file_download.txt";
 const TXT_URL = BASE + "/" + TXT_FILE;
 const TXT_LEN = 46;
 const HTML_FILE = "file_download.html";
 const HTML_URL = BASE + "/" + HTML_FILE;
 const HTML_LEN = 117;
+const EMPTY_FILE = "empty_file_download.txt";
+const EMPTY_URL = BASE + "/" + EMPTY_FILE;
+const EMPTY_LEN = 0;
 const BIG_LEN = 1000; // something bigger both TXT_LEN and HTML_LEN
 
 function backgroundScript() {
   let complete = new Map();
 
   function waitForComplete(id) {
     if (complete.has(id)) {
       return complete.get(id).promise;
@@ -137,16 +140,20 @@ add_task(async function test_search() {
   equal(msg.status, "success", "download() succeeded");
   downloadIds.txt1 = msg.id;
 
   const TXT_FILE2 = "NewFile.txt";
   msg = await download({url: TXT_URL, filename: TXT_FILE2});
   equal(msg.status, "success", "download() succeeded");
   downloadIds.txt2 = msg.id;
 
+  msg = await download({url: EMPTY_URL});
+  equal(msg.status, "success", "download() succeeded");
+  downloadIds.txt3 = msg.id;
+
   const time2 = new Date();
 
   msg = await download({url: HTML_URL});
   equal(msg.status, "success", "download() succeeded");
   downloadIds.html1 = msg.id;
 
   const HTML_FILE2 = "renamed.html";
   msg = await download({url: HTML_URL, filename: HTML_FILE2});
@@ -183,16 +190,27 @@ add_task(async function test_search() {
     mime: "text/plain",
     state: "complete",
     bytesReceived: TXT_LEN,
     totalBytes: TXT_LEN,
     fileSize: TXT_LEN,
     exists: true,
   });
 
+  await checkDownloadItem(downloadIds.txt3, {
+    url: EMPTY_URL,
+    filename: downloadPath(EMPTY_FILE),
+    mime: "text/plain",
+    state: "complete",
+    bytesReceived: EMPTY_LEN,
+    totalBytes: EMPTY_LEN,
+    fileSize: EMPTY_LEN,
+    exists: true,
+  });
+
   await checkDownloadItem(downloadIds.html1, {
     url: HTML_URL,
     filename: downloadPath(HTML_FILE),
     mime: "text/html",
     state: "complete",
     bytesReceived: HTML_LEN,
     totalBytes: HTML_LEN,
     fileSize: HTML_LEN,
@@ -257,17 +275,17 @@ add_task(async function test_search() {
 
   // Check that compatible filename+regexp works
   await checkSearch({filename: downloadPath(HTML_FILE), filenameRegex: HTML_REGEX}, ["html1"], "compatible filename+filename regex");
 
   // Check that incompatible filename+regexp works
   await checkSearch({filename: downloadPath(TXT_FILE), filenameRegex: HTML_REGEX}, [], "incompatible filename+filename regex");
 
   // Check that simple positive search terms work.
-  await checkSearch({query: ["file_download"]}, ["txt1", "txt2", "html1", "html2"],
+  await checkSearch({query: ["file_download"]}, ["txt1", "txt2", "txt3", "html1", "html2"],
                     "term file_download");
   await checkSearch({query: ["NewFile"]}, ["txt2"], "term NewFile");
 
   // Check that positive search terms work case-insensitive.
   await checkSearch({query: ["nEwfILe"]}, ["txt2"], "term nEwfiLe");
 
   // Check that negative search terms work.
   await checkSearch({query: ["-txt"]}, ["html1", "html2"], "term -txt");
@@ -299,49 +317,52 @@ add_task(async function test_search() {
 
     // Check as ISO string
     newquery[field] = date.toISOString();
     await checkSearch(newquery, expected, `${description} as iso string`);
   }
 
   // Check startedBefore
   await checkSearchWithDate({startedBefore: time1}, [], "before time1");
-  await checkSearchWithDate({startedBefore: time2}, ["txt1", "txt2"], "before time2");
-  await checkSearchWithDate({startedBefore: time3}, ["txt1", "txt2", "html1", "html2"], "before time3");
+  await checkSearchWithDate({startedBefore: time2}, ["txt1", "txt2", "txt3"], "before time2");
+  await checkSearchWithDate({startedBefore: time3}, ["txt1", "txt2", "txt3", "html1", "html2"], "before time3");
 
   // Check startedAfter
-  await checkSearchWithDate({startedAfter: time1}, ["txt1", "txt2", "html1", "html2"], "after time1");
+  await checkSearchWithDate({startedAfter: time1}, ["txt1", "txt2", "txt3", "html1", "html2"], "after time1");
   await checkSearchWithDate({startedAfter: time2}, ["html1", "html2"], "after time2");
   await checkSearchWithDate({startedAfter: time3}, [], "after time3");
 
   // Check simple search on totalBytes
   await checkSearch({totalBytes: TXT_LEN}, ["txt1", "txt2"], "totalBytes");
   await checkSearch({totalBytes: HTML_LEN}, ["html1", "html2"], "totalBytes");
 
   // Check simple test on totalBytes{Greater,Less}
   // (NB: TXT_LEN < HTML_LEN < BIG_LEN)
   await checkSearch({totalBytesGreater: 0}, ["txt1", "txt2", "html1", "html2"], "totalBytesGreater than 0");
   await checkSearch({totalBytesGreater: TXT_LEN}, ["html1", "html2"], `totalBytesGreater than ${TXT_LEN}`);
   await checkSearch({totalBytesGreater: HTML_LEN}, [], `totalBytesGreater than ${HTML_LEN}`);
-  await checkSearch({totalBytesLess: TXT_LEN}, [], `totalBytesLess than ${TXT_LEN}`);
-  await checkSearch({totalBytesLess: HTML_LEN}, ["txt1", "txt2"], `totalBytesLess than ${HTML_LEN}`);
-  await checkSearch({totalBytesLess: BIG_LEN}, ["txt1", "txt2", "html1", "html2"], `totalBytesLess than ${BIG_LEN}`);
+  await checkSearch({totalBytesLess: TXT_LEN}, ["txt3"], `totalBytesLess than ${TXT_LEN}`);
+  await checkSearch({totalBytesLess: HTML_LEN}, ["txt1", "txt2", "txt3"], `totalBytesLess than ${HTML_LEN}`);
+  await checkSearch({totalBytesLess: BIG_LEN}, ["txt1", "txt2", "txt3", "html1", "html2"], `totalBytesLess than ${BIG_LEN}`);
+
+  // Bug 1503760 check if 0 byte files with no search query are returned.
+  await checkSearch({}, ["txt1", "txt2", "txt3", "html1", "html2"], "totalBytesGreater than -1");
 
   // Check good combinations of totalBytes*.
   await checkSearch({totalBytes: HTML_LEN, totalBytesGreater: TXT_LEN}, ["html1", "html2"], "totalBytes and totalBytesGreater");
   await checkSearch({totalBytes: TXT_LEN, totalBytesLess: HTML_LEN}, ["txt1", "txt2"], "totalBytes and totalBytesGreater");
   await checkSearch({totalBytes: HTML_LEN, totalBytesLess: BIG_LEN, totalBytesGreater: 0}, ["html1", "html2"], "totalBytes and totalBytesLess and totalBytesGreater");
 
   // Check bad combination of totalBytes*.
   await checkSearch({totalBytesLess: TXT_LEN, totalBytesGreater: HTML_LEN}, [], "bad totalBytesLess, totalBytesGreater combination");
   await checkSearch({totalBytes: TXT_LEN, totalBytesGreater: HTML_LEN}, [], "bad totalBytes, totalBytesGreater combination");
   await checkSearch({totalBytes: HTML_LEN, totalBytesLess: TXT_LEN}, [], "bad totalBytes, totalBytesLess combination");
 
   // Check mime.
-  await checkSearch({mime: "text/plain"}, ["txt1", "txt2"], "mime text/plain");
+  await checkSearch({mime: "text/plain"}, ["txt1", "txt2", "txt3"], "mime text/plain");
   await checkSearch({mime: "text/html"}, ["html1", "html2"], "mime text/htmlplain");
   await checkSearch({mime: "video/webm"}, [], "mime video/webm");
 
   // Check fileSize.
   await checkSearch({fileSize: TXT_LEN}, ["txt1", "txt2"], "fileSize");
   await checkSearch({fileSize: HTML_LEN}, ["html1", "html2"], "fileSize");
 
   // Fields like bytesReceived, paused, state, exists are meaningful
@@ -366,25 +387,26 @@ add_task(async function test_search() {
     totalBytes: TXT_LEN,
     totalBytesGreater: 0,
     totalBytesLess: BIG_LEN,
     mime: "text/plain",
     fileSize: TXT_LEN,
   }, ["txt1"], "many properties");
 
   // Check simple orderBy (forward and backward).
-  await checkSearch({orderBy: ["startTime"]}, ["txt1", "txt2", "html1", "html2"], "orderBy startTime", true);
-  await checkSearch({orderBy: ["-startTime"]}, ["html2", "html1", "txt2", "txt1"], "orderBy -startTime", true);
+  await checkSearch({orderBy: ["startTime"]}, ["txt1", "txt2", "txt3", "html1", "html2"], "orderBy startTime", true);
+  await checkSearch({orderBy: ["-startTime"]}, ["html2", "html1", "txt3", "txt2", "txt1"], "orderBy -startTime", true);
 
   // Check orderBy with multiple fields.
   // NB: TXT_URL and HTML_URL differ only in extension and .html precedes .txt
-  await checkSearch({orderBy: ["url", "-startTime"]}, ["html2", "html1", "txt2", "txt1"], "orderBy with multiple fields", true);
+  // EMPTY_URL begins with e which precedes f
+  await checkSearch({orderBy: ["url", "-startTime"]}, ["txt3", "html2", "html1", "txt2", "txt1"], "orderBy with multiple fields", true);
 
   // Check orderBy with limit.
-  await checkSearch({orderBy: ["url"], limit: 1}, ["html1"], "orderBy with limit", true);
+  await checkSearch({orderBy: ["url"], limit: 1}, ["txt3"], "orderBy with limit", true);
 
   // Check bad arguments.
   async function checkBadSearch(query, pattern, description) {
     let item = await search(query);
     equal(item.status, "error", "search() failed");
     ok(pattern.test(item.errmsg), `error message for ${description} was correct (${item.errmsg}).`);
   }
 
--- a/toolkit/components/telemetry/Events.yaml
+++ b/toolkit/components/telemetry/Events.yaml
@@ -623,18 +623,16 @@ security.ui.identitypopup:
       - main
     extra_keys:
       tp: Whether Tracking Protection was active while the user opened the popup
       cr: Whether Cookie Restrictions was active while the user opened the popup
     products:
       - firefox
   click:
     objects: [
-      "tp_add_blocking",
-      "cookies_add_blocking",
       "cb_prefs_button",
       "clear_sitedata",
       "unblock",
       "unblock_private",
       "block",
       "report_breakage"
     ]
     bug_numbers: