Merge m-c to m-i
authorPhil Ringnalda <philringnalda@gmail.com>
Fri, 04 Nov 2016 21:04:44 -0700
changeset 347991 5da65f1ef19362af0d527f1196429e2fca1d2209
parent 347990 3940d0725fadcf2e3f9b1f721eaf24cd15bc18f2 (current diff)
parent 347784 a7c654513f2ffd9d9ef38fa2bf512b9e8dae3cdd (diff)
child 347992 a1af90b862e1514a0606876f28a8dc5cf4a186c8
push id10298
push userraliiev@mozilla.com
push dateMon, 14 Nov 2016 12:33:03 +0000
treeherdermozilla-aurora@7e29173b1641 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone52.0a1
Merge m-c to m-i MozReview-Commit-ID: 7W5SwSOspcB
layout/base/nsLayoutUtils.cpp
modules/libpref/init/all.js
--- a/browser/base/content/test/general/browser_aboutAccounts.js
+++ b/browser/base/content/test/general/browser_aboutAccounts.js
@@ -401,22 +401,22 @@ var gTests = [
 },
 ]; // gTests
 
 function test()
 {
   waitForExplicitFinish();
 
   Task.spawn(function* () {
-    for (let test of gTests) {
-      info(test.desc);
+    for (let testCase of gTests) {
+      info(testCase.desc);
       try {
-        yield test.run();
+        yield testCase.run();
       } finally {
-        yield test.teardown();
+        yield testCase.teardown();
       }
     }
 
     finish();
   });
 }
 
 function promiseOneMessage(tab, messageName) {
--- a/browser/base/content/test/general/browser_aboutHealthReport.js
+++ b/browser/base/content/test/general/browser_aboutHealthReport.js
@@ -99,23 +99,23 @@ var gTests = [
 function test()
 {
   waitForExplicitFinish();
 
   // xxxmpc leaving this here until we resolve bug 854038 and bug 854060
   requestLongerTimeout(10);
 
   Task.spawn(function* () {
-    for (let test of gTests) {
-      info(test.desc);
-      yield test.setup();
+    for (let testCase of gTests) {
+      info(testCase.desc);
+      yield testCase.setup();
 
       let iframe = yield promiseNewTabLoadEvent("about:healthreport");
 
-      yield test.run(iframe);
+      yield testCase.run(iframe);
 
       gBrowser.removeCurrentTab();
     }
 
     finish();
   });
 }
 
--- a/browser/base/content/test/general/browser_audioTabIcon.js
+++ b/browser/base/content/test/general/browser_audioTabIcon.js
@@ -312,22 +312,22 @@ function* test_browser_swapping(tab, bro
     // Now, test swapping with a muted but not playing tab.
     // Note that the tab remains muted, so we only need to pause playback.
     tab = gBrowser.getTabForBrowser(newBrowser);
     yield pause(tab);
 
     yield BrowserTestUtils.withNewTab({
       gBrowser,
       url: "about:blank",
-    }, newBrowser => test_swapped_browser_while_not_playing(tab, newBrowser));
+    }, secondAboutBlankBrowser => test_swapped_browser_while_not_playing(tab, secondAboutBlankBrowser));
   });
 }
 
 function* test_click_on_pinned_tab_after_mute() {
-  function* test_on_browser(browser) {
+  function* taskFn(browser) {
     let tab = gBrowser.getTabForBrowser(browser);
 
     gBrowser.selectedTab = originallySelectedTab;
     isnot(tab, gBrowser.selectedTab, "Sanity check, the tab should not be selected!");
 
     // Steps to reproduce the bug:
     //   Pin the tab.
     gBrowser.pinTab(tab);
@@ -356,22 +356,22 @@ function* test_click_on_pinned_tab_after
     gBrowser.selectedTab = originallySelectedTab;
   }
 
   let originallySelectedTab = gBrowser.selectedTab;
 
   yield BrowserTestUtils.withNewTab({
     gBrowser,
     url: PAGE
-  }, test_on_browser);
+  }, taskFn);
 }
 
 // This test only does something useful in e10s!
 function* test_cross_process_load() {
-  function* test_on_browser(browser) {
+  function* taskFn(browser) {
     let tab = gBrowser.getTabForBrowser(browser);
 
     //   Start playback and wait for it to finish.
     yield play(tab);
 
     let soundPlayingStoppedPromise = BrowserTestUtils.waitForEvent(tab, "TabAttrModified", false,
       event => event.detail.changed.includes("soundplaying")
     );
@@ -384,29 +384,29 @@ function* test_cross_process_load() {
 
     ok(!tab.hasAttribute("soundplaying"), "Tab should not be playing sound any more");
     ok(!tab.soundPlaying, "Tab should not be playing sound any more");
   }
 
   yield BrowserTestUtils.withNewTab({
     gBrowser,
     url: PAGE
-  }, test_on_browser);
+  }, taskFn);
 }
 
 function* test_mute_keybinding() {
   function* test_muting_using_keyboard(tab) {
     let mutedPromise = get_wait_for_mute_promise(tab, true);
     EventUtils.synthesizeKey("m", {ctrlKey: true});
     yield mutedPromise;
     mutedPromise = get_wait_for_mute_promise(tab, false);
     EventUtils.synthesizeKey("m", {ctrlKey: true});
     yield mutedPromise;
   }
-  function* test_on_browser(browser) {
+  function* taskFn(browser) {
     let tab = gBrowser.getTabForBrowser(browser);
 
     // Make sure it's possible to mute before the tab is playing.
     yield test_muting_using_keyboard(tab);
 
     //   Start playback and wait for it to finish.
     yield play(tab);
 
@@ -429,17 +429,17 @@ function* test_mute_keybinding() {
     yield test_muting_using_keyboard(tab);
 
     gBrowser.unpinTab(tab);
   }
 
   yield BrowserTestUtils.withNewTab({
     gBrowser,
     url: PAGE
-  }, test_on_browser);
+  }, taskFn);
 }
 
 function* test_on_browser(browser) {
   let tab = gBrowser.getTabForBrowser(browser);
 
   // Test the icon in a normal tab.
   yield test_playing_icon_on_tab(tab, browser, false);
 
@@ -457,31 +457,31 @@ function* test_on_browser(browser) {
       url: "data:text/html,test"
     }, () => test_on_browser(browser));
   } else {
     yield test_browser_swapping(tab, browser);
   }
 }
 
 function* test_delayed_tabattr_removal() {
-  function* test_on_browser(browser) {
+  function* taskFn(browser) {
     let tab = gBrowser.getTabForBrowser(browser);
     yield play(tab);
 
     // Extend the delay to guarantee the soundplaying attribute
     // is not removed from the tab when audio is stopped. Without
     // the extended delay the attribute could be removed in the
     // same tick and the test wouldn't catch that this broke.
     yield pause(tab, {extendedDelay: true});
   }
 
   yield BrowserTestUtils.withNewTab({
     gBrowser,
     url: PAGE
-  }, test_on_browser);
+  }, taskFn);
 }
 
 add_task(function*() {
   yield new Promise((resolve) => {
     SpecialPowers.pushPrefEnv({"set": [
                                 ["browser.tabs.showAudioPlayingIcon", true],
                               ]}, resolve);
   });
--- a/browser/base/content/test/general/browser_bug1297539.js
+++ b/browser/base/content/test/general/browser_bug1297539.js
@@ -37,21 +37,21 @@ function getTransferableFromClipboard(as
   return trans;
 }
 
 function* cutCurrentSelection(elementQueryString, property, browser) {
   // Cut the current selection.
   yield BrowserTestUtils.synthesizeKey("x", {accelKey: true}, browser);
 
   // The editor should be empty after cut.
-  yield ContentTask.spawn(browser, {elementQueryString, property},
-    function* ({elementQueryString, property}) {
-      let element = content.document.querySelector(elementQueryString);
-      is(element[property], "",
-        `${elementQueryString} should be empty after cut (superkey + x)`);
+  yield ContentTask.spawn(browser, [elementQueryString, property],
+    function* ([contentElementQueryString, contentProperty]) {
+      let element = content.document.querySelector(contentElementQueryString);
+      is(element[contentProperty], "",
+        `${contentElementQueryString} should be empty after cut (superkey + x)`);
     });
 }
 
 // Test that you are able to pasteTransferable for plain text
 // which is handled by TextEditor::PasteTransferable to paste into the editor.
 add_task(function* test_paste_transferable_plain_text()
 {
   let testPage =
--- a/browser/base/content/test/general/browser_bug491431.js
+++ b/browser/base/content/test/general/browser_bug491431.js
@@ -6,26 +6,26 @@ var testPage = "data:text/plain,test bug
 
 function test() {
   waitForExplicitFinish();
 
   let newWin, tabA, tabB;
 
   // test normal close
   tabA = gBrowser.addTab(testPage);
-  gBrowser.tabContainer.addEventListener("TabClose", function(aEvent) {
+  gBrowser.tabContainer.addEventListener("TabClose", function(firstTabCloseEvent) {
     gBrowser.tabContainer.removeEventListener("TabClose", arguments.callee, true);
-    ok(!aEvent.detail.adoptedBy, "This was a normal tab close");
+    ok(!firstTabCloseEvent.detail.adoptedBy, "This was a normal tab close");
 
     // test tab close by moving
     tabB = gBrowser.addTab(testPage);
-    gBrowser.tabContainer.addEventListener("TabClose", function(aEvent) {
+    gBrowser.tabContainer.addEventListener("TabClose", function(secondTabCloseEvent) {
       gBrowser.tabContainer.removeEventListener("TabClose", arguments.callee, true);
       executeSoon(function() {
-        ok(aEvent.detail.adoptedBy, "This was a tab closed by moving");
+        ok(secondTabCloseEvent.detail.adoptedBy, "This was a tab closed by moving");
 
         // cleanup
         newWin.close();
         executeSoon(finish);
       });
     }, true);
     newWin = gBrowser.replaceTabWithWindow(tabB);
   }, true);
--- a/browser/base/content/test/general/browser_bug553455.js
+++ b/browser/base/content/test/general/browser_bug553455.js
@@ -8,18 +8,18 @@ const SECUREROOT = "https://example.com/
 const XPINSTALL_URL = "chrome://mozapps/content/xpinstall/xpinstallConfirm.xul";
 const PREF_INSTALL_REQUIREBUILTINCERTS = "extensions.install.requireBuiltInCerts";
 const PROGRESS_NOTIFICATION = "addon-progress";
 
 const { REQUIRE_SIGNING } = Cu.import("resource://gre/modules/addons/AddonConstants.jsm", {});
 const { Task } = Cu.import("resource://gre/modules/Task.jsm");
 
 var rootDir = getRootDirectory(gTestPath);
-var path = rootDir.split('/');
-var chromeName = path[0] + '//' + path[2];
+var rootPath = rootDir.split('/');
+var chromeName = rootPath[0] + '//' + rootPath[2];
 var croot = chromeName + "/content/browser/toolkit/mozapps/extensions/test/xpinstall/";
 var jar = getJar(croot);
 if (jar) {
   var tmpdir = extractJarToTmp(jar);
   croot = 'file://' + tmpdir.path + '/';
 }
 const CHROMEROOT = croot;
 
@@ -450,18 +450,18 @@ function test_restartless() {
     is(notification.getAttribute("label"),
        "XPI Test has been installed successfully.",
        "Should have seen the right message");
 
     let installs = yield getInstalls();
     is(installs.length, 0, "Should be no pending installs");
 
     let addon = yield new Promise(resolve => {
-      AddonManager.getAddonByID("restartless-xpi@tests.mozilla.org", addon => {
-        resolve(addon);
+      AddonManager.getAddonByID("restartless-xpi@tests.mozilla.org", result => {
+        resolve(result);
       });
     });
     addon.uninstall();
 
     Services.perms.remove(makeURI("http://example.com/"), "install");
 
     let closePromise = waitForNotificationClose();
     gBrowser.removeTab(gBrowser.selectedTab);
@@ -494,18 +494,18 @@ function test_multiple() {
        "2 add-ons will be installed after you restart " + gApp + ".",
        "Should have seen the right message");
 
     let installs = yield getInstalls();
     is(installs.length, 1, "Should be one pending install");
     installs[0].cancel();
 
     let addon = yield new Promise(resolve => {
-      AddonManager.getAddonByID("restartless-xpi@tests.mozilla.org", function (addon) {
-        resolve(addon);
+      AddonManager.getAddonByID("restartless-xpi@tests.mozilla.org", function (result) {
+        resolve(result);
       });
     });
     addon.uninstall();
     Services.perms.remove(makeURI("http://example.com/"), "install");
     yield removeTab();
   });
 },
 
@@ -671,18 +671,18 @@ function test_allUnverified() {
     is(container.childNodes[0].firstChild.getAttribute("value"), "XPI Test", "Should have the right add-on");
     is(container.childNodes[0].childNodes.length, 1, "Shouldn't have the unverified marker");
 
     let notificationPromise = waitForNotification("addon-install-complete");
     acceptInstallDialog();
     yield notificationPromise;
 
     let addon = yield new Promise(resolve => {
-      AddonManager.getAddonByID("restartless-xpi@tests.mozilla.org", function(addon) {
-        resolve(addon);
+      AddonManager.getAddonByID("restartless-xpi@tests.mozilla.org", function(result) {
+        resolve(result);
       });
     });
     addon.uninstall();
 
     Services.perms.remove(makeURI("http://example.com/"), "install");
     yield removeTab();
   });
 },
@@ -914,27 +914,27 @@ function test_theme() {
 
     let notification = panel.childNodes[0];
     is(notification.button.label, "Restart Now", "Should have seen the right button");
     is(notification.getAttribute("label"),
        "Theme Test will be installed after you restart " + gApp + ".",
        "Should have seen the right message");
 
     let addon = yield new Promise(resolve => {
-      AddonManager.getAddonByID("{972ce4c6-7e08-4474-a285-3208198ce6fd}", function(addon) {
-        resolve(addon);
+      AddonManager.getAddonByID("{972ce4c6-7e08-4474-a285-3208198ce6fd}", function(result) {
+        resolve(result);
       });
     });
     ok(addon.userDisabled, "Should be switching away from the default theme.");
     // Undo the pending theme switch
     addon.userDisabled = false;
 
     addon = yield new Promise(resolve => {
-      AddonManager.getAddonByID("theme-xpi@tests.mozilla.org", function(addon) {
-        resolve(addon);
+      AddonManager.getAddonByID("theme-xpi@tests.mozilla.org", function(result) {
+        resolve(result);
       });
     });
     isnot(addon, null, "Test theme will have been installed");
     addon.uninstall();
 
     Services.perms.remove(makeURI("http://example.com/"), "install");
     yield removeTab();
   });
--- a/browser/base/content/test/general/browser_bug561636.js
+++ b/browser/base/content/test/general/browser_bug561636.js
@@ -69,26 +69,26 @@ function* blurChildElement(browser)
   yield ContentTask.spawn(browser, {}, function* () {
     content.document.getElementById('i').blur();
   });
 }
 
 function* checkChildFocus(browser, message)
 {
   yield ContentTask.spawn(browser, [message, testId], function* (args) {
-    let [msg, testId] = args;
+    let [msg, id] = args;
     var focused = content.document.activeElement == content.document.getElementById('i');
 
     var validMsg = true;
     if (msg) {
       validMsg = (msg == content.document.getElementById('i').validationMessage);
     }
 
-    Assert.equal(focused, true, "Test " + testId + " First invalid element should be focused");
-    Assert.equal(validMsg, true, "Test " + testId + " The panel should show the message from validationMessage");
+    Assert.equal(focused, true, "Test " + id + " First invalid element should be focused");
+    Assert.equal(validMsg, true, "Test " + id + " The panel should show the message from validationMessage");
   });
 }
 
 /**
  * In this test, we check that no popup appears if the form is valid.
  */
 add_task(function* ()
 {
--- a/browser/base/content/test/general/browser_bug592338.js
+++ b/browser/base/content/test/general/browser_bug592338.js
@@ -139,17 +139,17 @@ function runNextTest() {
 
 function test() {
   waitForExplicitFinish();
 
   Services.prefs.setBoolPref("extensions.logging.enabled", true);
 
   AddonManager.getInstallForURL(TESTROOT + "theme.xpi", function(aInstall) {
     aInstall.addListener({
-      onInstallEnded: function(aInstall, aAddon) {
+      onInstallEnded: function() {
         AddonManager.getAddonByID("theme-xpi@tests.mozilla.org", function(aAddon) {
           isnot(aAddon, null, "Should have installed the test theme.");
 
           // In order to switch themes while the test is running we turn on dynamic
           // theme switching. This means the test isn't exactly correct but should
           // do some good
           Services.prefs.setBoolPref("extensions.dss.enabled", true);
 
--- a/browser/base/content/test/general/browser_bug676619.js
+++ b/browser/base/content/test/general/browser_bug676619.js
@@ -7,35 +7,35 @@ function test () {
   function loadListener() {
     function testLocation(link, url, next) {
       new TabOpenListener(url, function () {
         gBrowser.removeTab(this.tab);
       }, function () {
         next();
       });
 
-      ContentTask.spawn(gBrowser.selectedBrowser, link, link => {
-        content.document.getElementById(link).click();
+      ContentTask.spawn(gBrowser.selectedBrowser, link, contentLink => {
+        content.document.getElementById(contentLink).click();
       });
     }
 
     function testLink(link, name, next) {
       addWindowListener("chrome://mozapps/content/downloads/unknownContentType.xul", function (win) {
         ContentTask.spawn(gBrowser.selectedBrowser, null, () => {
           Assert.equal(content.document.getElementById("unload-flag").textContent,
             "Okay", "beforeunload shouldn't have fired");
         }).then(() => {
           is(win.document.getElementById("location").value, name, "file name should match");
           win.close();
           next();
         });
       });
 
-      ContentTask.spawn(gBrowser.selectedBrowser, link, link => {
-        content.document.getElementById(link).click();
+      ContentTask.spawn(gBrowser.selectedBrowser, link, contentLink => {
+        content.document.getElementById(contentLink).click();
       });
     }
 
     testLink("link1", "test.txt",
       testLink.bind(null, "link2", "video.ogg",
         testLink.bind(null, "link3", "just some video",
           testLink.bind(null, "link4", "with-target.txt",
             testLink.bind(null, "link5", "javascript.txt",
--- a/browser/base/content/test/general/browser_bug719271.js
+++ b/browser/base/content/test/general/browser_bug719271.js
@@ -1,17 +1,17 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 "use strict";
 
 const TEST_PAGE = "http://example.org/browser/browser/base/content/test/general/zoom_test.html";
 const TEST_VIDEO = "http://example.org/browser/browser/base/content/test/general/video.ogg";
 
-var gTab1, gTab2, gLevel1, gLevel2;
+var gTab1, gTab2, gLevel1;
 
 function test() {
   waitForExplicitFinish();
 
   Task.spawn(function* () {
     gTab1 = gBrowser.addTab();
     gTab2 = gBrowser.addTab();
 
@@ -39,19 +39,19 @@ function zoomTab1() {
   }).then(zoomTab2, FullZoomHelper.failAndContinue(finish));
 }
 
 function zoomTab2() {
   Task.spawn(function* () {
     is(gBrowser.selectedTab, gTab2, "Tab 2 is selected");
 
     FullZoom.reduce();
-    let gLevel2 = ZoomManager.getZoomForBrowser(gBrowser.getBrowserForTab(gTab2));
+    let level2 = ZoomManager.getZoomForBrowser(gBrowser.getBrowserForTab(gTab2));
 
-    ok(gLevel2 < 1, "New zoom for tab 2 should be less than 1");
+    ok(level2 < 1, "New zoom for tab 2 should be less than 1");
     FullZoomHelper.zoomTest(gTab1, gLevel1, "Zooming tab 2 should not affect tab 1");
 
     yield FullZoomHelper.selectTabAndWaitForLocationChange(gTab1);
     FullZoomHelper.zoomTest(gTab1, gLevel1, "Tab 1 should have the same zoom after it's selected");
   }).then(testNavigation, FullZoomHelper.failAndContinue(finish));
 }
 
 function testNavigation() {
--- a/browser/base/content/test/general/browser_bug763468_perwindowpb.js
+++ b/browser/base/content/test/general/browser_bug763468_perwindowpb.js
@@ -52,19 +52,19 @@ function test() {
       aWin.close();
     });
   });
 
   // test first when not on private mode
   testOnWindow({}, function(aWin) {
     doTest(false, aWin, function() {
       // then test when on private mode
-      testOnWindow({private: true}, function(aWin) {
-        doTest(true, aWin, function() {
+      testOnWindow({private: true}, function(aWin2) {
+        doTest(true, aWin2, function() {
           // then test again when not on private mode
-          testOnWindow({}, function(aWin) {
-            doTest(false, aWin, finish);
+          testOnWindow({}, function(aWin3) {
+            doTest(false, aWin3, finish);
           });
         });
       });
     });
   });
 }
--- a/browser/base/content/test/general/browser_bug767836_perwindowpb.js
+++ b/browser/base/content/test/general/browser_bug767836_perwindowpb.js
@@ -59,18 +59,18 @@ function test() {
 
   // check whether any custom new tab url has been configured
   ok(!aboutNewTabService.overridden, "No custom newtab url is set");
 
   // test normal mode
   testOnWindow(false, function(aWindow) {
     doTest(false, aWindow, function() {
       // test private mode
-      testOnWindow(true, function(aWindow) {
-        doTest(true, aWindow, function() {
+      testOnWindow(true, function(aWindow2) {
+        doTest(true, aWindow2, function() {
           finish();
         });
       });
     });
   });
 }
 
 function openNewTab(aWindow, aCallback) {
--- a/browser/base/content/test/general/browser_clipboard.js
+++ b/browser/base/content/test/general/browser_clipboard.js
@@ -27,22 +27,21 @@ add_task(function*() {
   yield ContentTask.spawn(browser, { modifier, htmlPrefix, htmlPostfix }, function* (arg) {
     var doc = content.document;
     var main = doc.getElementById("main");
     main.focus();
 
     const utils = content.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                          .getInterface(Components.interfaces.nsIDOMWindowUtils);
 
-    const modifier = arg.modifier;
     function sendKey(key) {
-      if (utils.sendKeyEvent("keydown", key, 0, modifier)) {
-        utils.sendKeyEvent("keypress", key, key.charCodeAt(0), modifier);
+      if (utils.sendKeyEvent("keydown", key, 0, arg.modifier)) {
+        utils.sendKeyEvent("keypress", key, key.charCodeAt(0), arg.modifier);
       }
-      utils.sendKeyEvent("keyup", key, 0, modifier);
+      utils.sendKeyEvent("keyup", key, 0, arg.modifier);
     }
 
     // Select an area of the text.
     let selection = doc.getSelection();
     selection.modify("move", "left", "line");
     selection.modify("move", "right", "character");
     selection.modify("move", "right", "character");
     selection.modify("move", "right", "character");
@@ -153,21 +152,20 @@ add_task(function*() {
           reject('Clipboard Data did not contain an image, was ' + clipboardData.getData("text/html"));
         }
         resolve();
       }, true)
 
       const utils = content.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                            .getInterface(Components.interfaces.nsIDOMWindowUtils);
 
-      const modifier = arg.modifier;
-      if (utils.sendKeyEvent("keydown", "v", 0, modifier)) {
-        utils.sendKeyEvent("keypress", "v", "v".charCodeAt(0), modifier);
+      if (utils.sendKeyEvent("keydown", "v", 0, arg.modifier)) {
+        utils.sendKeyEvent("keypress", "v", "v".charCodeAt(0), arg.modifier);
       }
-      utils.sendKeyEvent("keyup", "v", 0, modifier);
+      utils.sendKeyEvent("keyup", "v", 0, arg.modifier);
     });
 
     // The new content should now include an image.
     Assert.equal(main.innerHTML, '<i>Italic</i> <img id="img" tabindex="1" ' +
       'src="http://example.org/browser/browser/base/content/test/general/moz.png">' +
       'Test <b>Bold</b> After<b></b>', "Paste after copy image");
   });
 
--- a/browser/base/content/test/general/browser_contentSearchUI.js
+++ b/browser/base/content/test/general/browser_contentSearchUI.js
@@ -661,22 +661,22 @@ function setUp(aNoEngine) {
 }
 
 function msg(type, data=null) {
   gMsgMan.sendAsyncMessage(TEST_MSG, {
     type: type,
     data: data,
   });
   let deferred = Promise.defer();
-  gMsgMan.addMessageListener(TEST_MSG, function onMsg(msg) {
-    if (msg.data.type != type) {
+  gMsgMan.addMessageListener(TEST_MSG, function onMsg(msgObj) {
+    if (msgObj.data.type != type) {
       return;
     }
     gMsgMan.removeMessageListener(TEST_MSG, onMsg);
-    deferred.resolve(msg.data.data);
+    deferred.resolve(msgObj.data.data);
   });
   return deferred.promise;
 }
 
 function checkState(actualState, expectedInputVal, expectedSuggestions,
                     expectedSelectedIdx, expectedSelectedButtonIdx) {
   expectedSuggestions = expectedSuggestions.map(sugg => {
     return typeof(sugg) == "object" ? sugg : {
@@ -737,21 +737,21 @@ function promiseTab() {
   }, true, true);
   openUILinkIn(pageURL, "current");
   return deferred.promise;
 }
 
 function promiseMsg(name, type, msgMan) {
   let deferred = Promise.defer();
   info("Waiting for " + name + " message " + type + "...");
-  msgMan.addMessageListener(name, function onMsg(msg) {
-    info("Received " + name + " message " + msg.data.type + "\n");
-    if (msg.data.type == type) {
+  msgMan.addMessageListener(name, function onMsg(msgObj) {
+    info("Received " + name + " message " + msgObj.data.type + "\n");
+    if (msgObj.data.type == type) {
       msgMan.removeMessageListener(name, onMsg);
-      deferred.resolve(msg);
+      deferred.resolve(msgObj);
     }
   });
   return deferred.promise;
 }
 
 function setUpEngines() {
   return Task.spawn(function* () {
     info("Removing default search engines");
--- a/browser/base/content/test/general/browser_contextmenu.js
+++ b/browser/base/content/test/general/browser_contextmenu.js
@@ -897,38 +897,39 @@ add_task(function* test_input_spell_fals
 const remoteClientsFixture = [ { id: 1, name: "Foo"}, { id: 2, name: "Bar"} ];
 
 add_task(function* test_plaintext_sendpagetodevice() {
   if (!gFxAccounts.sendTabToDeviceEnabled) {
     return;
   }
   const oldGetter = setupRemoteClientsFixture(remoteClientsFixture);
 
-  let plainTextItems = ["context-navigation",   null,
-                        ["context-back",         false,
-                         "context-forward",      false,
-                         "context-reload",       true,
-                         "context-bookmarkpage", true], null,
+  let plainTextItemsWithSendPage =
+                    ["context-navigation",   null,
+                      ["context-back",         false,
+                        "context-forward",      false,
+                        "context-reload",       true,
+                        "context-bookmarkpage", true], null,
                     "---",                  null,
                     "context-savepage",     true,
                     ...(hasPocket ? ["context-pocket", true] : []),
                     "---",                  null,
                     "context-sendpagetodevice", true,
                       ["*Foo", true,
                        "*Bar", true,
                        "---", null,
                        "*All Devices", true], null,
                     "---",                  null,
                     "context-viewbgimage",  false,
                     "context-selectall",    true,
                     "---",                  null,
                     "context-viewsource",   true,
                     "context-viewinfo",     true
                    ];
-  yield test_contextmenu("#test-text", plainTextItems, {
+  yield test_contextmenu("#test-text", plainTextItemsWithSendPage, {
       *onContextMenuShown() {
         yield openMenuItemSubmenu("context-sendpagetodevice");
       }
     });
 
   restoreRemoteClients(oldGetter);
 });
 
@@ -975,21 +976,21 @@ add_task(function* test_cleanup_html() {
 /**
  * Selects the text of the element that matches the provided `selector`
  *
  * @param {String} selector
  *        A selector passed to querySelector to find
  *        the element that will be referenced.
  */
 function* selectText(selector) {
-  yield ContentTask.spawn(gBrowser.selectedBrowser, selector, function*(selector) {
-    info(`Selecting text of ${selector}`);
+  yield ContentTask.spawn(gBrowser.selectedBrowser, selector, function*(contentSelector) {
+    info(`Selecting text of ${contentSelector}`);
     let doc = content.document;
     let win = doc.defaultView;
     win.getSelection().removeAllRanges();
     let div = doc.createRange();
-    let element = doc.querySelector(selector);
+    let element = doc.querySelector(contentSelector);
     Assert.ok(element, "Found element to select text from");
     div.setStartBefore(element);
     div.setEndAfter(element);
     win.getSelection().addRange(div);
   });
 }
--- a/browser/base/content/test/general/browser_decoderDoctor.js
+++ b/browser/base/content/test/general/browser_decoderDoctor.js
@@ -1,19 +1,19 @@
 "use strict";
 
 function* test_decoder_doctor_notification(type, notificationMessage, options) {
   yield BrowserTestUtils.withNewTab({ gBrowser }, function*(browser) {
     let awaitNotificationBar =
       BrowserTestUtils.waitForNotificationBar(gBrowser, browser, "decoder-doctor-notification");
 
-    yield ContentTask.spawn(browser, type, function*(type) {
+    yield ContentTask.spawn(browser, type, function*(aType) {
       Services.obs.notifyObservers(content.window,
                                    "decoder-doctor-notification",
-                                   JSON.stringify({type: type,
+                                   JSON.stringify({type: aType,
                                                    isSolved: false,
                                                    decoderDoctorReportId: "test",
                                                    formats: "test"}));
     });
 
     let notification;
     try {
       notification = yield awaitNotificationBar;
--- a/browser/base/content/test/general/browser_discovery.js
+++ b/browser/base/content/test/general/browser_discovery.js
@@ -31,45 +31,45 @@ var iconDiscoveryTests = [
   { rel: "shortcut-icon", pass: false, text: "rel shortcut-icon not discovered" },
   { href: "moz.png", text: "relative href works" },
   { href: "notthere.png", text: "404'd icon is removed properly" },
   { href: "data:image/x-icon,%00", type: "image/x-icon", text: "data: URIs work" },
   { type: "image/png; charset=utf-8", text: "type may have optional parameters (RFC2046)" }
 ];
 
 function runIconDiscoveryTest() {
-  var test = iconDiscoveryTests[0];
+  var testCase = iconDiscoveryTests[0];
   var head = doc().getElementById("linkparent");
   var hasSrc = gBrowser.getIcon() != null;
-  if (test.pass)
-    ok(hasSrc, test.text);
+  if (testCase.pass)
+    ok(hasSrc, testCase.text);
   else
-    ok(!hasSrc, test.text);
+    ok(!hasSrc, testCase.text);
 
   head.removeChild(head.getElementsByTagName('link')[0]);
   iconDiscoveryTests.shift();
   iconDiscovery(); // Run the next test.
 }
 
 function iconDiscovery() {
   if (iconDiscoveryTests.length) {
     setHandlerFunc(runIconDiscoveryTest);
     gBrowser.setIcon(gBrowser.selectedTab, null,
                      Services.scriptSecurityManager.getSystemPrincipal());
 
-    var test = iconDiscoveryTests[0];
+    var testCase = iconDiscoveryTests[0];
     var head = doc().getElementById("linkparent");
     var link = doc().createElement("link");
 
     var rootDir = getRootDirectory(gTestPath);
-    var rel = test.rel || "icon";
-    var href = test.href || rootDir + "moz.png";
-    var type = test.type || "image/png";
-    if (test.pass == undefined)
-      test.pass = true;
+    var rel = testCase.rel || "icon";
+    var href = testCase.href || rootDir + "moz.png";
+    var type = testCase.type || "image/png";
+    if (testCase.pass == undefined)
+      testCase.pass = true;
 
     link.rel = rel;
     link.href = href;
     link.type = type;
     head.appendChild(link);
   } else {
     searchDiscovery();
   }
@@ -87,27 +87,27 @@ var searchDiscoveryTests = [
   { type: "APPLICATION/OPENSEARCHDESCRIPTION+XML", text: "type is case insensitve" },
   { type: " application/opensearchdescription+xml ", text: "type may contain extra whitespace" },
   { type: "application/opensearchdescription+xml; charset=utf-8", text: "type may have optional parameters (RFC2046)" },
   { type: "aapplication/opensearchdescription+xml", pass: false, text: "type should not be loosely matched" },
   { rel: "search search search", count: 1, text: "only one engine should be added" }
 ];
 
 function runSearchDiscoveryTest() {
-  var test = searchDiscoveryTests[0];
-  var title = test.title || searchDiscoveryTests.length;
+  var testCase = searchDiscoveryTests[0];
+  var title = testCase.title || searchDiscoveryTests.length;
   if (browser.engines) {
-    var hasEngine = (test.count) ? (browser.engines[0].title == title &&
-                                    browser.engines.length == test.count) :
-                                   (browser.engines[0].title == title);
-    ok(hasEngine, test.text);
+    var hasEngine = (testCase.count) ? (browser.engines[0].title == title &&
+                                        browser.engines.length == testCase.count) :
+                                       (browser.engines[0].title == title);
+    ok(hasEngine, testCase.text);
     browser.engines = null;
   }
   else
-    ok(!test.pass, test.text);
+    ok(!testCase.pass, testCase.text);
 
   searchDiscoveryTests.shift();
   searchDiscovery(); // Run the next test.
 }
 
 // This handler is called twice, once for each added link element.
 // Only want to check once the second link element has been added.
 var ranOnce = false;
@@ -124,25 +124,25 @@ function runMultipleEnginesTestAndFinali
   finish();
 }
 
 function searchDiscovery() {
   let head = doc().getElementById("linkparent");
 
   if (searchDiscoveryTests.length) {
     setHandlerFunc(runSearchDiscoveryTest);
-    let test = searchDiscoveryTests[0];
+    let testCase = searchDiscoveryTests[0];
     let link = doc().createElement("link");
 
-    let rel = test.rel || "search";
-    let href = test.href || "http://so.not.here.mozilla.com/search.xml";
-    let type = test.type || "application/opensearchdescription+xml";
-    let title = test.title || searchDiscoveryTests.length;
-    if (test.pass == undefined)
-      test.pass = true;
+    let rel = testCase.rel || "search";
+    let href = testCase.href || "http://so.not.here.mozilla.com/search.xml";
+    let type = testCase.type || "application/opensearchdescription+xml";
+    let title = testCase.title || searchDiscoveryTests.length;
+    if (testCase.pass == undefined)
+      testCase.pass = true;
 
     link.rel = rel;
     link.href = href;
     link.type = type;
     link.title = title;
     head.appendChild(link);
   } else {
     setHandlerFunc(runMultipleEnginesTestAndFinalize);
--- a/browser/base/content/test/general/browser_documentnavigation.js
+++ b/browser/base/content/test/general/browser_documentnavigation.js
@@ -25,44 +25,44 @@ function* expectFocusOnF6(backward, expe
     is(msg.data.details, expected, desc + " child focus matches");
     focusChangedInChildResolver();
   }
 
   if (onContent) {
     messageManager.addMessageListener("BrowserTest:FocusChanged", focusChangedListener);
 
     yield ContentTask.spawn(gBrowser.selectedBrowser, { expectedElementId: expectedElement }, function* (arg) {
-      let expectedElement = content.document.getElementById(arg.expectedElementId);
-      if (!expectedElement) {
+      let contentExpectedElement = content.document.getElementById(arg.expectedElementId);
+      if (!contentExpectedElement) {
         // Element not found, so look in the child frames.
         for (let f = 0; f < content.frames.length; f++) {
           if (content.frames[f].document.getElementById(arg.expectedElementId)) {
-            expectedElement = content.frames[f].document;
+            contentExpectedElement = content.frames[f].document;
             break;
           }
         }
       }
-      else if (expectedElement.localName == "html") {
-        expectedElement = expectedElement.ownerDocument;
+      else if (contentExpectedElement.localName == "html") {
+        contentExpectedElement = contentExpectedElement.ownerDocument;
       }
 
-      if (!expectedElement) {
+      if (!contentExpectedElement) {
         sendSyncMessage("BrowserTest:FocusChanged",
                         { details : "expected element " + arg.expectedElementId + " not found" });
         return;
       }
 
-      expectedElement.addEventListener("focus", function focusReceived() {
-        expectedElement.removeEventListener("focus", focusReceived, true);
+      contentExpectedElement.addEventListener("focus", function focusReceived() {
+        contentExpectedElement.removeEventListener("focus", focusReceived, true);
 
-        const fm = Components.classes["@mozilla.org/focus-manager;1"].
-                              getService(Components.interfaces.nsIFocusManager);
-        let details = fm.focusedWindow.document.documentElement.id;
-        if (fm.focusedElement) {
-          details += "," + fm.focusedElement.id;
+        const contentFM = Components.classes["@mozilla.org/focus-manager;1"].
+                            getService(Components.interfaces.nsIFocusManager);
+        let details = contentFM.focusedWindow.document.documentElement.id;
+        if (contentFM.focusedElement) {
+          details += "," + contentFM.focusedElement.id;
         }
 
         sendSyncMessage("BrowserTest:FocusChanged", { details : details });
       }, true);
     });
   }
 
   EventUtils.synthesizeKey("VK_F6", { shiftKey: backward });
--- a/browser/base/content/test/general/browser_e10s_chrome_process.js
+++ b/browser/base/content/test/general/browser_e10s_chrome_process.js
@@ -126,18 +126,18 @@ function* loadURI(browser, uri) {
   return true;
 },
 
 // Loads the new page by finding a link with the right href in the document and
 // clicking it
 function* clickLink(browser, uri) {
   info("Clicking link");
 
-  function frame_script(uri) {
-    let link = content.document.querySelector("a[href='" + uri + "']");
+  function frame_script(frameUri) {
+    let link = content.document.querySelector("a[href='" + frameUri + "']");
     link.click();
   }
 
   browser.messageManager.loadFrameScript("data:,(" + frame_script.toString() + ")(" + JSON.stringify(uri) + ");", false);
 
   return false;
 },
 ];
--- a/browser/base/content/test/general/browser_feed_discovery.js
+++ b/browser/base/content/test/general/browser_feed_discovery.js
@@ -13,21 +13,21 @@ add_task(function* () {
   let discovered = browser.feeds;
   ok(discovered.length > 0, "some feeds should be discovered");
 
   let feeds = {};
   for (let aFeed of discovered) {
     feeds[aFeed.href] = true;
   }
 
-  yield ContentTask.spawn(browser, feeds, function* (feeds) {
+  yield ContentTask.spawn(browser, feeds, function* (contentFeeds) {
     for (let aLink of content.document.getElementsByTagName("link")) {
       // ignore real stylesheets, and anything without an href property
       if (aLink.type != "text/css" && aLink.href) {
         if (/bogus/i.test(aLink.title)) {
-          ok(!feeds[aLink.href], "don't discover " + aLink.href);
+          ok(!contentFeeds[aLink.href], "don't discover " + aLink.href);
         } else {
-          ok(feeds[aLink.href], "should discover " + aLink.href);
+          ok(contentFeeds[aLink.href], "should discover " + aLink.href);
         }
       }
     }
   });
 })
--- a/browser/base/content/test/general/browser_findbarClose.js
+++ b/browser/base/content/test/general/browser_findbarClose.js
@@ -15,19 +15,19 @@ add_task(function* findbar_test() {
   newTab.linkedBrowser.loadURI("http://example.com/browser/" +
     "browser/base/content/test/general/test_bug628179.html");
   yield promise;
 
   gFindBar.open();
 
   yield new ContentTask.spawn(newTab.linkedBrowser, null, function* () {
     let iframe = content.document.getElementById("iframe");
-    let promise = ContentTaskUtils.waitForEvent(iframe, "load", false);
+    let awaitLoad = ContentTaskUtils.waitForEvent(iframe, "load", false);
     iframe.src = "http://example.org/";
-    yield promise;
+    yield awaitLoad;
   });
 
   ok(!gFindBar.hidden, "the Find bar isn't hidden after the location of a " +
      "subdocument changes");
 
   gFindBar.close();
   gBrowser.removeTab(newTab);
   finish();
--- a/browser/base/content/test/general/browser_fullscreen-window-open.js
+++ b/browser/base/content/test/general/browser_fullscreen-window-open.js
@@ -44,19 +44,19 @@ var gTests = [
   test_open_with_innerSize,
   test_open_with_dialog,
   test_open_when_open_new_window_by_pref,
   test_open_with_pref_to_disable_in_fullscreen,
   test_open_from_chrome,
 ];
 
 function runNextTest () {
-  let test = gTests.shift();
-  if (test) {
-    executeSoon(test);
+  let testCase = gTests.shift();
+  if (testCase) {
+    executeSoon(testCase);
   }
   else {
     finish();
   }
 }
 
 
 // Test for window.open() with no feature.
--- a/browser/base/content/test/general/browser_fxa_oauth.js
+++ b/browser/base/content/test/general/browser_fxa_oauth.js
@@ -308,19 +308,19 @@ function test() {
   waitForExplicitFinish();
 
   Task.spawn(function* () {
     const webchannelWhitelistPref = "webchannel.allowObject.urlWhitelist";
     let origWhitelist = Services.prefs.getCharPref(webchannelWhitelistPref);
     let newWhitelist = origWhitelist + " http://example.com";
     Services.prefs.setCharPref(webchannelWhitelistPref, newWhitelist);
     try {
-      for (let test of gTests) {
-        info("Running: " + test.desc);
-        yield test.run();
+      for (let testCase of gTests) {
+        info("Running: " + testCase.desc);
+        yield testCase.run();
       }
     } finally {
       Services.prefs.clearUserPref(webchannelWhitelistPref);
     }
   }).then(finish, ex => {
     Assert.ok(false, "Unexpected Exception: " + ex);
     finish();
   });
--- a/browser/base/content/test/general/browser_fxa_web_channel.js
+++ b/browser/base/content/test/general/browser_fxa_web_channel.js
@@ -194,17 +194,17 @@ function makeObserver(aObserveTopic, aOb
   Services.obs.addObserver(callback, aObserveTopic, false);
   return removeMe;
 }
 
 function test() {
   waitForExplicitFinish();
 
   Task.spawn(function* () {
-    for (let test of gTests) {
-      info("Running: " + test.desc);
-      yield test.run();
+    for (let testCase of gTests) {
+      info("Running: " + testCase.desc);
+      yield testCase.run();
     }
   }).then(finish, ex => {
     Assert.ok(false, "Unexpected Exception: " + ex);
     finish();
   });
 }
--- a/browser/base/content/test/general/browser_fxaccounts.js
+++ b/browser/base/content/test/general/browser_fxaccounts.js
@@ -178,20 +178,20 @@ function configureProfileURL(profile, re
             // .sjs as part of the query string.
             "&path=";
 
   Services.prefs.setCharPref("identity.fxaccounts.remote.profile.uri", url);
 }
 
 function promiseObserver(topic, count = 1) {
   return new Promise(resolve => {
-    let obs = (subject, topic, data) => {
+    let obs = (aSubject, aTopic, aData) => {
       if (--count == 0) {
-        Services.obs.removeObserver(obs, topic);
-        resolve(subject);
+        Services.obs.removeObserver(obs, aTopic);
+        resolve(aSubject);
       }
     }
     Services.obs.addObserver(obs, topic, false);
   });
 }
 
 // Stolen from browser_aboutHome.js
 function promiseWaitForEvent(node, type, capturing) {
--- a/browser/base/content/test/general/browser_page_style_menu.js
+++ b/browser/base/content/test/general/browser_page_style_menu.js
@@ -45,53 +45,53 @@ add_task(function*() {
     items.push(current);
   }
 
   items = items.map(el => ({
     label: el.getAttribute("label"),
     checked: el.getAttribute("checked") == "true",
   }));
 
-  let validLinks = yield ContentTask.spawn(gBrowser.selectedBrowser, items, function(items) {
-    let validLinks = 0;
+  let validLinks = yield ContentTask.spawn(gBrowser.selectedBrowser, items, function(contentItems) {
+    let contentValidLinks = 0;
     Array.forEach(content.document.querySelectorAll("link, style"), function (el) {
       var title = el.getAttribute("title");
       var rel = el.getAttribute("rel");
       var media = el.getAttribute("media");
       var idstring = el.nodeName + " " + (title ? title : "without title and") +
                      " with rel=\"" + rel + "\"" +
                      (media ? " and media=\"" + media + "\"" : "");
 
-      var item = items.filter(item => item.label == title);
+      var item = contentItems.filter(aItem => aItem.label == title);
       var found = item.length == 1;
       var checked = found && item[0].checked;
 
       switch (el.getAttribute("data-state")) {
         case "0":
           ok(!found, idstring + " should not show up in page style menu");
           break;
         case "0-todo":
-          validLinks++;
+          contentValidLinks++;
           todo(!found, idstring + " should not show up in page style menu");
           ok(!checked, idstring + " should not be selected");
           break;
         case "1":
-          validLinks++;
+          contentValidLinks++;
           ok(found, idstring + " should show up in page style menu");
           ok(!checked, idstring + " should not be selected");
           break;
         case "2":
-          validLinks++;
+          contentValidLinks++;
           ok(found, idstring + " should show up in page style menu");
           ok(checked, idstring + " should be selected");
           break;
         default:
           throw "data-state attribute is missing or has invalid value";
       }
     });
-    return validLinks;
+    return contentValidLinks;
   });
 
   ok(items.length, "At least one item in the menu");
   is(items.length, validLinks, "all valid links found");
 
   yield BrowserTestUtils.removeTab(tab);
 });
--- a/browser/base/content/test/general/browser_popup_blocker.js
+++ b/browser/base/content/test/general/browser_popup_blocker.js
@@ -48,17 +48,17 @@ function test() {
     }
     gBrowser.tabContainer.addEventListener("TabOpen", onTabOpen);
 
     // Press the button.
     let allow = menu.querySelector("[observes='blockedPopupAllowSite']");
     allow.doCommand();
     yield promiseWaitForCondition(() =>
       popupTabs.length == 2 &&
-      popupTabs.every(tab => tab.linkedBrowser.currentURI.spec != "about:blank"));
+      popupTabs.every(aTab => aTab.linkedBrowser.currentURI.spec != "about:blank"));
 
     gBrowser.tabContainer.removeEventListener("TabOpen", onTabOpen);
 
     is(popupTabs[0].linkedBrowser.currentURI.spec, "data:text/plain;charset=utf-8,a", "Popup a");
     is(popupTabs[1].linkedBrowser.currentURI.spec, "data:text/plain;charset=utf-8,b", "Popup b");
 
     // Clean up.
     gBrowser.removeTab(tab);
--- a/browser/base/content/test/general/browser_refreshBlocker.js
+++ b/browser/base/content/test/general/browser_refreshBlocker.js
@@ -12,22 +12,22 @@ const PREF = "accessibility.blockautoref
  *
  * @param browser (<xul:browser>)
  *        The browser to test for refreshing.
  * @param expectRefresh (bool)
  *        Whether or not we expect the refresh attempt to succeed.
  * @returns Promise
  */
 function* attemptFakeRefresh(browser, expectRefresh) {
-  yield ContentTask.spawn(browser, expectRefresh, function*(expectRefresh) {
+  yield ContentTask.spawn(browser, expectRefresh, function*(contentExpectRefresh) {
     let URI = docShell.QueryInterface(Ci.nsIWebNavigation).currentURI;
     let refresher = docShell.QueryInterface(Ci.nsIRefreshURI);
     refresher.refreshURI(URI, 0, false, true);
 
-    Assert.equal(refresher.refreshPending, expectRefresh,
+    Assert.equal(refresher.refreshPending, contentExpectRefresh,
       "Got the right refreshPending state");
 
     if (refresher.refreshPending) {
       // Cancel the pending refresh
       refresher.cancelRefreshURITimers();
     }
 
     // The RefreshBlocker will wait until onLocationChange has
--- a/browser/base/content/test/general/browser_sanitizeDialog.js
+++ b/browser/base/content/test/general/browser_sanitizeDialog.js
@@ -579,17 +579,17 @@ add_task(function* test_offline_cache() 
     };
     storage.asyncVisitStorage(visitor, false);
     // Offline cache visit happens synchronously, since it's forwarded to the old code
     is(size, 0, "offline application cache entries evicted");
   };
 
   var cacheListener = {
     onCacheEntryCheck: function() { return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED; },
-    onCacheEntryAvailable: function (entry, isnew, appcache, status) {
+    onCacheEntryAvailable: function (entry, isnew, unused, status) {
       is(status, Cr.NS_OK);
       var stream = entry.openOutputStream(0);
       var content = "content";
       stream.write(content, content.length);
       stream.close();
       entry.close();
       wh.open();
     }
--- a/browser/base/content/test/general/browser_save_link-perwindowpb.js
+++ b/browser/base/content/test/general/browser_save_link-perwindowpb.js
@@ -59,19 +59,19 @@ function triggerSave(aWindow, aCallback)
     var saveLinkCommand = aWindow.document.getElementById("context-savelink");
     info("saveLinkCommand: " + saveLinkCommand);
     saveLinkCommand.doCommand();
 
     event.target.hidePopup();
     info("popup hidden");
   }
 
-  function onTransferComplete(aWindow, downloadSuccess, destDir) {
+  function onTransferComplete(aWindow2, downloadSuccess, destDir) {
     ok(downloadSuccess, "Link should have been downloaded successfully");
-    aWindow.close();
+    aWindow2.close();
 
     executeSoon(() => aCallback());
   }
 }
 
 function test() {
   info("Start the test");
   waitForExplicitFinish();
@@ -81,20 +81,20 @@ function test() {
     info("testOnWindow(" + options + ")");
     var win = OpenBrowserWindow(options);
     info("got " + win);
     whenDelayedStartupFinished(win, () => callback(win));
   }
 
   function whenDelayedStartupFinished(aWindow, aCallback) {
     info("whenDelayedStartupFinished");
-    Services.obs.addObserver(function observer(aSubject, aTopic) {
+    Services.obs.addObserver(function obs(aSubject, aTopic) {
       info("whenDelayedStartupFinished, got topic: " + aTopic + ", got subject: " + aSubject + ", waiting for " + aWindow);
       if (aWindow == aSubject) {
-        Services.obs.removeObserver(observer, aTopic);
+        Services.obs.removeObserver(obs, aTopic);
         executeSoon(aCallback);
         info("whenDelayedStartupFinished found our window");
       }
     }, "browser-delayed-startup-finished", false);
   }
 
   mockTransferRegisterer.register();
 
@@ -165,18 +165,18 @@ function test() {
   Services.obs.addObserver(observer, "http-on-examine-response", false);
 
   testOnWindow(undefined, function(win) {
     // The first save from a regular window sets a cookie.
     triggerSave(win, function() {
       is(gNumSet, 1, "1 cookie should be set");
 
       // The second save from a private window also sets a cookie.
-      testOnWindow({private: true}, function(win) {
-        triggerSave(win, function() {
+      testOnWindow({private: true}, function(win2) {
+        triggerSave(win2, function() {
           is(gNumSet, 2, "2 cookies should be set");
           finish();
         });
       });
     });
   });
 }
 
--- a/browser/base/content/test/general/browser_save_link_when_window_navigates.js
+++ b/browser/base/content/test/general/browser_save_link_when_window_navigates.js
@@ -75,19 +75,19 @@ function triggerSave(aWindow, aCallback)
         win.document.documentElement._fireButtonEvent("accept");
         win.close();
         return;
       }
     }
     ok(false, "No Unknown Content Type dialog yet?");
   }
 
-  function onTransferComplete(aWindow, downloadSuccess, destDir) {
+  function onTransferComplete(aWindow2, downloadSuccess) {
     ok(downloadSuccess, "Link should have been downloaded successfully");
-    aWindow.close();
+    aWindow2.close();
 
     executeSoon(aCallback);
   }
 }
 
 
 var windowObserver = {
   setCallback: function(aCallback) {
@@ -158,16 +158,16 @@ function test() {
 
   Services.prefs.setBoolPref(ALWAYS_DOWNLOAD_DIR_PREF, false);
   testOnWindow(undefined, function(win) {
     let windowGonePromise = promiseWindowWillBeClosed(win);
     Services.prefs.setBoolPref(SAVE_PER_SITE_PREF, true);
     triggerSave(win, function() {
       windowGonePromise.then(function() {
         Services.prefs.setBoolPref(SAVE_PER_SITE_PREF, false);
-        testOnWindow(undefined, function(win) {
-          triggerSave(win, finish);
+        testOnWindow(undefined, function(win2) {
+          triggerSave(win2, finish);
         });
       });
     });
   });
 }
 
--- a/browser/base/content/test/general/browser_selectpopup.js
+++ b/browser/base/content/test/general/browser_selectpopup.js
@@ -265,46 +265,46 @@ add_task(function*() {
     [ "frame", "border-top: 5px solid green; border-left: 10px solid red; border-right: 35px solid blue;", 10, 5 ],
     [ "frame", "border: none; padding-left: 6px; padding-right: 12px; padding-top: 2px;", -4, -3 ],
     [ "select", "margin: 9px; transform: translateY(-3px);", 9, 6 ],
   ];
 
   for (let stepIndex = 0; stepIndex < steps.length; stepIndex++) {
     let step = steps[stepIndex];
 
-    yield ContentTask.spawn(gBrowser.selectedBrowser, step, function*(step) {
+    yield ContentTask.spawn(gBrowser.selectedBrowser, step, function*(contentStep) {
       return new Promise(resolve => {
         let changedWin = content;
 
         let elem;
-        if (step[0] == "select") {
+        if (contentStep[0] == "select") {
           changedWin = content.document.getElementById("frame").contentWindow;
           elem = changedWin.document.getElementById("select");
         }
         else {
-          elem = content.document.getElementById(step[0]);
+          elem = content.document.getElementById(contentStep[0]);
         }
 
         changedWin.addEventListener("MozAfterPaint", function onPaint() {
           changedWin.removeEventListener("MozAfterPaint", onPaint);
           resolve();
         });
 
-        elem.style = step[1];
+        elem.style = contentStep[1];
       });
     });
 
     yield openSelectPopup(selectPopup, false);
 
     expectedX += step[2];
     expectedY += step[3];
 
-    let rect = selectPopup.getBoundingClientRect();
-    is(rect.left, expectedX, "step " + (stepIndex + 1) + " x");
-    is(rect.top, expectedY, "step " + (stepIndex + 1) + " y");
+    let popupRect = selectPopup.getBoundingClientRect();
+    is(popupRect.left, expectedX, "step " + (stepIndex + 1) + " x");
+    is(popupRect.top, expectedY, "step " + (stepIndex + 1) + " y");
 
     yield hideSelectPopup(selectPopup);
   }
 
   yield BrowserTestUtils.removeTab(tab);
 });
 
 // Test that we get the right events when a select popup is changed.
@@ -360,38 +360,36 @@ add_task(function* test_event_order() {
         targetIsOption: true,
       },
     ];
 
     for (let mode of ["enter", "click"]) {
       let expected = mode == "enter" ? expectedEnter : expectedClick;
       yield openSelectPopup(selectPopup, true, mode == "enter" ? "#one" : "#two");
 
-      let eventsPromise = ContentTask.spawn(browser, { mode, expected }, function*(args) {
-        let expected = args.expected;
-
+      let eventsPromise = ContentTask.spawn(browser, [mode, expected], function*([contentMode, contentExpected]) {
         return new Promise((resolve) => {
           function onEvent(event) {
             select.removeEventListener(event.type, onEvent);
-            Assert.ok(expected.length, "Unexpected event " + event.type);
-            let expectation = expected.shift();
+            Assert.ok(contentExpected.length, "Unexpected event " + event.type);
+            let expectation = contentExpected.shift();
             Assert.equal(event.type, expectation.type,
                          "Expected the right event order");
             Assert.ok(event.bubbles, "All of these events should bubble");
             Assert.equal(event.cancelable, expectation.cancelable,
                          "Cancellation property should match");
             Assert.equal(event.target.localName,
                          expectation.targetIsOption ? "option" : "select",
                          "Target matches");
-            if (!expected.length) {
+            if (!contentExpected.length) {
               resolve();
             }
           }
 
-          let select = content.document.getElementById(args.mode == "enter" ? "one" : "two");
+          let select = content.document.getElementById(contentMode == "enter" ? "one" : "two");
           for (let event of ["input", "change", "mousedown", "mouseup", "click"]) {
             select.addEventListener(event, onEvent);
           }
         });
       });
 
       EventUtils.synthesizeKey("KEY_ArrowDown", { code: "ArrowDown" });
       yield hideSelectPopup(selectPopup, mode);
@@ -445,19 +443,19 @@ function* performLargePopupTests(win)
     yield hideSelectPopup(selectPopup, "enter", win);
 
     position = positions.shift();
     if (!position) {
       break;
     }
 
     let contentPainted = BrowserTestUtils.contentPainted(browser);
-    yield ContentTask.spawn(browser, position, function*(position) {
+    yield ContentTask.spawn(browser, position, function*(contentPosition) {
       let select = content.document.getElementById("one");
-      select.setAttribute("style", position);
+      select.setAttribute("style", contentPosition);
     });
     yield contentPainted;
   }
 }
 
 // This test checks select elements with a large number of options to ensure that
 // the popup appears within the browser area.
 add_task(function* test_large_popup() {
--- a/browser/base/content/test/general/browser_syncui.js
+++ b/browser/base/content/test/general/browser_syncui.js
@@ -39,19 +39,19 @@ function checkBroadcasterVisible(broadca
   for (let check of all) {
     let eltHidden = document.getElementById(check).hidden;
     Assert.equal(eltHidden, check == broadcasterId ? false : true, check);
   }
 }
 
 function promiseObserver(topic) {
   return new Promise(resolve => {
-    let obs = (subject, topic, data) => {
-      Services.obs.removeObserver(obs, topic);
-      resolve(subject);
+    let obs = (aSubject, aTopic, aData) => {
+      Services.obs.removeObserver(obs, aTopic);
+      resolve(aSubject);
     }
     Services.obs.addObserver(obs, topic, false);
   });
 }
 
 function checkButtonTooltips(stringPrefix) {
   for (let butId of ["PanelUI-remotetabs-syncnow", "PanelUI-fxa-icon"]) {
     let text = document.getElementById(butId).getAttribute("tooltiptext");
--- a/browser/base/content/test/general/browser_tabfocus.js
+++ b/browser/base/content/test/general/browser_tabfocus.js
@@ -58,17 +58,17 @@ function* getFocusedElementForBrowser(br
   }
   var focusedWindow = {};
   var node = fm.getFocusedElementForWindow(browser.contentWindow, false, focusedWindow);
   return "Focus is " + (node ? node.id : "<none>");
 }
 
 function focusInChild()
 {
-  var fm = Components.classes["@mozilla.org/focus-manager;1"].
+  var contentFM = Components.classes["@mozilla.org/focus-manager;1"].
                       getService(Components.interfaces.nsIFocusManager);
 
   function getWindowDocId(target)
   {
     return (String(target.location).indexOf("1") >= 0) ? "window1" : "window2";
   }
 
   function eventListener(event) {
@@ -86,34 +86,34 @@ function focusInChild()
   addEventListener("blur", eventListener, true);
 
   addMessageListener("Browser:ChangeFocus", function changeFocus(message) {
     content.document.getElementById(message.data.id)[message.data.type]();
   });
 
   addMessageListener("Browser:GetFocusedElement", function getFocusedElement(message) {
     var focusedWindow = {};
-    var node = fm.getFocusedElementForWindow(content, false, focusedWindow);
+    var node = contentFM.getFocusedElementForWindow(content, false, focusedWindow);
     var details = "Focus is " + (node ? node.id : "<none>");
 
     /* Check focus manager properties. Add an error onto the string if they are
        not what is expected which will cause matching to fail in the parent process. */
     let doc = content.document;
     if (!message.data.dontCheckExtraFocus) {
-      if (fm.focusedElement != node) {
+      if (contentFM.focusedElement != node) {
         details += "<ERROR: focusedElement doesn't match>";
       }
-      if (fm.focusedWindow && fm.focusedWindow != content) {
+      if (contentFM.focusedWindow && contentFM.focusedWindow != content) {
         details += "<ERROR: focusedWindow doesn't match>";
       }
-      if ((fm.focusedWindow == content) != doc.hasFocus()) {
+      if ((contentFM.focusedWindow == content) != doc.hasFocus()) {
         details += "<ERROR: child hasFocus() is not correct>";
       }
-      if ((fm.focusedElement && doc.activeElement != fm.focusedElement) ||
-          (!fm.focusedElement && doc.activeElement != doc.body)) {
+      if ((contentFM.focusedElement && doc.activeElement != contentFM.focusedElement) ||
+          (!contentFM.focusedElement && doc.activeElement != doc.body)) {
         details += "<ERROR: child activeElement is not correct>";
       }
     }
 
     sendSyncMessage("Browser:GetCurrentFocus", { details : details });
   });
 }
 
@@ -155,17 +155,16 @@ add_task(function*() {
 
   _lastfocus = "urlbar";
   _lastfocuswindow = "main-window";
 
   window.addEventListener("focus", _browser_tabfocus_test_eventOccured, true);
   window.addEventListener("blur", _browser_tabfocus_test_eventOccured, true);
 
   // make sure that the focus initially starts out blank
-  var fm = Services.focus;
   var focusedWindow = {};
 
   let focused = yield getFocusedElementForBrowser(browser1);
   is(focused, "Focus is <none>", "initial focus in tab 1");
 
   focused = yield getFocusedElementForBrowser(browser2);
   is(focused, "Focus is <none>", "initial focus in tab 2");
 
@@ -368,29 +367,29 @@ add_task(function*() {
   window.removeEventListener("blur", _browser_tabfocus_test_eventOccured, true);
 
   gBrowser.removeCurrentTab();
   gBrowser.removeCurrentTab();
 
   finish();
 });
 
-function getWindowDocId(target)
-{
-  if (target == browser1.contentWindow || target == browser1.contentDocument) {
-    return "window1";
-  }
-  if (target == browser2.contentWindow || target == browser2.contentDocument) {
-    return "window2";
-  }
-  return "main-window";
-}
-
 function _browser_tabfocus_test_eventOccured(event)
 {
+  function getWindowDocId(target)
+  {
+    if (target == browser1.contentWindow || target == browser1.contentDocument) {
+      return "window1";
+    }
+    if (target == browser2.contentWindow || target == browser2.contentDocument) {
+      return "window2";
+    }
+    return "main-window";
+  }
+
   var id;
 
   // Some focus events from the child bubble up? Ignore them.
   if (Cu.isCrossProcessWrapper(event.originalTarget))
     return;
 
   if (event.target instanceof Window)
     id = getWindowDocId(event.originalTarget) + "-window";
--- a/browser/base/content/test/general/browser_web_channel.js
+++ b/browser/base/content/test/general/browser_web_channel.js
@@ -125,29 +125,29 @@ var gTests = [
 
       let preRedirectChannel = new WebChannel("pre_redirect", Services.io.newURI(HTTP_IFRAME_PATH, null, null));
       let postRedirectChannel = new WebChannel("post_redirect", Services.io.newURI(HTTP_REDIRECTED_IFRAME_PATH, null, null));
 
       let promiseTestDone = new Promise(function (resolve, reject) {
         preRedirectChannel.listen(function (id, message, preRedirectSender) {
           if (message.command === "redirecting") {
 
-            postRedirectChannel.listen(function (id, message, postRedirectSender) {
-              is(id, "post_redirect");
-              isnot(message.command, "no_response_expected");
+            postRedirectChannel.listen(function (aId, aMessage, aPostRedirectSender) {
+              is(aId, "post_redirect");
+              isnot(aMessage.command, "no_response_expected");
 
-              if (message.command === "loaded") {
+              if (aMessage.command === "loaded") {
                 // The message should not be received on the preRedirectChannel
                 // because the target window has redirected.
                 preRedirectChannel.send({ command: "no_response_expected" }, preRedirectSender);
-                postRedirectChannel.send({ command: "done" }, postRedirectSender);
-              } else if (message.command === "done") {
+                postRedirectChannel.send({ command: "done" }, aPostRedirectSender);
+              } else if (aMessage.command === "done") {
                 resolve();
               } else {
-                reject(new Error(`Unexpected command ${message.command}`));
+                reject(new Error(`Unexpected command ${aMessage.command}`));
               }
             });
           } else {
             reject(new Error(`Unexpected command ${message.command}`));
           }
         });
       });
 
@@ -398,17 +398,17 @@ var gTests = [
     }
   }
 ]; // gTests
 
 function test() {
   waitForExplicitFinish();
 
   Task.spawn(function* () {
-    for (let test of gTests) {
-      info("Running: " + test.desc);
-      yield test.run();
+    for (let testCase of gTests) {
+      info("Running: " + testCase.desc);
+      yield testCase.run();
     }
   }).then(finish, ex => {
     ok(false, "Unexpected Exception: " + ex);
     finish();
   });
 }
--- a/browser/base/content/test/general/content_aboutAccounts.js
+++ b/browser/base/content/test/general/content_aboutAccounts.js
@@ -25,27 +25,27 @@ addEventListener("DOMContentLoaded", fun
   removeEventListener("DOMContentLoaded", domContentLoaded, true);
   let iframe = content.document.getElementById("remote");
   if (!iframe) {
     // at least one test initially loads about:blank - in that case, we are done.
     return;
   }
   // We use DOMContentLoaded here as that fires for our iframe even when we've
   // arranged for the URL in the iframe to cause an error.
-  addEventListener("DOMContentLoaded", function iframeLoaded(event) {
+  addEventListener("DOMContentLoaded", function iframeLoaded(dclEvent) {
     if (iframe.contentWindow.location.href == "about:blank" ||
-        event.target != iframe.contentDocument) {
+        dclEvent.target != iframe.contentDocument) {
       return;
     }
     removeEventListener("DOMContentLoaded", iframeLoaded, true);
     sendAsyncMessage("test:iframe:load", {url: iframe.contentDocument.location.href});
     // And an event listener for the test responses, which we send to the test
     // via a message.
-    iframe.contentWindow.addEventListener("FirefoxAccountsTestResponse", function (event) {
-      sendAsyncMessage("test:response", {data: event.detail.data});
+    iframe.contentWindow.addEventListener("FirefoxAccountsTestResponse", function (fxAccountsEvent) {
+      sendAsyncMessage("test:response", {data: fxAccountsEvent.detail.data});
     }, true);
   }, true);
 }, true);
 
 // Return the visibility state of a list of ids.
 addMessageListener("test:check-visibilities", function (message) {
   let result = {};
   for (let id of message.data.ids) {
@@ -67,19 +67,19 @@ addMessageListener("test:check-visibilit
 });
 
 addMessageListener("test:load-with-mocked-profile-path", function (message) {
   addEventListener("DOMContentLoaded", function domContentLoaded(event) {
     removeEventListener("DOMContentLoaded", domContentLoaded, true);
     content.getDefaultProfilePath = () => message.data.profilePath;
     // now wait for the iframe to load.
     let iframe = content.document.getElementById("remote");
-    iframe.addEventListener("load", function iframeLoaded(event) {
+    iframe.addEventListener("load", function iframeLoaded(loadEvent) {
       if (iframe.contentWindow.location.href == "about:blank" ||
-          event.target != iframe) {
+          loadEvent.target != iframe) {
         return;
       }
       iframe.removeEventListener("load", iframeLoaded, true);
       sendAsyncMessage("test:load-with-mocked-profile-path-response",
                        {url: iframe.contentDocument.location.href});
     }, true);
   });
   let webNav = docShell.QueryInterface(Ci.nsIWebNavigation);
--- a/browser/base/content/test/general/contextmenu_common.js
+++ b/browser/base/content/test/general/contextmenu_common.js
@@ -253,39 +253,39 @@ function* test_contextmenu(selector, men
 
   // Default to centered if no positioning is defined.
   if (!options.offsetX && !options.offsetY) {
     options.centered = true;
   }
 
   if (!options.skipFocusChange) {
     yield ContentTask.spawn(gBrowser.selectedBrowser,
-                            {lastElementSelector, selector},
-                            function*({lastElementSelector, selector}) {
-      if (lastElementSelector) {
-        let lastElement = content.document.querySelector(lastElementSelector);
-        lastElement.blur();
+                            [lastElementSelector, selector],
+                            function*([contentLastElementSelector, contentSelector]) {
+      if (contentLastElementSelector) {
+        let contentLastElement = content.document.querySelector(contentLastElementSelector);
+        contentLastElement.blur();
       }
-      let element = content.document.querySelector(selector);
+      let element = content.document.querySelector(contentSelector);
       element.focus();
     });
     lastElementSelector = selector;
     info(`Moved focus to ${selector}`);
   }
 
   if (options.preCheckContextMenuFn) {
     yield options.preCheckContextMenuFn();
     info("Completed preCheckContextMenuFn");
   }
 
   if (options.waitForSpellCheck) {
     info("Waiting for spell check");
-    yield ContentTask.spawn(gBrowser.selectedBrowser, selector, function*(selector) {
+    yield ContentTask.spawn(gBrowser.selectedBrowser, selector, function*(contentSelector) {
       let {onSpellCheck} = Cu.import("resource://gre/modules/AsyncSpellCheckTestHelper.jsm", {});
-      let element = content.document.querySelector(selector);
+      let element = content.document.querySelector(contentSelector);
       yield new Promise(resolve => onSpellCheck(element, resolve));
       info("Spell check running");
     });
   }
 
   let awaitPopupShown = BrowserTestUtils.waitForEvent(contextMenu, "popupshown");
   yield BrowserTestUtils.synthesizeMouse(selector, options.offsetX || 0, options.offsetY || 0, {
       type: "contextmenu",
--- a/browser/base/content/test/general/head.js
+++ b/browser/base/content/test/general/head.js
@@ -322,17 +322,17 @@ function waitForAsyncUpdates(aCallback, 
  * @param aURI The URI.
  * @param aExpectedValue The expected value.
  * @return {Promise}
  * @resolves When the check has been added successfully.
  * @rejects JavaScript exception.
  */
 function promiseIsURIVisited(aURI, aExpectedValue) {
   let deferred = Promise.defer();
-  PlacesUtils.asyncHistory.isURIVisited(aURI, function(aURI, aIsVisited) {
+  PlacesUtils.asyncHistory.isURIVisited(aURI, function(unused, aIsVisited) {
     deferred.resolve(aIsVisited);
   });
 
   return deferred.promise;
 }
 
 function whenNewTabLoaded(aWindow, aCallback) {
   aWindow.BrowserOpenTab();
@@ -368,19 +368,19 @@ function promiseHistoryClearedState(aURI
   let deferred = Promise.defer();
   let callbackCount = 0;
   let niceStr = aShouldBeCleared ? "no longer" : "still";
   function callbackDone() {
     if (++callbackCount == aURIs.length)
       deferred.resolve();
   }
   aURIs.forEach(function (aURI) {
-    PlacesUtils.asyncHistory.isURIVisited(aURI, function(aURI, aIsVisited) {
-      is(aIsVisited, !aShouldBeCleared,
-         "history visit " + aURI.spec + " should " + niceStr + " exist");
+    PlacesUtils.asyncHistory.isURIVisited(aURI, function(uri, isVisited) {
+      is(isVisited, !aShouldBeCleared,
+         "history visit " + uri.spec + " should " + niceStr + " exist");
       callbackDone();
     });
   });
 
   return deferred.promise;
 }
 
 /**
@@ -395,17 +395,17 @@ function promiseHistoryClearedState(aURI
  *        If you're using this method to avoid hitting the network, you want the default (true).
  *        However, the browser UI will behave differently for loads stopped directly from
  *        the progress listener (effectively in the middle of a call to loadURI) and so there
  *        are cases where you may want to avoid stopping the load directly from within the
  *        progress listener callback.
  * @return promise
  */
 function waitForDocLoadAndStopIt(aExpectedURL, aBrowser=gBrowser.selectedBrowser, aStopFromProgressListener=true) {
-  function content_script(aStopFromProgressListener) {
+  function content_script(contentStopFromProgressListener) {
     let { interfaces: Ci, utils: Cu } = Components;
     Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
     let wp = docShell.QueryInterface(Ci.nsIWebProgress);
 
     function stopContent(now, uri) {
       if (now) {
         /* Hammer time. */
         content.stop();
@@ -423,17 +423,17 @@ function waitForDocLoadAndStopIt(aExpect
 
         if (webProgress.isTopLevel &&
             flags & Ci.nsIWebProgressListener.STATE_START) {
           wp.removeProgressListener(progressListener);
 
           let chan = req.QueryInterface(Ci.nsIChannel);
           dump(`waitForDocLoadAndStopIt: Document start: ${chan.URI.spec}\n`);
 
-          stopContent(aStopFromProgressListener, chan.originalURI.spec);
+          stopContent(contentStopFromProgressListener, chan.originalURI.spec);
         }
       },
       QueryInterface: XPCOMUtils.generateQI(["nsISupportsWeakReference"])
     };
     wp.addProgressListener(progressListener, wp.NOTIFY_STATE_WINDOW);
 
     /**
      * As |this| is undefined and we can't extend |docShell|, adding an unload
@@ -903,18 +903,18 @@ function promiseNotificationShown(notifi
  * @resolves An object with subject and data properties from the observed
  *           notification.
  * @rejects Never.
  */
 function promiseTopicObserved(aTopic)
 {
   return new Promise((resolve) => {
     Services.obs.addObserver(
-      function PTO_observe(aSubject, aTopic, aData) {
-        Services.obs.removeObserver(PTO_observe, aTopic);
+      function PTO_observe(aSubject, aTopic2, aData) {
+        Services.obs.removeObserver(PTO_observe, aTopic2);
         resolve({subject: aSubject, data: aData});
       }, aTopic, false);
   });
 }
 
 function promiseNewSearchEngine(basename) {
   return new Promise((resolve, reject) => {
     info("Waiting for engine to be added: " + basename);
@@ -1040,17 +1040,17 @@ function getPropertyBagValue(bag, key) {
  *        will contain other extra information that is not
  *        compared against.
  * @returns Promise
  */
 function promiseCrashReport(expectedExtra={}) {
   return Task.spawn(function*() {
     info("Starting wait on crash-report-status");
     let [subject, ] =
-      yield TestUtils.topicObserved("crash-report-status", (subject, data) => {
+      yield TestUtils.topicObserved("crash-report-status", (unused, data) => {
         return data == "success";
       });
     info("Topic observed!");
 
     if (!(subject instanceof Ci.nsIPropertyBag2)) {
       throw new Error("Subject was not a Ci.nsIPropertyBag2");
     }
 
--- a/browser/base/content/test/urlbar/browser_action_keyword.js
+++ b/browser/base/content/test/urlbar/browser_action_keyword.js
@@ -15,17 +15,17 @@ add_task(function*() {
   let tab = gBrowser.selectedTab = gBrowser.addTab("about:mozilla");
   let tabs = [tab];
   registerCleanupFunction(function* () {
     for (let tab of tabs)
       gBrowser.removeTab(tab);
     yield PlacesUtils.bookmarks.remove(bm);
   });
 
-  yield promiseTabLoadEvent(tab);
+  yield BrowserTestUtils.browserLoaded(tab.linkedBrowser);
 
   let bm = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
                                                 url: "http://example.com/?q=%s",
                                                 title: "test" });
   yield PlacesUtils.keywords.insert({ keyword: "keyword",
                                       url: "http://example.com/?q=%s" });
 
   let result = yield promise_first_result("keyword something");
@@ -34,17 +34,17 @@ add_task(function*() {
   let types = new Set(result.getAttribute("type").split(/\s+/));
   Assert.ok(types.has("keyword"));
   is(result.getAttribute("actiontype"), "keyword", "Expect correct `actiontype` attribute");
   is(result.getAttribute("title"), "example.com", "Expect correct title");
 
   // We need to make a real URI out of this to ensure it's normalised for
   // comparison.
   let uri = NetUtil.newURI(result.getAttribute("url"));
-  is(uri.spec, makeActionURI("keyword", {url: "http://example.com/?q=something", input: "keyword something"}).spec, "Expect correct url");
+  is(uri.spec, PlacesUtils.mozActionURI("keyword", {url: "http://example.com/?q=something", input: "keyword something"}), "Expect correct url");
 
   let titleHbox = result._titleText.parentNode.parentNode;
   ok(titleHbox.classList.contains("ac-title"), "Title hbox element sanity check");
   is_element_visible(titleHbox, "Title element should be visible");
   is(result._titleText.textContent, "example.com: something", "Node should contain the name of the bookmark and query");
 
   let urlHbox = result._urlText.parentNode.parentNode;
   ok(urlHbox.classList.contains("ac-url"), "URL hbox element sanity check");
@@ -52,30 +52,30 @@ add_task(function*() {
 
   let actionHbox = result._actionText.parentNode.parentNode;
   ok(actionHbox.classList.contains("ac-action"), "Action hbox element sanity check");
   is_element_visible(actionHbox, "Action element should be visible");
   is(result._actionText.textContent, "", "Action text should be empty");
 
   // Click on the result
   info("Normal click on result");
-  let tabPromise = promiseTabLoadEvent(tab);
+  let tabPromise = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
   EventUtils.synthesizeMouseAtCenter(result, {});
   yield tabPromise;
   is(tab.linkedBrowser.currentURI.spec, "http://example.com/?q=something", "Tab should have loaded from clicking on result");
 
   // Middle-click on the result
   info("Middle-click on result");
   result = yield promise_first_result("keyword somethingmore");
   isnot(result, null, "Expect a keyword result");
   // We need to make a real URI out of this to ensure it's normalised for
   // comparison.
   uri = NetUtil.newURI(result.getAttribute("url"));
-  is(uri.spec, makeActionURI("keyword", {url: "http://example.com/?q=somethingmore", input: "keyword somethingmore"}).spec, "Expect correct url");
+  is(uri.spec, PlacesUtils.mozActionURI("keyword", {url: "http://example.com/?q=somethingmore", input: "keyword somethingmore"}), "Expect correct url");
 
   tabPromise = BrowserTestUtils.waitForEvent(gBrowser.tabContainer, "TabOpen");
   EventUtils.synthesizeMouseAtCenter(result, {button: 1});
   let tabOpenEvent = yield tabPromise;
   let newTab = tabOpenEvent.target;
   tabs.push(newTab);
-  yield promiseTabLoadEvent(newTab);
+  yield BrowserTestUtils.browserLoaded(newTab.linkedBrowser);
   is(newTab.linkedBrowser.currentURI.spec, "http://example.com/?q=somethingmore", "Tab should have loaded from middle-clicking on result");
 });
--- a/browser/base/content/test/urlbar/browser_action_searchengine.js
+++ b/browser/base/content/test/urlbar/browser_action_searchengine.js
@@ -1,17 +1,16 @@
 add_task(function* () {
   Services.search.addEngineWithDetails("MozSearch", "", "", "", "GET",
                                        "http://example.com/?q={searchTerms}");
   let engine = Services.search.getEngineByName("MozSearch");
   let originalEngine = Services.search.currentEngine;
   Services.search.currentEngine = engine;
 
-  let tab = gBrowser.selectedTab = gBrowser.addTab("about:mozilla", {animate: false});
-  yield promiseTabLoaded(gBrowser.selectedTab);
+  let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:mozilla");
 
   registerCleanupFunction(() => {
     Services.search.currentEngine = originalEngine;
     let engine = Services.search.getEngineByName("MozSearch");
     Services.search.removeEngine(engine);
 
     try {
       gBrowser.removeTab(tab);
@@ -24,14 +23,14 @@ add_task(function* () {
   let result = gURLBar.popup.richlistbox.firstChild;
 
   isnot(result, null, "Should have a result");
   is(result.getAttribute("url"),
      `moz-action:searchengine,{"engineName":"MozSearch","input":"open%20a%20search","searchQuery":"open%20a%20search"}`,
      "Result should be a moz-action: for the correct search engine");
   is(result.hasAttribute("image"), false, "Result shouldn't have an image attribute");
 
-  let tabPromise = promiseTabLoaded(gBrowser.selectedTab);
+  let tabPromise = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
   result.click();
   yield tabPromise;
 
   is(gBrowser.selectedBrowser.currentURI.spec, "http://example.com/?q=open+a+search", "Correct URL should be loaded");
 });
--- a/browser/base/content/test/urlbar/browser_action_searchengine_alias.js
+++ b/browser/base/content/test/urlbar/browser_action_searchengine_alias.js
@@ -1,18 +1,17 @@
 add_task(function* () {
   let iconURI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAABGklEQVQoz2NgGB6AnZ1dUlJSXl4eSDIyMhLW4Ovr%2B%2Fr168uXL69Zs4YoG%2BLi4i5dusTExMTGxsbNzd3f37937976%2BnpmZmagbHR09J49e5YvX66kpATVEBYW9ubNm2nTphkbG7e2tp44cQLIuHfvXm5urpaWFlDKysqqu7v73LlzECMYIiIiHj58mJCQoKKicvXq1bS0NKBgW1vbjh074uPjgeqAXE1NzSdPnvDz84M0AEUvXLgAsW379u1z5swBen3jxo2zZ892cHB4%2BvQp0KlAfwI1cHJyghQFBwfv2rULokFXV%2FfixYu7d%2B8GGqGgoMDKyrpu3br9%2B%2FcDuXl5eVA%2FAEWBfoWHAdAYoNuAYQ0XAeoUERFhGDYAAPoUaT2dfWJuAAAAAElFTkSuQmCC";
   Services.search.addEngineWithDetails("MozSearch", iconURI, "moz", "", "GET",
                                        "http://example.com/?q={searchTerms}");
   let engine = Services.search.getEngineByName("MozSearch");
   let originalEngine = Services.search.currentEngine;
   Services.search.currentEngine = engine;
 
-  let tab = gBrowser.selectedTab = gBrowser.addTab("about:mozilla", {animate: false});
-  yield promiseTabLoaded(gBrowser.selectedTab);
+  let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:mozilla");
 
   registerCleanupFunction(() => {
     Services.search.currentEngine = originalEngine;
     let engine = Services.search.getEngineByName("MozSearch");
     Services.search.removeEngine(engine);
 
     try {
       gBrowser.removeTab(tab);
@@ -23,13 +22,14 @@ add_task(function* () {
 
   yield promiseAutocompleteResultPopup("moz open a search");
 
   let result = gURLBar.popup.richlistbox.children[0];
   ok(result.hasAttribute("image"), "Result should have an image attribute");
   ok(result.getAttribute("image") === engine.iconURI.spec,
      "Image attribute should have the search engine's icon");
 
+  let tabPromise = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
   EventUtils.synthesizeKey("VK_RETURN", { });
-  yield promiseTabLoaded(gBrowser.selectedTab);
+  yield tabPromise;
 
   is(gBrowser.selectedBrowser.currentURI.spec, "http://example.com/?q=open+a+search");
 });
--- a/browser/base/content/test/urlbar/browser_autocomplete_a11y_label.js
+++ b/browser/base/content/test/urlbar/browser_autocomplete_a11y_label.js
@@ -1,18 +1,17 @@
 /* Any copyright is dedicated to the Public Domain.
  * http://creativecommons.org/publicdomain/zero/1.0/ */
 
 const SUGGEST_ALL_PREF = "browser.search.suggest.enabled";
 const SUGGEST_URLBAR_PREF = "browser.urlbar.suggest.searches";
 const TEST_ENGINE_BASENAME = "searchSuggestionEngine.xml";
 
 add_task(function* switchToTab() {
-  let tab = gBrowser.addTab("about:about");
-  yield promiseTabLoaded(tab);
+  let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:about");
 
   yield promiseAutocompleteResultPopup("% about");
 
   ok(gURLBar.popup.richlistbox.children.length > 1, "Should get at least 2 results");
   let result = gURLBar.popup.richlistbox.children[1];
   is(result.getAttribute("type"), "switchtab", "Expect right type attribute");
   is(result.label, "about:about about:about Tab", "Result a11y label should be: <title> <url> Tab");
 
--- a/browser/base/content/test/urlbar/browser_autocomplete_autoselect.js
+++ b/browser/base/content/test/urlbar/browser_autocomplete_autoselect.js
@@ -37,18 +37,17 @@ add_task(function*() {
   let visits = [];
   repeat(maxResults, i => {
     visits.push({
       uri: makeURI("http://example.com/autocomplete/?" + i),
     });
   });
   yield PlacesTestUtils.addVisits(visits);
 
-  let tab = gBrowser.selectedTab = gBrowser.addTab("about:mozilla", {animate: false});
-  yield promiseTabLoaded(tab);
+  let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:mozilla");
   yield promiseAutocompleteResultPopup("example.com/autocomplete");
 
   let popup = gURLBar.popup;
   let results = popup.richlistbox.children;
   is(results.length, maxResults,
      "Should get maxResults=" + maxResults + " results");
   is_selected(0);
 
--- a/browser/base/content/test/urlbar/browser_autocomplete_cursor.js
+++ b/browser/base/content/test/urlbar/browser_autocomplete_cursor.js
@@ -1,11 +1,10 @@
 add_task(function*() {
-  let tab = gBrowser.selectedTab = gBrowser.addTab("about:mozilla", {animate: false});
-  yield promiseTabLoaded(tab);
+  let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:mozilla");
   yield promiseAutocompleteResultPopup("www.mozilla.org");
 
   gURLBar.selectTextRange(4, 4);
 
   is(gURLBar.popup.state, "open", "Popup should be open");
   is(gURLBar.popup.richlistbox.selectedIndex, 0, "Should have selected something");
 
   EventUtils.synthesizeKey("VK_RIGHT", {});
--- a/browser/base/content/test/urlbar/browser_autocomplete_no_title.js
+++ b/browser/base/content/test/urlbar/browser_autocomplete_no_title.js
@@ -1,11 +1,10 @@
 add_task(function*() {
-  let tab = gBrowser.selectedTab = gBrowser.addTab("about:mozilla", {animate: false});
-  yield promiseTabLoaded(tab);
+  let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:mozilla");
 
   let uri = NetUtil.newURI("http://bug1060642.example.com/beards/are/pretty/great");
   yield PlacesTestUtils.addVisits([{uri: uri, title: ""}]);
 
   yield promiseAutocompleteResultPopup("bug1060642");
   ok(gURLBar.popup.richlistbox.children.length > 1, "Should get at least 2 results");
   let result = gURLBar.popup.richlistbox.children[1];
   is(result._titleText.textContent, "bug1060642.example.com", "Result title should be as expected");
--- a/browser/base/content/test/urlbar/browser_bug1003461-switchtab-override.js
+++ b/browser/base/content/test/urlbar/browser_bug1003461-switchtab-override.js
@@ -1,32 +1,29 @@
 /* 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/. */
 
 add_task(function* test_switchtab_override() {
   let testURL = "http://example.org/browser/browser/base/content/test/urlbar/dummy_page.html";
 
   info("Opening first tab");
-  let tab = gBrowser.addTab(testURL);
-  let deferred = Promise.defer();
-  whenTabLoaded(tab, deferred.resolve);
-  yield deferred.promise;
+  let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, testURL);
 
   info("Opening and selecting second tab");
   let secondTab = gBrowser.selectedTab = gBrowser.addTab();
   registerCleanupFunction(() => {
     try {
       gBrowser.removeTab(tab);
       gBrowser.removeTab(secondTab);
     } catch (ex) { /* tabs may have already been closed in case of failure */ }
   });
 
   info("Wait for autocomplete")
-  deferred = Promise.defer();
+  let deferred = Promise.defer();
   let onSearchComplete = gURLBar.onSearchComplete;
   registerCleanupFunction(() => {
     gURLBar.onSearchComplete = onSearchComplete;
   });
   gURLBar.onSearchComplete = function () {
     ok(gURLBar.popupOpen, "The autocomplete popup is correctly open");
     onSearchComplete.apply(gURLBar);
     deferred.resolve();
@@ -47,17 +44,17 @@ add_task(function* test_switchtab_overri
   let onTabSelect = event => {
     deferred.reject(new Error("Should have overridden switch to tab"));
   };
   gBrowser.tabContainer.addEventListener("TabSelect", onTabSelect, false);
   registerCleanupFunction(() => {
     gBrowser.tabContainer.removeEventListener("TabSelect", onTabSelect, false);
   });
   // Otherwise it would load the page.
-  whenTabLoaded(secondTab, deferred.resolve);
+  BrowserTestUtils.browserLoaded(secondTab.linkedBrowser).then(deferred.resolve);
 
   EventUtils.synthesizeKey("VK_SHIFT", { type: "keydown" });
   EventUtils.synthesizeKey("VK_RETURN", { });
   info(`gURLBar.value = ${gURLBar.value}`);
   EventUtils.synthesizeKey("VK_SHIFT", { type: "keyup" });
   yield deferred.promise;
 
   yield PlacesTestUtils.clearHistory();
--- a/browser/base/content/test/urlbar/browser_bug1024133-switchtab-override-keynav.js
+++ b/browser/base/content/test/urlbar/browser_bug1024133-switchtab-override-keynav.js
@@ -1,20 +1,17 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 add_task(function* test_switchtab_override_keynav() {
   let testURL = "http://example.org/browser/browser/base/content/test/urlbar/dummy_page.html";
 
   info("Opening first tab");
-  let tab = gBrowser.addTab(testURL);
-  let tabLoadDeferred = Promise.defer();
-  whenTabLoaded(tab, tabLoadDeferred.resolve);
-  yield tabLoadDeferred.promise;
+  let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, testURL);
 
   info("Opening and selecting second tab");
   let secondTab = gBrowser.selectedTab = gBrowser.addTab();
   registerCleanupFunction(() => {
     try {
       gBrowser.removeTab(tab);
       gBrowser.removeTab(secondTab);
     } catch (ex) { /* tabs may have already been closed in case of failure */ }
--- a/browser/base/content/test/urlbar/browser_bug1025195_switchToTabHavingURI_aOpenParams.js
+++ b/browser/base/content/test/urlbar/browser_bug1025195_switchToTabHavingURI_aOpenParams.js
@@ -1,110 +1,100 @@
 /* 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/. */
 
-add_task(function *test_ignoreFragment() {
-  let tabRefAboutHome = gBrowser.addTab("about:home#1");
-  yield promiseTabLoaded(tabRefAboutHome);
-  let tabRefAboutMozilla = gBrowser.addTab("about:mozilla");
-  yield promiseTabLoaded(tabRefAboutMozilla);
-
-  gBrowser.selectedTab = tabRefAboutMozilla;
+add_task(function* test_ignoreFragment() {
+  let tabRefAboutHome =
+    yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:home#1");
+  yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:mozilla");
   let numTabsAtStart = gBrowser.tabs.length;
 
   switchTab("about:home#1", true);
   switchTab("about:mozilla", true);
 
-  let hashChangePromise = new Promise(resolve => {
-    tabRefAboutHome.linkedBrowser.contentWindow.addEventListener("hashchange", resolve, false);
+  let hashChangePromise = ContentTask.spawn(tabRefAboutHome.linkedBrowser, null, function* () {
+    yield ContentTaskUtils.waitForEvent(this, "hashchange", false);
   });
   switchTab("about:home#2", true, { ignoreFragment: "whenComparingAndReplace" });
   is(tabRefAboutHome, gBrowser.selectedTab, "The same about:home tab should be switched to");
   yield hashChangePromise;
   is(gBrowser.currentURI.ref, "2", "The ref should be updated to the new ref");
   switchTab("about:mozilla", true);
   switchTab("about:home#3", true, { ignoreFragment: "whenComparing" });
   is(tabRefAboutHome, gBrowser.selectedTab, "The same about:home tab should be switched to");
   is(gBrowser.currentURI.ref, "2", "The ref should be unchanged since the fragment is only ignored when comparing");
   switchTab("about:mozilla", true);
   switchTab("about:home#1", false);
   isnot(tabRefAboutHome, gBrowser.selectedTab, "Selected tab should not be initial about:blank tab");
   is(gBrowser.tabs.length, numTabsAtStart + 1, "Should have one new tab opened");
   switchTab("about:mozilla", true);
   switchTab("about:home", true, {ignoreFragment: "whenComparingAndReplace"});
-  yield promiseWaitForCondition(function() {
+  yield BrowserTestUtils.waitForCondition(function() {
     return tabRefAboutHome.linkedBrowser.currentURI.spec == "about:home";
   });
   is(tabRefAboutHome.linkedBrowser.currentURI.spec, "about:home", "about:home shouldn't have hash");
   switchTab("about:about", false, { ignoreFragment: "whenComparingAndReplace" });
   cleanupTestTabs();
 });
 
 add_task(function* test_ignoreQueryString() {
-  let tabRefAboutHome = gBrowser.addTab("about:home?hello=firefox");
-  yield promiseTabLoaded(tabRefAboutHome);
-  let tabRefAboutMozilla = gBrowser.addTab("about:mozilla");
-  yield promiseTabLoaded(tabRefAboutMozilla);
-  gBrowser.selectedTab = tabRefAboutMozilla;
+  let tabRefAboutHome =
+    yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:home?hello=firefox");
+  yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:mozilla");
 
   switchTab("about:home?hello=firefox", true);
   switchTab("about:home?hello=firefoxos", false);
   // Remove the last opened tab to test ignoreQueryString option.
   gBrowser.removeCurrentTab();
   switchTab("about:home?hello=firefoxos", true, { ignoreQueryString: true });
   is(tabRefAboutHome, gBrowser.selectedTab, "Selected tab should be the initial about:home tab");
   is(gBrowser.currentURI.spec, "about:home?hello=firefox", "The spec should NOT be updated to the new query string");
   cleanupTestTabs();
 });
 
 add_task(function* test_replaceQueryString() {
-  let tabRefAboutHome = gBrowser.addTab("about:home?hello=firefox");
-  yield promiseTabLoaded(tabRefAboutHome);
-  let tabRefAboutMozilla = gBrowser.addTab("about:mozilla");
-  yield promiseTabLoaded(tabRefAboutMozilla);
-  gBrowser.selectedTab = tabRefAboutMozilla;
+  let tabRefAboutHome =
+    yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:home?hello=firefox");
+  yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:mozilla");
 
   switchTab("about:home", false);
   switchTab("about:home?hello=firefox", true);
   switchTab("about:home?hello=firefoxos", false);
   // Remove the last opened tab to test replaceQueryString option.
   gBrowser.removeCurrentTab();
   switchTab("about:home?hello=firefoxos", true, { replaceQueryString: true });
   is(tabRefAboutHome, gBrowser.selectedTab, "Selected tab should be the initial about:home tab");
   // Wait for the tab to load the new URI spec.
-  yield promiseTabLoaded(tabRefAboutHome);
+  yield BrowserTestUtils.browserLoaded(tabRefAboutHome.linkedBrowser);
   is(gBrowser.currentURI.spec, "about:home?hello=firefoxos", "The spec should be updated to the new spec");
   cleanupTestTabs();
 });
 
 add_task(function* test_replaceQueryStringAndFragment() {
-  let tabRefAboutHome = gBrowser.addTab("about:home?hello=firefox#aaa");
-  yield promiseTabLoaded(tabRefAboutHome);
-  let tabRefAboutMozilla = gBrowser.addTab("about:mozilla?hello=firefoxos#aaa");
-  yield promiseTabLoaded(tabRefAboutMozilla);
-  gBrowser.selectedTab = tabRefAboutMozilla;
+  let tabRefAboutHome =
+    yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:home?hello=firefox#aaa");
+  let tabRefAboutMozilla =
+    yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:mozilla?hello=firefoxos#aaa");
 
   switchTab("about:home", false);
   gBrowser.removeCurrentTab();
   switchTab("about:home?hello=firefox#aaa", true);
   is(tabRefAboutHome, gBrowser.selectedTab, "Selected tab should be the initial about:home tab");
   switchTab("about:mozilla?hello=firefox#bbb", true, { replaceQueryString: true, ignoreFragment: "whenComparingAndReplace" });
   is(tabRefAboutMozilla, gBrowser.selectedTab, "Selected tab should be the initial about:mozilla tab");
   switchTab("about:home?hello=firefoxos#bbb", true, { ignoreQueryString: true, ignoreFragment: "whenComparingAndReplace" });
   is(tabRefAboutHome, gBrowser.selectedTab, "Selected tab should be the initial about:home tab");
   cleanupTestTabs();
 });
 
 add_task(function* test_ignoreQueryStringIgnoresFragment() {
-  let tabRefAboutHome = gBrowser.addTab("about:home?hello=firefox#aaa");
-  yield promiseTabLoaded(tabRefAboutHome);
-  let tabRefAboutMozilla = gBrowser.addTab("about:mozilla?hello=firefoxos#aaa");
-  yield promiseTabLoaded(tabRefAboutMozilla);
-  gBrowser.selectedTab = tabRefAboutMozilla;
+  let tabRefAboutHome =
+    yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:home?hello=firefox#aaa");
+  yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:mozilla?hello=firefoxos#aaa");
 
   switchTab("about:home?hello=firefox#bbb", false, { ignoreQueryString: true });
   gBrowser.removeCurrentTab();
   switchTab("about:home?hello=firefoxos#aaa", true, { ignoreQueryString: true });
   is(tabRefAboutHome, gBrowser.selectedTab, "Selected tab should be the initial about:home tab");
   cleanupTestTabs();
 });
 
--- a/browser/base/content/test/urlbar/browser_bug1070778.js
+++ b/browser/base/content/test/urlbar/browser_bug1070778.js
@@ -22,18 +22,17 @@ add_task(function*() {
                                              title: "keyword abc" })));
 
   registerCleanupFunction(function* () {
     for (let bm of bookmarks) {
       yield PlacesUtils.bookmarks.remove(bm);
     }
   });
 
-  let tab = gBrowser.selectedTab = gBrowser.addTab("about:mozilla", {animate: false});
-  yield promiseTabLoaded(tab);
+  let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:mozilla");
   yield promiseAutocompleteResultPopup("keyword a");
 
   // First item should already be selected
   is_selected(0);
   // Select next one (important!)
   EventUtils.synthesizeKey("VK_DOWN", {});
   is_selected(1);
   // Re-select keyword item
@@ -43,14 +42,14 @@ add_task(function*() {
   EventUtils.synthesizeKey("b", {});
   yield promiseSearchComplete();
 
   is(gURLBar.textValue, "keyword ab", "urlbar should have expected input");
 
   let result = gURLBar.popup.richlistbox.firstChild;
   isnot(result, null, "Should have first item");
   let uri = NetUtil.newURI(result.getAttribute("url"));
-  is(uri.spec, makeActionURI("keyword", {url: "http://example.com/?q=ab", input: "keyword ab"}).spec, "Expect correct url");
+  is(uri.spec, PlacesUtils.mozActionURI("keyword", {url: "http://example.com/?q=ab", input: "keyword ab"}), "Expect correct url");
 
   EventUtils.synthesizeKey("VK_ESCAPE", {});
   yield promisePopupHidden(gURLBar.popup);
   gBrowser.removeTab(tab);
 });
--- a/browser/base/content/test/urlbar/browser_bug1104165-switchtab-decodeuri.js
+++ b/browser/base/content/test/urlbar/browser_bug1104165-switchtab-decodeuri.js
@@ -1,12 +1,12 @@
 add_task(function* test_switchtab_decodeuri() {
   info("Opening first tab");
-  let tab = gBrowser.addTab("http://example.org/browser/browser/base/content/test/urlbar/dummy_page.html#test%7C1");
-  yield promiseTabLoadEvent(tab);
+  const TEST_URL = "http://example.org/browser/browser/base/content/test/urlbar/dummy_page.html#test%7C1";
+  let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, TEST_URL);
 
   info("Opening and selecting second tab");
   gBrowser.selectedTab = gBrowser.addTab();
 
   info("Wait for autocomplete")
   yield promiseAutocompleteResultPopup("dummy_page");
 
   info("Select autocomplete popup entry");
--- a/browser/base/content/test/urlbar/browser_bug1225194-remotetab.js
+++ b/browser/base/content/test/urlbar/browser_bug1225194-remotetab.js
@@ -2,17 +2,15 @@ add_task(function* test_remotetab_opens(
   const url = "http://example.org/browser/browser/base/content/test/urlbar/dummy_page.html";
   yield BrowserTestUtils.withNewTab({url: "about:robots", gBrowser}, function* () {
     // Set the urlbar to include the moz-action
     gURLBar.value = "moz-action:remotetab," + JSON.stringify({ url });
     // Focus the urlbar so we can press enter
     gURLBar.focus();
 
     // The URL is going to open in the current tab as it is currently about:blank
-    let promiseTabLoaded = promiseTabLoadEvent(gBrowser.selectedTab);
-
+    let promiseTabLoaded = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
     EventUtils.synthesizeKey("VK_RETURN", {});
-
     yield promiseTabLoaded;
 
     Assert.equal(gBrowser.selectedTab.linkedBrowser.currentURI.spec, url, "correct URL loaded");
   });
 });
--- a/browser/base/content/test/urlbar/browser_locationBarCommand.js
+++ b/browser/base/content/test/urlbar/browser_locationBarCommand.js
@@ -49,17 +49,17 @@ add_task(function* shift_left_click_test
 
   info("URL should be loaded in a new window");
   is(gURLBar.value, "", "Urlbar reverted to original value");
   yield promiseCheckChildNoFocusedElement(gBrowser.selectedBrowser);
   is(document.activeElement, gBrowser.selectedBrowser, "Content window should be focused");
   is(win.gURLBar.textValue, TEST_VALUE, "New URL is loaded in new window");
 
   // Cleanup.
-  yield promiseWindowClosed(win);
+  yield BrowserTestUtils.closeWindow(win);
 });
 
 add_task(function* right_click_test() {
   info("Running test: Right click on go button");
 
   // Add a new tab.
   yield* promiseOpenNewTab();
 
--- a/browser/base/content/test/urlbar/browser_locationBarExternalLoad.js
+++ b/browser/base/content/test/urlbar/browser_locationBarExternalLoad.js
@@ -30,25 +30,25 @@ function promiseNewTabSwitched() {
   });
 }
 
 function* testURL(url, loadFunc, endFunc) {
   let tabSwitchedPromise = promiseNewTabSwitched();
   let tab = gBrowser.selectedTab = gBrowser.addTab();
   let browser = gBrowser.selectedBrowser;
 
-  let pageshowPromise = promiseWaitForEvent(browser, "pageshow");
+  let pageshowPromise = BrowserTestUtils.waitForContentEvent(browser, "pageshow");
 
   yield tabSwitchedPromise;
   yield pageshowPromise;
 
   let pagePrincipal = gBrowser.contentPrincipal;
   loadFunc(url);
 
-  yield promiseWaitForEvent(browser, "pageshow");
+  yield BrowserTestUtils.waitForContentEvent(browser, "pageshow");
 
   yield ContentTask.spawn(browser, { isRemote: gMultiProcessBrowser },
     function* (arg) {
       const fm = Components.classes["@mozilla.org/focus-manager;1"].
                             getService(Components.interfaces.nsIFocusManager);
       Assert.equal(fm.focusedElement, null, "focusedElement not null");
 
       if (arg.isRemote) {
--- a/browser/base/content/test/urlbar/browser_search_favicon.js
+++ b/browser/base/content/test/urlbar/browser_search_favicon.js
@@ -20,18 +20,17 @@ add_task(function*() {
   gEngine = Services.search.getEngineByName("SearchEngine");
   gEngine.addParam("q", "{searchTerms}", null);
   gOriginalEngine = Services.search.currentEngine;
   Services.search.currentEngine = gEngine;
 
   let uri = NetUtil.newURI("http://s.example.com/search?q=foo&client=1");
   yield PlacesTestUtils.addVisits({ uri: uri, title: "Foo - SearchEngine Search" });
 
-  gBrowser.selectedTab = gBrowser.addTab("about:mozilla", {animate: false});
-  yield promiseTabLoaded(gBrowser.selectedTab);
+  yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:mozilla");
 
   // The first autocomplete result has the action searchengine, while
   // the second result is the "search favicon" element.
   yield promiseAutocompleteResultPopup("foo");
   let result = gURLBar.popup.richlistbox.children[1];
 
   isnot(result, null, "Expect a search result");
   is(result.getAttribute("type"), "searchengine", "Expect correct `type` attribute");
--- a/browser/base/content/test/urlbar/browser_urlbarOneOffs.js
+++ b/browser/base/content/test/urlbar/browser_urlbarOneOffs.js
@@ -169,43 +169,51 @@ add_task(function* searchWith() {
 
   yield hidePopup();
 });
 
 // Clicks a one-off.
 add_task(function* oneOffClick() {
   gBrowser.selectedTab = gBrowser.addTab();
 
-  let typedValue = "foo";
+  // We are explicitly using something that looks like a url, to make the test
+  // stricter. Even if it looks like a url, we should search.
+  let typedValue = "foo.bar";
   yield promiseAutocompleteResultPopup(typedValue);
 
   assertState(0, -1, typedValue);
 
   let oneOffs = gURLBar.popup.oneOffSearchButtons.getSelectableButtons(true);
-  let resultsPromise = promiseSearchResultsLoaded();
+  let resultsPromise =
+    BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser, false,
+                                   "http://mochi.test:8888/");
   EventUtils.synthesizeMouseAtCenter(oneOffs[0], {});
   yield resultsPromise;
 
   gBrowser.removeTab(gBrowser.selectedTab);
 });
 
 // Presses the Return key when a one-off is selected.
 add_task(function* oneOffReturn() {
   gBrowser.selectedTab = gBrowser.addTab();
 
-  let typedValue = "foo";
+  // We are explicitly using something that looks like a url, to make the test
+  // stricter. Even if it looks like a url, we should search.
+  let typedValue = "foo.bar";
   yield promiseAutocompleteResultPopup(typedValue, window, true);
 
   assertState(0, -1, typedValue);
 
   // Alt+Down to select the first one-off.
   EventUtils.synthesizeKey("VK_DOWN", { altKey: true })
   assertState(0, 0, typedValue);
 
-  let resultsPromise = promiseSearchResultsLoaded();
+  let resultsPromise =
+    BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser, false,
+                                   "http://mochi.test:8888/");
   EventUtils.synthesizeKey("VK_RETURN", {})
   yield resultsPromise;
 
   gBrowser.removeTab(gBrowser.selectedTab);
 });
 
 
 function assertState(result, oneOff, textValue = undefined) {
@@ -217,17 +225,8 @@ function assertState(result, oneOff, tex
     Assert.equal(gURLBar.textValue, textValue, "Expected textValue");
   }
 }
 
 function* hidePopup() {
   EventUtils.synthesizeKey("VK_ESCAPE", {});
   yield promisePopupHidden(gURLBar.popup);
 }
-
-function promiseSearchResultsLoaded() {
-  let tab = gBrowser.selectedTab;
-  return promiseTabLoadEvent(tab).then(() => {
-    Assert.equal(tab.linkedBrowser.currentURI.spec,
-                 "http://mochi.test:8888/",
-                 'Expected "search results" page loaded');
-  });
-}
--- a/browser/base/content/test/urlbar/browser_urlbarSearchSingleWordNotification.js
+++ b/browser/base/content/test/urlbar/browser_urlbarSearchSingleWordNotification.js
@@ -1,11 +1,8 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
 "use strict";
 
 var notificationObserver;
 registerCleanupFunction(function() {
   Services.prefs.clearUserPref("browser.fixup.domainwhitelist.localhost");
   if (notificationObserver) {
     notificationObserver.disconnect();
   }
@@ -126,26 +123,27 @@ add_task(function* test_navigate_large_h
   gBrowser.removeTab(tab);
 });
 
 function get_test_function_for_localhost_with_hostname(hostName, isPrivate) {
   return function* test_navigate_single_host() {
     const pref = "browser.fixup.domainwhitelist.localhost";
     let win;
     if (isPrivate) {
-      win = yield promiseOpenAndLoadWindow({private: true}, true);
+      let promiseWin = BrowserTestUtils.waitForNewWindow();
+      win = OpenBrowserWindow({private: true});
+      yield promiseWin;
       let deferredOpenFocus = Promise.defer();
       waitForFocus(deferredOpenFocus.resolve, win);
       yield deferredOpenFocus.promise;
     } else {
       win = window;
     }
     let browser = win.gBrowser;
-    let tab = browser.selectedTab = browser.addTab("about:blank");
-    yield BrowserTestUtils.browserLoaded(tab.linkedBrowser);
+    let tab = yield BrowserTestUtils.openNewForegroundTab(browser);
 
     Services.prefs.setBoolPref(pref, false);
     yield* runURLBarSearchTest({
       valueToOpen: hostName,
       expectSearch: true,
       expectNotification: true,
       aWindow: win,
     });
@@ -170,17 +168,17 @@ function get_test_function_for_localhost
       valueToOpen: hostName,
       expectSearch: isPrivate,
       expectNotification: isPrivate,
       aWindow: win,
     });
     browser.removeTab(tab);
     if (isPrivate) {
       info("Waiting for private window to close");
-      yield promiseWindowClosed(win);
+      yield BrowserTestUtils.closeWindow(win);
       let deferredFocus = Promise.defer();
       info("Waiting for focus");
       waitForFocus(deferredFocus.resolve, window);
       yield deferredFocus.promise;
     }
   }
 }
 
--- a/browser/base/content/test/urlbar/browser_urlbarSearchSuggestions.js
+++ b/browser/base/content/test/urlbar/browser_urlbarSearchSuggestions.js
@@ -17,51 +17,50 @@ add_task(function* prepare() {
 
     // Make sure the popup is closed for the next test.
     gURLBar.blur();
     Assert.ok(!gURLBar.popup.popupOpen, "popup should be closed");
   });
 });
 
 add_task(function* clickSuggestion() {
-  gBrowser.selectedTab = gBrowser.addTab();
+  let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser);
   gURLBar.focus();
   yield promiseAutocompleteResultPopup("foo");
   let [idx, suggestion, engineName] = yield promiseFirstSuggestion();
   Assert.equal(engineName,
                "browser_searchSuggestionEngine%20searchSuggestionEngine.xml",
                "Expected suggestion engine");
   let item = gURLBar.popup.richlistbox.getItemAtIndex(idx);
-  let loadPromise = promiseTabLoaded(gBrowser.selectedTab);
+
+  let uri = Services.search.currentEngine.getSubmission(suggestion).uri;
+  let loadPromise = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser,
+                                                   false, uri.spec);
   item.click();
   yield loadPromise;
-  let uri = Services.search.currentEngine.getSubmission(suggestion).uri;
-  Assert.ok(uri.equals(gBrowser.currentURI),
-            "The search results page should have loaded");
-  gBrowser.removeTab(gBrowser.selectedTab);
+  yield BrowserTestUtils.removeTab(tab);
 });
 
 function getFirstSuggestion() {
   let controller = gURLBar.popup.input.controller;
   let matchCount = controller.matchCount;
   for (let i = 0; i < matchCount; i++) {
     let url = controller.getValueAt(i);
     let mozActionMatch = url.match(/^moz-action:([^,]+),(.*)$/);
     if (mozActionMatch) {
       let [, type, paramStr] = mozActionMatch;
       let params = JSON.parse(paramStr);
       if (type == "searchengine" && "searchSuggestion" in params) {
         return [i, params.searchSuggestion, params.engineName];
       }
     }
   }
-  return [-1, null];
+  return [-1, null, null];
 }
 
-function promiseFirstSuggestion() {
-  return new Promise(resolve => {
-    let tuple;
-    waitForCondition(() => {
-      tuple = getFirstSuggestion();
-      return tuple[0] >= 0;
-    }, () => resolve(tuple));
+function* promiseFirstSuggestion() {
+  let tuple = [-1, null, null];
+  yield BrowserTestUtils.waitForCondition(() => {
+    tuple = getFirstSuggestion();
+    return tuple[0] >= 0;
   });
+  return tuple;
 }
--- a/browser/base/content/test/urlbar/browser_urlbarSearchSuggestionsNotification.js
+++ b/browser/base/content/test/urlbar/browser_urlbarSearchSuggestionsNotification.js
@@ -109,17 +109,18 @@ add_task(function* enable() {
   gURLBar.blur();
   gURLBar.focus();
   yield promiseAutocompleteResultPopup("foo");
   assertVisible(true);
   Assert.ok(!suggestionsPresent());
   let enableButton = document.getAnonymousElementByAttribute(
     gURLBar.popup, "anonid", "search-suggestions-notification-enable"
   );
-  let searchPromise = promiseSuggestionsPresent();
+  let searchPromise = BrowserTestUtils.waitForCondition(suggestionsPresent,
+                                                        "waiting for suggestions");
   enableButton.click();
   yield searchPromise;
   // Clicking Yes should trigger a new search so that suggestions appear
   // immediately.
   Assert.ok(suggestionsPresent());
   gURLBar.blur();
   gURLBar.focus();
   // Suggestions should still be present in a new search of course.
@@ -230,22 +231,16 @@ function suggestionsPresent() {
       if (type == "searchengine" && "searchSuggestion" in params) {
         return true;
       }
     }
   }
   return false;
 }
 
-function promiseSuggestionsPresent() {
-  return new Promise(resolve => {
-    waitForCondition(suggestionsPresent, resolve);
-  });
-}
-
 function assertVisible(visible, win=window) {
   let style =
     win.getComputedStyle(win.gURLBar.popup.searchSuggestionsNotification);
   Assert.equal(style.visibility, visible ? "visible" : "collapse");
 }
 
 function promiseTransition(win=window) {
   return new Promise(resolve => {
--- a/browser/base/content/test/urlbar/head.js
+++ b/browser/base/content/test/urlbar/head.js
@@ -3,123 +3,19 @@ Components.utils.import("resource://gre/
 XPCOMUtils.defineLazyModuleGetter(this, "Promise",
   "resource://gre/modules/Promise.jsm");
 XPCOMUtils.defineLazyModuleGetter(this, "Task",
   "resource://gre/modules/Task.jsm");
 XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils",
   "resource://gre/modules/PlacesUtils.jsm");
 XPCOMUtils.defineLazyModuleGetter(this, "PlacesTestUtils",
   "resource://testing-common/PlacesTestUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "TabCrashHandler",
-  "resource:///modules/ContentCrashHandlers.jsm");
 XPCOMUtils.defineLazyModuleGetter(this, "Preferences",
   "resource://gre/modules/Preferences.jsm");
 
-function waitForCondition(condition, nextTest, errorMsg, retryTimes) {
-  retryTimes = typeof retryTimes !== 'undefined' ?  retryTimes : 30;
-  var tries = 0;
-  var interval = setInterval(function() {
-    if (tries >= retryTimes) {
-      ok(false, errorMsg);
-      moveOn();
-    }
-    var conditionPassed;
-    try {
-      conditionPassed = condition();
-    } catch (e) {
-      ok(false, e + "\n" + e.stack);
-      conditionPassed = false;
-    }
-    if (conditionPassed) {
-      moveOn();
-    }
-    tries++;
-  }, 100);
-  var moveOn = function() { clearInterval(interval); nextTest(); };
-}
-
-function promiseWaitForCondition(aConditionFn) {
-  let deferred = Promise.defer();
-  waitForCondition(aConditionFn, deferred.resolve, "Condition didn't pass.");
-  return deferred.promise;
-}
-
-function promiseWaitForEvent(object, eventName, capturing = false, chrome = false) {
-  return new Promise((resolve) => {
-    function listener(event) {
-      info("Saw " + eventName);
-      object.removeEventListener(eventName, listener, capturing, chrome);
-      resolve(event);
-    }
-
-    info("Waiting for " + eventName);
-    object.addEventListener(eventName, listener, capturing, chrome);
-  });
-}
-
-function promiseWindowWillBeClosed(win) {
-  return new Promise((resolve, reject) => {
-    Services.obs.addObserver(function observe(subject, topic) {
-      if (subject == win) {
-        Services.obs.removeObserver(observe, topic);
-        resolve();
-      }
-    }, "domwindowclosed", false);
-  });
-}
-
-function promiseWindowClosed(win) {
-  let promise = promiseWindowWillBeClosed(win);
-  win.close();
-  return promise;
-}
-
-function promiseOpenAndLoadWindow(aOptions, aWaitForDelayedStartup=false) {
-  let deferred = Promise.defer();
-  let win = OpenBrowserWindow(aOptions);
-  if (aWaitForDelayedStartup) {
-    Services.obs.addObserver(function onDS(aSubject, aTopic, aData) {
-      if (aSubject != win) {
-        return;
-      }
-      Services.obs.removeObserver(onDS, "browser-delayed-startup-finished");
-      deferred.resolve(win);
-    }, "browser-delayed-startup-finished", false);
-
-  } else {
-    win.addEventListener("load", function onLoad() {
-      win.removeEventListener("load", onLoad);
-      deferred.resolve(win);
-    });
-  }
-  return deferred.promise;
-}
-
-function whenNewTabLoaded(aWindow, aCallback) {
-  aWindow.BrowserOpenTab();
-
-  let browser = aWindow.gBrowser.selectedBrowser;
-  if (browser.contentDocument.readyState === "complete") {
-    aCallback();
-    return;
-  }
-
-  whenTabLoaded(aWindow.gBrowser.selectedTab, aCallback);
-}
-
-function whenTabLoaded(aTab, aCallback) {
-  promiseTabLoadEvent(aTab).then(aCallback);
-}
-
-function promiseTabLoaded(aTab) {
-  let deferred = Promise.defer();
-  whenTabLoaded(aTab, deferred.resolve);
-  return deferred.promise;
-}
-
 /**
  * Waits for the next top-level document load in the current browser.  The URI
  * of the document is compared against aExpectedURL.  The load is then stopped
  * before it actually starts.
  *
  * @param aExpectedURL
  *        The URL of the document that is expected to load.
  * @param aStopFromProgressListener
@@ -188,61 +84,16 @@ function waitForDocLoadAndStopIt(aExpect
 
     let mm = aBrowser.messageManager;
     mm.loadFrameScript("data:,(" + content_script.toString() + ")(" + aStopFromProgressListener + ");", true);
     mm.addMessageListener("Test:WaitForDocLoadAndStopIt", complete);
     info("waitForDocLoadAndStopIt: Waiting for URL: " + aExpectedURL);
   });
 }
 
-/**
- * Waits for a load (or custom) event to finish in a given tab. If provided
- * load an uri into the tab.
- *
- * @param tab
- *        The tab to load into.
- * @param [optional] url
- *        The url to load, or the current url.
- * @return {Promise} resolved when the event is handled.
- * @resolves to the received event
- * @rejects if a valid load event is not received within a meaningful interval
- */
-function promiseTabLoadEvent(tab, url)
-{
-  info("Wait tab event: load");
-
-  function handle(loadedUrl) {
-    if (loadedUrl === "about:blank" || (url && loadedUrl !== url)) {
-      info(`Skipping spurious load event for ${loadedUrl}`);
-      return false;
-    }
-
-    info("Tab event received: load");
-    return true;
-  }
-
-  // Create two promises: one resolved from the content process when the page
-  // loads and one that is rejected if we take too long to load the url.
-  let loaded = BrowserTestUtils.browserLoaded(tab.linkedBrowser, false, handle);
-
-  if (url)
-    BrowserTestUtils.loadURI(tab.linkedBrowser, url);
-
-  return loaded;
-}
-
-function makeActionURI(action, params) {
-  let encodedParams = {};
-  for (let key in params) {
-    encodedParams[key] = encodeURIComponent(params[key]);
-  }
-  let url = "moz-action:" + action + "," + JSON.stringify(encodedParams);
-  return NetUtil.newURI(url);
-}
-
 function is_hidden(element) {
   var style = element.ownerGlobal.getComputedStyle(element);
   if (style.display == "none")
     return true;
   if (style.visibility != "visible")
     return true;
   if (style.display == "-moz-popup")
     return ["hiding", "closed"].indexOf(element.state) != -1;
@@ -307,17 +158,17 @@ function promisePopupHidden(popup) {
 function promiseSearchComplete(win = window) {
   return promisePopupShown(win.gURLBar.popup).then(() => {
     function searchIsComplete() {
       return win.gURLBar.controller.searchStatus >=
         Ci.nsIAutoCompleteController.STATUS_COMPLETE_NO_MATCH;
     }
 
     // Wait until there are at least two matches.
-    return new Promise(resolve => waitForCondition(searchIsComplete, resolve));
+    return BrowserTestUtils.waitForCondition(searchIsComplete, "waiting urlbar search to complete");
   });
 }
 
 function promiseAutocompleteResultPopup(inputText,
                                         win = window,
                                         fireInputEvent = false) {
   waitForFocus(() => {
     win.gURLBar.focus();
--- a/browser/base/content/urlbarBindings.xml
+++ b/browser/base/content/urlbarBindings.xml
@@ -405,19 +405,27 @@ file, You can obtain one at http://mozil
           let url = this.value;
           if (!url) {
             return;
           }
 
           let mayInheritPrincipal = false;
           let postData = null;
           let browser = gBrowser.selectedBrowser;
+          let action = this._parseActionUrl(url);
 
-          let action = this._parseActionUrl(url);
-          if (action) {
+          if (selectedOneOff && selectedOneOff.engine) {
+            // If there's a selected one-off button then load a search using
+            // the one-off's engine.
+            [url, postData] =
+              this._parseAndRecordSearchEngineLoad(selectedOneOff.engine,
+                                                   this.oneOffSearchQuery,
+                                                   event, where,
+                                                   openUILinkParams);
+          } else if (action) {
             switch (action.type) {
               case "visiturl":
                 // Unifiedcomplete uses fixupURI to tell if something is a visit
                 // or a search, and passes out the fixedURI as the url param.
                 // By using that uri we would end up passing a different string
                 // to the docshell that may run a different not-found heuristic.
                 // For example, "mozilla/run" would be fixed by unifiedcomplete
                 // to "http://mozilla/run". The docshell, once it can't resolve
@@ -466,35 +474,16 @@ file, You can obtain one at http://mozil
                   action.params.searchSuggestion || action.params.searchQuery,
                   event,
                   where,
                   openUILinkParams,
                   actionDetails
                 );
                 break;
             }
-          } else if (selectedOneOff && selectedOneOff.engine) {
-            // If there's a selected one-off button and the input value is a
-            // search query (or "keyword" in URI-fixup terminology), then load a
-            // search using the one-off's engine.
-            let value = this.oneOffSearchQuery;
-            let fixup;
-            try {
-              fixup = Services.uriFixup.getFixupURIInfo(
-                value,
-                Services.uriFixup.FIXUP_FLAG_ALLOW_KEYWORD_LOOKUP
-              );
-            } catch (ex) {}
-            if (!fixup || !fixup.keywordProviderName) {
-              return;
-            }
-
-            [url, postData] =
-              this._parseAndRecordSearchEngineLoad(selectedOneOff.engine, value,
-                                                   event, where, openUILinkParams);
           } else {
             // This is a fallback for add-ons and old testing code that directly
             // set value and try to confirm it. UnifiedComplete should always
             // resolve to a valid url.
             try {
               new URL(url);
             } catch (ex) {
               let lastLocationChange = browser.lastLocationChange;
--- a/browser/components/contextualidentity/test/browser/browser_eme.js
+++ b/browser/components/contextualidentity/test/browser/browser_eme.js
@@ -112,17 +112,17 @@ add_task(function* test() {
                                                                        sessionTypes: ['persistent-license'],
                                                                        persistentState: 'required',
                                                                      }]);
     let mediaKeys = yield access.createMediaKeys();
     let session = mediaKeys.createSession(aKeyInfo.sessionType);
     let res = {};
 
     // Insert the media key.
-    let result = yield new Promise(resolve => {
+    yield new Promise(resolve => {
       session.addEventListener("message", function(event) {
         session.update(aKeyInfo.keyObj).then(
           () => { resolve(); }
         ).catch(
           () => {
             ok(false, "Update the media key fail.");
             resolve();
           }
--- a/browser/components/contextualidentity/test/browser/browser_favicon.js
+++ b/browser/components/contextualidentity/test/browser/browser_favicon.js
@@ -108,17 +108,16 @@ add_task(function* test() {
   let testURL = "http://localhost:" + serverPort + "/";
   let testFaviconURL = "http://localhost:" + serverPort + "/favicon.png";
 
   for (let userContextId of Object.keys(USER_CONTEXTS)) {
     gUserContextId = userContextId;
 
     // Load the page in 3 different contexts and set a cookie
     // which should only be visible in that context.
-    let value = USER_CONTEXTS[userContextId];
 
     // Open our tab in the given user context.
     let tabInfo = yield* openTabInUserContext(testURL, userContextId);
 
     // Write a cookie according to the userContext.
     yield ContentTask.spawn(tabInfo.browser, { userContext: USER_CONTEXTS[userContextId] }, function (arg) {
       content.document.cookie = "userContext=" + arg.userContext;
     });
--- a/browser/components/contextualidentity/test/browser/browser_forgetAPI_EME_forgetThisSite.js
+++ b/browser/components/contextualidentity/test/browser/browser_forgetAPI_EME_forgetThisSite.js
@@ -102,17 +102,17 @@ function* setupEMEKey(browser) {
                                                                        sessionTypes: ['persistent-license'],
                                                                        persistentState: 'required',
                                                                      }]);
     let mediaKeys = yield access.createMediaKeys();
     let session = mediaKeys.createSession(aKeyInfo.sessionType);
     let res = {};
 
     // Insert the EME key.
-    let result = yield new Promise(resolve => {
+    yield new Promise(resolve => {
       session.addEventListener("message", function(event) {
         session.update(aKeyInfo.keyObj).then(
           () => { resolve(); }
         ).catch(
           () => {
             ok(false, "Update the EME key fail.");
             resolve();
           }
--- a/browser/components/contextualidentity/test/browser/browser_forgetAPI_quota_clearStoragesForPrincipal.js
+++ b/browser/components/contextualidentity/test/browser/browser_forgetAPI_quota_clearStoragesForPrincipal.js
@@ -82,17 +82,17 @@ function* checkIndexedDB(browser) {
 
     let db = yield new Promise(done => {
       request.onsuccess = event => {
         done(event.target.result);
       };
     });
 
     try {
-      let transaction = db.transaction(["obj"], "readonly");
+      db.transaction(["obj"], "readonly");
       ok(false, "The indexedDB should not exist");
     } catch (e) {
       is(e.name, "NotFoundError", "The indexedDB does not exist as expected");
     }
   });
 }
 
 //
@@ -140,9 +140,8 @@ add_task(function* test_quota_clearStora
 
     // Check whether indexed DB has been cleared.
     yield checkIndexedDB(tabs[userContextId].browser);
 
     // Close this tab.
     yield BrowserTestUtils.removeTab(tabs[userContextId].tab);
   }
 });
-
--- a/browser/components/contextualidentity/test/browser/browser_forgetaboutsite.js
+++ b/browser/components/contextualidentity/test/browser/browser_forgetaboutsite.js
@@ -175,30 +175,30 @@ function* test_cache_cleared() {
                          "memory",
                          Ci.nsICacheStorage.OPEN_NORMALLY,
                          LoadContextInfo.custom(false, {userContextId}));
   }
 
 
   // Check that caches have been set correctly.
   for (let userContextId of Object.keys(USER_CONTEXTS)) {
-    let mem = getCacheStorage("memory");
-    let disk = getCacheStorage("disk");
+    let mem = getCacheStorage("memory", LoadContextInfo.custom(false, {userContextId}));
+    let disk = getCacheStorage("disk", LoadContextInfo.custom(false, {userContextId}));
 
     Assert.ok(mem.exists(createURI("http://" + TEST_HOST + "/"), ""), "The memory cache has been set correctly");
     Assert.ok(disk.exists(createURI("http://" + TEST_HOST + "/"), ""), "The disk cache has been set correctly");
   }
 
   // Forget the site.
   ForgetAboutSite.removeDataFromDomain(TEST_HOST);
 
   // Check that do caches be removed or not?
   for (let userContextId of Object.keys(USER_CONTEXTS)) {
-    let mem = getCacheStorage("memory");
-    let disk = getCacheStorage("disk");
+    let mem = getCacheStorage("memory", LoadContextInfo.custom(false, {userContextId}));
+    let disk = getCacheStorage("disk", LoadContextInfo.custom(false, {userContextId}));
 
     Assert.ok(!mem.exists(createURI("http://" + TEST_HOST + "/"), ""), "The memory cache is cleared");
     Assert.ok(!disk.exists(createURI("http://" + TEST_HOST + "/"), ""), "The disk cache is cleared");
   }
 }
 
 // Image Cache
 function* test_image_cache_cleared() {
@@ -299,17 +299,17 @@ function* test_storage_cleared() {
       let request = content.indexedDB.open("idb", 1);
 
       let db = yield new Promise(done => {
         request.onsuccess = event => {
           done(event.target.result);
         };
       });
       try {
-        let transaction = db.transaction(["obj"], "readonly");
+        db.transaction(["obj"], "readonly");
         Assert.ok(false, "The indexedDB should not exist");
       } catch (e) {
         Assert.equal(e.name, "NotFoundError", "The indexedDB does not exist as expected");
       }
     });
 
     // Close the tab.
     yield BrowserTestUtils.removeTab(tabInfo.tab);
--- a/browser/components/contextualidentity/test/browser/browser_middleClick.js
+++ b/browser/components/contextualidentity/test/browser/browser_middleClick.js
@@ -9,17 +9,17 @@ add_task(function* () {
 
   let tab = gBrowser.addTab(URI, { userContextId: 1 });
   gBrowser.selectedTab = tab;
 
   let browser = gBrowser.getBrowserForTab(tab);
   yield BrowserTestUtils.browserLoaded(browser);
 
   info("Create a HTMLAnchorElement...");
-  let position = yield ContentTask.spawn(browser, URI,
+  yield ContentTask.spawn(browser, URI,
     function(URI) {
       let anchor = content.document.createElement("a");
       anchor.setAttribute('id', 'clickMe');
       anchor.setAttribute("href", URI);
       anchor.appendChild(content.document.createTextNode("click me!"));
       content.document.body.appendChild(anchor);
     }
   );
--- a/browser/components/customizableui/CustomizableUI.jsm
+++ b/browser/components/customizableui/CustomizableUI.jsm
@@ -329,17 +329,17 @@ var CustomizableUIInternal = {
     }
   },
 
   _introduceNewBuiltinWidgets: function() {
     // We should still enter even if gSavedState.currentVersion >= kVersion
     // because the per-widget pref facility is independent of versioning.
     if (!gSavedState) {
       // Flip all the prefs so we don't try to re-introduce later:
-      for (let [id, widget] of gPalette) {
+      for (let [, widget] of gPalette) {
         if (widget.defaultArea && widget._introducedInVersion === "pref") {
           let prefId = "browser.toolbarbuttons.introduced." + widget.id;
           Services.prefs.setBoolPref(prefId, true);
         }
       }
       return;
     }
 
@@ -605,17 +605,16 @@ var CustomizableUIInternal = {
     }
   },
 
   registerToolbarNode: function(aToolbar, aExistingChildren) {
     let area = aToolbar.id;
     if (gBuildAreas.has(area) && gBuildAreas.get(area).has(aToolbar)) {
       return;
     }
-    let document = aToolbar.ownerDocument;
     let areaProperties = gAreas.get(area);
 
     // If this area is not registered, try to do it automatically:
     if (!areaProperties) {
       // If there's no defaultset attribute and this isn't a legacy extra toolbar,
       // we assume that we should wait for registerArea to be called:
       if (!aToolbar.hasAttribute("defaultset") &&
           !aToolbar.hasAttribute("customindex")) {
@@ -1074,25 +1073,25 @@ var CustomizableUIInternal = {
       }
     }
 
     for (let [, widget] of gPalette) {
       widget.instances.delete(document);
       this.notifyListeners("onWidgetInstanceRemoved", widget.id, document);
     }
 
-    for (let [area, areaMap] of gPendingBuildAreas) {
+    for (let [, areaMap] of gPendingBuildAreas) {
       let toDelete = [];
       for (let [areaNode, ] of areaMap) {
         if (areaNode.ownerDocument == document) {
           toDelete.push(areaNode);
         }
       }
       for (let areaNode of toDelete) {
-        areaMap.delete(toDelete);
+        areaMap.delete(areaNode);
       }
     }
 
     this.notifyListeners("onWindowClosed", aWindow);
   },
 
   setLocationAttributes: function(aNode, aArea) {
     let props = gAreas.get(aArea);
@@ -2179,17 +2178,17 @@ var CustomizableUIInternal = {
           area.set("defaultPlacements", [widget.id]);
         }
       }
     }
 
     // Look through previously saved state to see if we're restoring a widget.
     let seenAreas = new Set();
     let widgetMightNeedAutoAdding = true;
-    for (let [area, placements] of gPlacements) {
+    for (let [area, ] of gPlacements) {
       seenAreas.add(area);
       let areaIsRegistered = gAreas.has(area);
       let index = gPlacements.get(area).indexOf(widget.id);
       if (index != -1) {
         widgetMightNeedAutoAdding = false;
         if (areaIsRegistered) {
           widget.currentArea = area;
           widget.currentPosition = index;
--- a/browser/components/customizableui/CustomizableWidgets.jsm
+++ b/browser/components/customizableui/CustomizableWidgets.jsm
@@ -479,17 +479,16 @@ const CustomizableWidgets = [
       } else {
         for (let tab of client.tabs) {
           let tabEnt = this._createTabElement(doc, tab);
           attachFragment.appendChild(tabEnt);
         }
       }
     },
     _createTabElement(doc, tabInfo) {
-      let win = doc.defaultView;
       let item = doc.createElementNS(kNSXUL, "toolbarbutton");
       let tooltipText = (tabInfo.title ? tabInfo.title + "\n" : "") + tabInfo.url;
       item.setAttribute("itemtype", "tab");
       item.setAttribute("class", "subviewbutton");
       item.setAttribute("targetURI", tabInfo.url);
       item.setAttribute("label", tabInfo.title != "" ? tabInfo.title : tabInfo.url);
       item.setAttribute("image", tabInfo.icon);
       item.setAttribute("tooltiptext", tooltipText);
@@ -544,17 +543,16 @@ const CustomizableWidgets = [
     type: "view",
     viewId: "PanelUI-sidebar",
     tooltiptext: "sidebar-button.tooltiptext2",
     onViewShowing: function(aEvent) {
       // Populate the subview with whatever menuitems are in the
       // sidebar menu. We skip menu elements, because the menu panel has no way
       // of dealing with those right now.
       let doc = aEvent.target.ownerDocument;
-      let win = doc.defaultView;
       let menu = doc.getElementById("viewSidebarMenu");
 
       // First clear any existing menuitems then populate. Add it to the
       // standard menu first, then copy all sidebar options to the panel.
       let sidebarItems = doc.getElementById("PanelUI-sidebarItems");
       clearSubview(sidebarItems);
       fillSubviewFromMenuItems([...menu.children], sidebarItems);
     }
--- a/browser/components/customizableui/CustomizeMode.jsm
+++ b/browser/components/customizableui/CustomizeMode.jsm
@@ -37,17 +37,16 @@ XPCOMUtils.defineLazyModuleGetter(this, 
                                   "resource://gre/modules/LightweightThemeManager.jsm");
 XPCOMUtils.defineLazyModuleGetter(this, "SessionStore",
                                   "resource:///modules/sessionstore/SessionStore.jsm");
 
 let gDebug;
 XPCOMUtils.defineLazyGetter(this, "log", () => {
   let scope = {};
   Cu.import("resource://gre/modules/Console.jsm", scope);
-  let ConsoleAPI = scope.ConsoleAPI;
   try {
     gDebug = Services.prefs.getBoolPref(kPrefCustomizationDebug);
   } catch (ex) {}
   let consoleOptions = {
     maxLogLevel: gDebug ? "all" : "log",
     prefix: "CustomizeMode",
   };
   return new scope.ConsoleAPI(consoleOptions);
@@ -241,17 +240,16 @@ CustomizeMode.prototype = {
           };
 
           Services.obs.addObserver(delayedStartupObserver, "browser-delayed-startup-finished", false);
         });
       }
 
       let toolbarVisibilityBtn = document.getElementById(kToolbarVisibilityBtn);
       let togglableToolbars = window.getTogglableToolbars();
-      let bookmarksToolbar = document.getElementById("PersonalToolbar");
       if (togglableToolbars.length == 0) {
         toolbarVisibilityBtn.setAttribute("hidden", "true");
       } else {
         toolbarVisibilityBtn.removeAttribute("hidden");
       }
 
       this.updateLWTStyling();
 
@@ -422,17 +420,16 @@ CustomizeMode.prototype = {
     this.window.PanelUI.menuButton.open = false;
 
     this.window.PanelUI.beginBatchUpdate();
 
     this._removePanelCustomizationPlaceholders();
 
     let window = this.window;
     let document = this.document;
-    let documentElement = document.documentElement;
 
     // Hide the palette before starting the transition for increased perf.
     this.visiblePalette.hidden = true;
     this.visiblePalette.removeAttribute("showing");
     this.paletteEmptyNotice.hidden = true;
 
     // Disable the button-text fade-out mask
     // during the transition for increased perf.
@@ -1401,29 +1398,27 @@ CustomizeMode.prototype = {
       let currentLwt = LightweightThemeManager.currentTheme;
       for (let lwt of lwts) {
         lwt.isActive = !!currentLwt && (lwt.id == currentLwt.id);
         themes.push(lwt);
       }
 
       let footer = doc.getElementById("customization-lwtheme-menu-footer");
       let panel = footer.parentNode;
-      let themesInMyThemesSection = 0;
       let recommendedLabel = doc.getElementById("customization-lwtheme-menu-recommended");
       for (let theme of themes) {
         let button = buildToolbarButton(theme);
         button.addEventListener("command", () => {
           if ("userDisabled" in button.theme)
             button.theme.userDisabled = false;
           else
             LightweightThemeManager.currentTheme = button.theme;
           onThemeSelected(panel);
         });
         panel.insertBefore(button, recommendedLabel);
-        themesInMyThemesSection++;
       }
 
       let lwthemePrefs = Services.prefs.getBranch("lightweightThemes.");
       let recommendedThemes = lwthemePrefs.getComplexValue("recommendedThemes",
                                                            Ci.nsISupportsString).data;
       recommendedThemes = JSON.parse(recommendedThemes);
       let sb = Services.strings.createBundle("chrome://browser/locale/lightweightThemes.properties");
       for (let theme of recommendedThemes) {
--- a/browser/components/customizableui/DragPositionManager.jsm
+++ b/browser/components/customizableui/DragPositionManager.jsm
@@ -29,17 +29,16 @@ function AreaPositionManager(aContainer)
   this.update(aContainer);
 }
 
 AreaPositionManager.prototype = {
   _nodePositionStore: null,
   _wideCache: null,
 
   update: function(aContainer) {
-    let window = aContainer.ownerGlobal;
     this._nodePositionStore = new WeakMap();
     this._wideCache = new Set();
     let last = null;
     let singleItemHeight;
     for (let child of aContainer.children) {
       if (child.hidden) {
         continue;
       }
@@ -414,9 +413,8 @@ var DragPositionManager = {
   },
 
   getManagerForArea: function(aArea) {
     return gManagers.get(aArea);
   }
 };
 
 Object.freeze(DragPositionManager);
-
--- a/browser/components/customizableui/PanelWideWidgetTracker.jsm
+++ b/browser/components/customizableui/PanelWideWidgetTracker.jsm
@@ -34,17 +34,16 @@ var PanelWideWidgetTracker = {
       gPanelPlacements = CustomizableUI.getWidgetIdsInArea(gPanel);
       let moveForward = this.shouldMoveForward(aWidgetId, aNewPosition);
       this.adjustWidgets(aWidgetId, moveForward);
     }
   },
   onWidgetRemoved: function(aWidgetId, aPrevArea) {
     if (aPrevArea == gPanel) {
       gPanelPlacements = CustomizableUI.getWidgetIdsInArea(gPanel);
-      let pos = gPanelPlacements.indexOf(aWidgetId);
       this.adjustWidgets(aWidgetId, false);
     }
   },
   onWidgetReset: function(aWidgetId) {
     gPanelPlacements = CustomizableUI.getWidgetIdsInArea(gPanel);
   },
   // Listener to keep abreast of any new nodes. We use the DOM one because
   // we need access to the actual node's classlist, so we can't use the ones above.
--- a/browser/components/customizableui/test/browser_1096763_seen_widgets_post_reset.js
+++ b/browser/components/customizableui/test/browser_1096763_seen_widgets_post_reset.js
@@ -1,14 +1,14 @@
 "use strict";
 
 const BUTTONID = "test-seenwidget-post-reset";
 
 add_task(function*() {
-  let widget = CustomizableUI.createWidget({
+  CustomizableUI.createWidget({
     id: BUTTONID,
     label: "Test widget seen post reset",
     defaultArea: CustomizableUI.AREA_NAVBAR
   });
 
   const kPrefCustomizationState = "browser.uiCustomization.state";
   let bsPass = Cu.import("resource:///modules/CustomizableUI.jsm", {});
   ok(bsPass.gSeenWidgets.has(BUTTONID), "Widget should be seen after createWidget is called.");
--- a/browser/components/customizableui/test/browser_1161838_inserted_new_default_buttons.js
+++ b/browser/components/customizableui/test/browser_1161838_inserted_new_default_buttons.js
@@ -16,19 +16,16 @@ function test() {
   // Force us to have a saved state:
   CustomizableUIInternal.saveState();
   CustomizableUIInternal.loadSavedState();
 
   CustomizableUIInternal._introduceNewBuiltinWidgets();
   is(gFuturePlacements.size, 0,
      "No change to future placements initially.");
 
-  let currentVersion = CustomizableUIBSPass.kVersion;
-
-
   // Add our widget to the defaults:
   let testWidgetNew = {
     id: "test-messing-with-default-placements-new-pref",
     label: "Test messing with default placements - pref-based",
     defaultArea: CustomizableUI.AREA_NAVBAR,
     introducedInVersion: "pref",
   };
 
@@ -74,9 +71,8 @@ function test() {
   gFuturePlacements.delete(CustomizableUI.AREA_NAVBAR);
   let indexInDefaultPlacements = navbarPlacements.indexOf(testWidgetNew.id);
   if (indexInDefaultPlacements != -1) {
     navbarPlacements.splice(indexInDefaultPlacements, 1);
   }
   gPalette.delete(testWidgetNew.id);
   CustomizableUI.reset();
 }
-
--- a/browser/components/customizableui/test/browser_878452_drag_to_panel.js
+++ b/browser/components/customizableui/test/browser_878452_drag_to_panel.js
@@ -3,17 +3,16 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 "use strict";
 
 // Dragging an item from the palette to another button in the panel should work.
 add_task(function*() {
   yield startCustomizing();
   let btn = document.getElementById("feed-button");
-  let panel = document.getElementById(CustomizableUI.AREA_PANEL);
   let placements = getAreaWidgetIds(CustomizableUI.AREA_PANEL);
 
   let lastButtonIndex = placements.length - 1;
   let lastButton = placements[lastButtonIndex];
   let placementsAfterInsert = placements.slice(0, lastButtonIndex).concat(["feed-button", lastButton]);
   let lastButtonNode = document.getElementById(lastButton);
   simulateItemDrag(btn, lastButtonNode);
   assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterInsert);
--- a/browser/components/customizableui/test/browser_880164_customization_context_menus.js
+++ b/browser/components/customizableui/test/browser_880164_customization_context_menus.js
@@ -112,17 +112,16 @@ add_task(function*() {
 
 // Right-click on the urlbar-container should
 // show a context menu with disabled options to move it.
 add_task(function*() {
   let contextMenu = document.getElementById("toolbar-context-menu");
   let shownPromise = popupShown(contextMenu);
   let urlBarContainer = document.getElementById("urlbar-container");
   // Need to make sure not to click within an edit field.
-  let urlbarRect = urlBarContainer.getBoundingClientRect();
   EventUtils.synthesizeMouse(urlBarContainer, 100, 1, {type: "contextmenu", button: 2 });
   yield shownPromise;
 
   let expectedEntries = [
     [".customize-context-moveToPanel", false],
     [".customize-context-removeFromToolbar", false],
     ["---"]
   ];
--- a/browser/components/customizableui/test/browser_884402_customize_from_overflow.js
+++ b/browser/components/customizableui/test/browser_884402_customize_from_overflow.js
@@ -14,17 +14,16 @@ registerCleanupFunction(function() {
 // show a context menu with options to move it.
 add_task(function*() {
 
   overflowPanel.setAttribute("animate", "false");
 
   originalWindowWidth = window.outerWidth;
   let navbar = document.getElementById(CustomizableUI.AREA_NAVBAR);
   ok(!navbar.hasAttribute("overflowing"), "Should start with a non-overflowing toolbar.");
-  let oldChildCount = navbar.customizationTarget.childElementCount;
   window.resizeTo(400, window.outerHeight);
 
   yield waitForCondition(() => navbar.hasAttribute("overflowing"));
   ok(navbar.hasAttribute("overflowing"), "Should have an overflowing toolbar.");
 
   let chevron = document.getElementById("nav-bar-overflow-button");
   let shownPanelPromise = promisePanelElementShown(window, overflowPanel);
   chevron.click();
--- a/browser/components/customizableui/test/browser_938995_indefaultstate_nonremovable.js
+++ b/browser/components/customizableui/test/browser_938995_indefaultstate_nonremovable.js
@@ -3,17 +3,16 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 "use strict";
 
 const kWidgetId = "test-non-removable-widget";
 
 // Adding non-removable items to a toolbar or the panel shouldn't change inDefaultState
 add_task(function() {
-  let navbar = document.getElementById("nav-bar");
   ok(CustomizableUI.inDefaultState, "Should start in default state");
 
   let button = createDummyXULButton(kWidgetId, "Test non-removable inDefaultState handling");
   CustomizableUI.addWidgetToArea(kWidgetId, CustomizableUI.AREA_NAVBAR);
   button.setAttribute("removable", "false");
   ok(CustomizableUI.inDefaultState, "Should still be in default state after navbar addition");
   button.remove();
 
--- a/browser/components/customizableui/test/browser_962069_drag_to_overflow_chevron.js
+++ b/browser/components/customizableui/test/browser_962069_drag_to_overflow_chevron.js
@@ -7,17 +7,16 @@
 var originalWindowWidth;
 
 // Drag to overflow chevron should open the overflow panel.
 add_task(function*() {
   originalWindowWidth = window.outerWidth;
   let navbar = document.getElementById(CustomizableUI.AREA_NAVBAR);
   ok(!navbar.hasAttribute("overflowing"), "Should start with a non-overflowing toolbar.");
   ok(CustomizableUI.inDefaultState, "Should start in default state.");
-  let oldChildCount = navbar.customizationTarget.childElementCount;
   window.resizeTo(400, window.outerHeight);
   yield waitForCondition(() => navbar.hasAttribute("overflowing"));
   ok(navbar.hasAttribute("overflowing"), "Should have an overflowing toolbar.");
 
   let widgetOverflowPanel = document.getElementById("widget-overflow");
   let panelShownPromise = promisePanelElementShown(window, widgetOverflowPanel);
   let identityBox = document.getElementById("identity-box");
   let overflowChevron = document.getElementById("nav-bar-overflow-button");
--- a/browser/components/customizableui/test/browser_967000_button_sync.js
+++ b/browser/components/customizableui/test/browser_967000_button_sync.js
@@ -189,20 +189,18 @@ add_task(function* () {
   PanelUI.hide();
 
   Services.prefs.clearUserPref("identity.mobilepromo.android");
   Services.prefs.clearUserPref("identity.mobilepromo.ios");
 });
 
 // Test the "Sync Now" button
 add_task(function* () {
-  let nSyncs = 0;
   mockedInternal.getTabClients = () => [];
   mockedInternal.syncTabs = () => {
-    nSyncs++;
     return Promise.resolve();
   }
 
   // configure our broadcasters so we are in the right state.
   document.getElementById("sync-reauth-state").hidden = true;
   document.getElementById("sync-setup-state").hidden = true;
   document.getElementById("sync-syncnow-state").hidden = false;
 
--- a/browser/components/customizableui/test/browser_973641_button_addon.js
+++ b/browser/components/customizableui/test/browser_973641_button_addon.js
@@ -27,17 +27,16 @@ add_task(function*() {
   ok(addonButton, "Addon button exists");
   ok(navBar.contains(addonButton), "Addon button is in the navbar");
   yield checkButtonFunctionality(addonButton);
 
   resetTabs();
 
   // move the add-on button in the Panel Menu
   CustomizableUI.addWidgetToArea(kButton, CustomizableUI.AREA_PANEL);
-  let addonButtonInNavbar = navBar.getElementsByAttribute("id", kButton);
   ok(!navBar.contains(addonButton), "Addon button was removed from the browser bar");
 
   // check the addon button's functionality in the Panel Menu
   yield PanelUI.show();
   var panelMenu = document.getElementById("PanelUI-mainView");
   let addonButtonInPanel = panelMenu.getElementsByAttribute("id", kButton);
   ok(panelMenu.contains(addonButton), "Addon button was added to the Panel Menu");
   yield checkButtonFunctionality(addonButtonInPanel[0]);
--- a/browser/components/customizableui/test/browser_984455_bookmarks_items_reparenting.js
+++ b/browser/components/customizableui/test/browser_984455_bookmarks_items_reparenting.js
@@ -57,17 +57,16 @@ function checkPlacesContextMenu(aItemWit
 
 /**
  * Opens the bookmarks menu panel, and then opens each of the "special"
  * submenus in that list. Then it checks that those submenu's context menus
  * are properly hooked up to a controller.
  */
 function checkSpecialContextMenus() {
   return Task.spawn(function* () {
-    let contextMenu = document.getElementById("placesContext");
     let bookmarksMenuButton = document.getElementById(kBookmarksButton);
     let bookmarksMenuPopup = document.getElementById("BMB_bookmarksPopup");
 
     const kSpecialItemIDs = {
       "BMB_bookmarksToolbar": "BMB_bookmarksToolbarPopup",
       "BMB_unsortedBookmarks": "BMB_unsortedBookmarksPopup",
     };
 
--- a/browser/components/customizableui/test/head.js
+++ b/browser/components/customizableui/test/head.js
@@ -471,17 +471,16 @@ function popupHidden(aPopup) {
  *   yield popupShownPromise;
  *
  *  let popupHiddenPromise = promisePopupEvent(somePopup, "hidden");
  *  // ... something that hides a popup
  *  yield popupHiddenPromise;
  */
 function promisePopupEvent(aPopup, aEventSuffix) {
   let deferred = Promise.defer();
-  let win = aPopup.ownerGlobal;
   let eventType = "popup" + aEventSuffix;
 
   function onPopupEvent(e) {
     aPopup.removeEventListener(eventType, onPopupEvent);
     deferred.resolve();
   }
 
   aPopup.addEventListener(eventType, onPopupEvent);
--- a/browser/components/distribution.js
+++ b/browser/components/distribution.js
@@ -106,17 +106,17 @@ DistributionCustomizer.prototype = {
     let re = /^item\.(\d+)\.(\w+)\.?(\w*)/;
     let items = {};
     let defaultIndex = -1;
     let maxIndex = -1;
 
     for (let key of keys) {
       let m = re.exec(key);
       if (m) {
-        let [foo, itemIndex, iprop, ilocale] = m;
+        let [, itemIndex, iprop, ilocale] = m;
         itemIndex = parseInt(itemIndex);
 
         if (ilocale)
           continue;
 
         if (keys.indexOf(key + "." + this._locale) >= 0) {
           key += "." + this._locale;
         } else if (keys.indexOf(key + "." + this._language) >= 0) {
--- a/browser/components/feeds/FeedConverter.js
+++ b/browser/components/feeds/FeedConverter.js
@@ -294,17 +294,19 @@ FeedConverter.prototype = {
       let httpChannel = channel.QueryInterface(Ci.nsIHttpChannel);
       // Make sure to check requestSucceeded before the potentially-throwing
       // getResponseHeader.
       if (!httpChannel.requestSucceeded) {
         // Just give up, but don't forget to cancel the channel first!
         request.cancel(Cr.NS_BINDING_ABORTED);
         return;
       }
-      let noSniff = httpChannel.getResponseHeader("X-Moz-Is-Feed");
+
+      // Note: this throws if the header is not set.
+      httpChannel.getResponseHeader("X-Moz-Is-Feed");
     }
     catch (ex) {
       this._sniffed = true;
     }
 
     this._request = request;
 
     // Save and reset the forced state bit early, in case there's some kind of
--- a/browser/components/feeds/FeedWriter.js
+++ b/browser/components/feeds/FeedWriter.js
@@ -479,20 +479,16 @@ FeedWriter.prototype = {
    * @returns element
    */
   _buildEnclosureDiv(entry) {
     let enclosuresDiv = this._document.createElementNS(HTML_NS, "div");
     enclosuresDiv.className = "enclosures";
 
     enclosuresDiv.appendChild(this._document.createTextNode(this._getString("mediaLabel")));
 
-    let roundme = function(n) {
-      return (Math.round(n * 100) / 100).toLocaleString();
-    }
-
     for (let i_enc = 0; i_enc < entry.enclosures.length; ++i_enc) {
       let enc = entry.enclosures.queryElementAt(i_enc, Ci.nsIWritablePropertyBag2);
 
       if (!(enc.hasKey("url")))
         continue;
 
       let enclosureDiv = this._document.createElementNS(HTML_NS, "div");
       enclosureDiv.setAttribute("class", "enclosure");
@@ -514,18 +510,19 @@ FeedWriter.prototype = {
 
         } catch (ex) { }
 
       }
 
       if (enc.hasKey("length") && /^[0-9]+$/.test(enc.get("length"))) {
         let enc_size = convertByteUnits(parseInt(enc.get("length")));
 
-        let size_text = this._getFormattedString("enclosureSizeText",
-                             [enc_size[0], this._getString(enc_size[1])]);
+        size_text = this._getFormattedString("enclosureSizeText",
+                                             [enc_size[0],
+                                             this._getString(enc_size[1])]);
       }
 
       let iconimg = this._document.createElementNS(HTML_NS, "img");
       iconimg.setAttribute("src", mozicon);
       iconimg.setAttribute("class", "type-icon");
       enclosureDiv.appendChild(iconimg);
 
       enclosureDiv.appendChild(this._document.createTextNode( " " ));
@@ -1056,17 +1053,16 @@ FeedWriter.prototype = {
                                 { pref: aPrefName,
                                   value: aPrefValue });
   },
 
   subscribe() {
     let feedType = this._getFeedType();
 
     // Subscribe to the feed using the selected handler and save prefs
-    let prefs = Services.prefs;
     let defaultHandler = "reader";
     let useAsDefault = this._document.getElementById("alwaysUse").getAttribute("checked");
 
     let menuList = this._document.getElementById("handlersMenuList");
     let selectedItem = menuList.selectedOptions[0];
     let subscribeCallback = () => {
       if (selectedItem.hasAttribute("webhandlerurl")) {
         let webURI = selectedItem.getAttribute("webhandlerurl");
@@ -1079,17 +1075,17 @@ FeedWriter.prototype = {
         if (handler) {
           if (useAsDefault) {
             wccr.setAutoHandler(this._getMimeTypeForFeedType(feedType), handler);
           }
 
           this._window.location.href = handler.getHandlerURI(this._window.location.href);
         }
       } else {
-        let prefReader = null;
+        let feedReader = null;
         switch (selectedItem.id) {
           case "selectedAppMenuItem":
             feedReader = "client";
             break;
           case "defaultHandlerMenuItem":
             feedReader = "default";
             break;
           case "liveBookmarksMenuItem":
--- a/browser/components/feeds/test/unit/test_758990.js
+++ b/browser/components/feeds/test/unit/test_758990.js
@@ -1,42 +1,42 @@
 function run_test() {
   var success = false;
   try {
-    var newURI = ios.newURI("feed:javascript:alert('hi');", null, null);
+    ios.newURI("feed:javascript:alert('hi');", null, null);
   }
   catch (e) {
     success = e.result == Cr.NS_ERROR_MALFORMED_URI;
   }
   if (!success)
     do_throw("We didn't throw NS_ERROR_MALFORMED_URI creating a feed:javascript: URI");
 
   success = false;
   try {
-    newURI = ios.newURI("feed:data:text/html,hi", null, null);
+    ios.newURI("feed:data:text/html,hi", null, null);
   }
   catch (e) {
     success = e.result == Cr.NS_ERROR_MALFORMED_URI;
   }
   if (!success)
     do_throw("We didn't throw NS_ERROR_MALFORMED_URI creating a feed:data: URI");
 
   success = false;
   try {
-    newURI = ios.newURI("pcast:javascript:alert('hi');", null, null);
+    ios.newURI("pcast:javascript:alert('hi');", null, null);
   }
   catch (e) {
     success = e.result == Cr.NS_ERROR_MALFORMED_URI;
   }
   if (!success)
     do_throw("We didn't throw NS_ERROR_MALFORMED_URI creating a pcast:javascript: URI");
 
   success = false;
   try {
-    newURI = ios.newURI("pcast:data:text/html,hi", null, null);
+    ios.newURI("pcast:data:text/html,hi", null, null);
   }
   catch (e) {
     success = e.result == Cr.NS_ERROR_MALFORMED_URI;
   }
   if (!success)
     do_throw("We didn't throw NS_ERROR_MALFORMED_URI creating a pcast:data: URI");
 
 }
--- a/browser/components/nsBrowserContentHandler.js
+++ b/browser/components/nsBrowserContentHandler.js
@@ -713,17 +713,17 @@ nsDefaultCommandLineHandler.prototype = 
       // displayed) we will crash if we open an url and then select a profile. To
       // prevent this handle all url command line flags and set the command line's
       // preventDefault to true to prevent the display of the ui. The initial
       // command line will be retained when nsAppRunner calls LaunchChild though
       // urls launched after the initial launch will be lost.
       if (!this._haveProfile) {
         try {
           // This will throw when a profile has not been selected.
-          var dir = Services.dirsvc.get("ProfD", Components.interfaces.nsILocalFile);
+          Services.dirsvc.get("ProfD", Components.interfaces.nsILocalFile);
           this._haveProfile = true;
         }
         catch (e) {
           while ((ar = cmdLine.handleFlagWithParam("url", false)));
           cmdLine.preventDefault = true;
         }
       }
     }
--- a/browser/components/nsBrowserGlue.js
+++ b/browser/components/nsBrowserGlue.js
@@ -1443,19 +1443,19 @@ BrowserGlue.prototype = {
                         accessKey: key,
                         popup:     null,
                         callback: function(aNotificationBar, aButton) {
                           win.openUILinkIn(url, "tab");
                         }
                       }
                     ];
 
-      let notification = notifyBox.appendNotification(text, "post-update-notification",
-                                                      null, notifyBox.PRIORITY_INFO_LOW,
-                                                      buttons);
+      notifyBox.appendNotification(text, "post-update-notification",
+                                   null, notifyBox.PRIORITY_INFO_LOW,
+                                   buttons);
     }
 
     if (actions.indexOf("showAlert") == -1)
       return;
 
     let title = getNotifyString({propName: "alertTitle",
                                  stringName: "puAlertTitle",
                                  stringParams: [appName]});
--- a/browser/components/places/content/bookmarkProperties.js
+++ b/browser/components/places/content/bookmarkProperties.js
@@ -628,22 +628,16 @@ var BookmarkPropertiesPanel = {
               Ci.nsINavHistoryResultNode.RESULT_TYPE_FOLDER
     });
   }),
 
   _promiseNewItem: Task.async(function* () {
     if (!PlacesUIUtils.useAsyncTransactions)
       return this._createNewItem();
 
-    let txnFunc =
-      { [BOOKMARK_FOLDER]: PlacesTransactions.NewFolder,
-        [LIVEMARK_CONTAINER]: PlacesTransactions.NewLivemark,
-        [BOOKMARK_ITEM]: PlacesTransactions.NewBookmark
-      }[this._itemType];
-
     let [containerId, index] = this._getInsertionPointDetails();
     let parentGuid = yield PlacesUtils.promiseItemGuid(containerId);
     let annotations = [];
     if (this._description) {
       annotations.push({ name: PlacesUIUtils.DESCRIPTION_ANNO
                        , value: this._description });
     }
     if (this._loadInSidebar) {
--- a/browser/components/places/content/browserPlacesViews.js
+++ b/browser/components/places/content/browserPlacesViews.js
@@ -1397,17 +1397,16 @@ PlacesToolbar.prototype = {
   /**
    * This function returns information about where to drop when dragging over
    * the toolbar.  The returned object has the following properties:
    * - ip: the insertion point for the bookmarks service.
    * - beforeIndex: child index to drop before, for the drop indicator.
    * - folderElt: the folder to drop into, if applicable.
    */
   _getDropPoint: function PT__getDropPoint(aEvent) {
-    let result = this.result;
     if (!PlacesUtils.nodeIsFolder(this._resultNode))
       return null;
 
     let dropPoint = { ip: null, beforeIndex: null, folderElt: null };
     let elt = aEvent.target;
     if (elt._placesNode && elt != this._rootElt &&
         elt.localName != "menupopup") {
       let eltRect = elt.getBoundingClientRect();
--- a/browser/components/places/content/controller.js
+++ b/browser/components/places/content/controller.js
@@ -384,17 +384,17 @@ PlacesController.prototype = {
       var data = { }, type = { };
       xferable.getAnyTransferData(type, data, { });
       data = data.value.QueryInterface(Ci.nsISupportsString).data;
       if (type.value != PlacesUtils.TYPE_X_MOZ_URL &&
           type.value != PlacesUtils.TYPE_UNICODE)
         return false;
 
       // unwrapNodes() will throw if the data blob is malformed.
-      var unwrappedNodes = PlacesUtils.unwrapNodes(data, type.value);
+      PlacesUtils.unwrapNodes(data, type.value);
       return this._view.insertionPoint != null;
     }
     catch (e) {
       // getAnyTransferData or unwrapNodes failed
       return false;
     }
   },
 
@@ -1599,17 +1599,16 @@ var PlacesControllerDragHelper = {
       if (flavor != TAB_DROP_TYPE) {
         // There's only ever one in the D&D case.
         unwrapped = PlacesUtils.unwrapNodes(data, flavor)[0];
       }
       else if (data instanceof XULElement && data.localName == "tab" &&
                data.ownerGlobal instanceof ChromeWindow) {
         let uri = data.linkedBrowser.currentURI;
         let spec = uri ? uri.spec : "about:blank";
-        let title = data.label;
         unwrapped = { uri: spec,
                       title: data.label,
                       type: PlacesUtils.TYPE_X_MOZ_URL};
       }
       else
         throw new Error("bogus data was passed as a tab");
 
       let index = insertionPoint.index;
@@ -1736,9 +1735,8 @@ function doGetPlacesControllerForCommand
 }
 
 function goDoPlacesCommand(aCommand)
 {
   let controller = doGetPlacesControllerForCommand(aCommand);
   if (controller && controller.isCommandEnabled(aCommand))
     controller.doCommand(aCommand);
 }
-
--- a/browser/components/places/content/editBookmarkOverlay.js
+++ b/browser/components/places/content/editBookmarkOverlay.js
@@ -190,18 +190,17 @@ var gEditItemOverlay = {
       }
     }
 
     // For sanity ensure that the implementer has uninited the panel before
     // trying to init it again, or we could end up leaking due to observers.
     if (this.initialized)
       this.uninitPanel(false);
 
-    let { itemId, itemGuid, isItem,
-          isURI, uri, title,
+    let { itemId, isItem, isURI,
           isBookmark, bulkTagging, uris,
           visibleRows, focusedElement } = this._setPaneInfo(aInfo);
 
     let showOrCollapse =
       (rowId, isAppropriateForInput, nameInHiddenRows = null) => {
         let visible = isAppropriateForInput;
         if (visible && "hiddenRows" in aInfo && nameInHiddenRows)
           visible &= aInfo.hiddenRows.indexOf(nameInHiddenRows) == -1;
@@ -621,17 +620,16 @@ var gEditItemOverlay = {
       // TODO: Bug 1089141 - Provide some feedback about the invalid url.
       return;
     }
 
     if (this._paneInfo.uri.equals(newURI))
       return;
 
     if (!PlacesUIUtils.useAsyncTransactions) {
-      let itemId = this._paneInfo.itemId;
       let txn = new PlacesEditBookmarkURITransaction(this._paneInfo.itemId, newURI);
       PlacesUtils.transactionManager.doTransaction(txn);
       return;
     }
     let guid = this._paneInfo.itemGuid;
     PlacesTransactions.EditUrl({ guid, url: newURI })
                       .transact().catch(Components.utils.reportError);
   },
--- a/browser/components/places/content/places.js
+++ b/browser/components/places/content/places.js
@@ -566,17 +566,16 @@ var PlacesOrganizer = {
      * The details of simple folder-items (as opposed to livemarks) or the
      * of livemark-children are not likely to fill the infoBox anyway,
      * thus we remove the "More/Less" button and show all details.
      *
      * the wasminimal attribute here is used to persist the "more/less"
      * state in a bookmark->folder->bookmark scenario.
      */
     var infoBox = document.getElementById("infoBox");
-    var infoBoxExpander = document.getElementById("infoBoxExpander");
     var infoBoxExpanderWrapper = document.getElementById("infoBoxExpanderWrapper");
     var additionalInfoBroadcaster = document.getElementById("additionalInfoBroadcaster");
 
     if (!aNode) {
       infoBoxExpanderWrapper.hidden = true;
       return;
     }
     if (aNode.itemId != -1 &&
@@ -1363,17 +1362,17 @@ var ContentArea = {
    * Options for the current view.
    *
    * @see ContentTree.viewOptions for supported options and default values.
    */
   get currentViewOptions() {
     // Use ContentTree options as default.
     let viewOptions = ContentTree.viewOptions;
     if (this._specialViews.has(this.currentPlace)) {
-      let { view, options } = this._specialViews.get(this.currentPlace);
+      let { options } = this._specialViews.get(this.currentPlace);
       for (let option in options) {
         viewOptions[option] = options[option];
       }
     }
     return viewOptions;
   },
 
   focus: function() {
--- a/browser/components/places/content/treeView.js
+++ b/browser/components/places/content/treeView.js
@@ -275,18 +275,16 @@ PlacesTreeView.prototype = {
     let cc = aContainer.childCount;
     let newElements = new Array(cc);
     this._rows = this._rows.splice(0, aFirstChildRow)
                      .concat(newElements, this._rows);
 
     if (this._isPlainContainer(aContainer))
       return cc;
 
-    const openLiteral = PlacesUIUtils.RDF.GetResource("http://home.netscape.com/NC-rdf#open");
-    const trueLiteral = PlacesUIUtils.RDF.GetLiteral("true");
     let sortingMode = this._result.sortingMode;
 
     let rowsInserted = 0;
     for (let i = 0; i < cc; i++) {
       let curChild = aContainer.getChild(i);
       let curChildType = curChild.type;
 
       let row = aFirstChildRow + rowsInserted;
@@ -1055,17 +1053,16 @@ PlacesTreeView.prototype = {
       sortedColumn.element.removeAttribute("sortDirection");
 
     // Set new sorting indicator by looking through all columns for ours.
     if (aSortingMode == Ci.nsINavHistoryQueryOptions.SORT_BY_NONE)
       return;
 
     let [desiredColumn, desiredIsDescending] =
       this._sortTypeToColumnType(aSortingMode);
-    let colCount = columns.count;
     let column = this._findColumnByType(desiredColumn);
     if (column) {
       let sortDir = desiredIsDescending ? "descending" : "ascending";
       column.element.setAttribute("sortDirection", sortDir);
     }
   },
 
   _inBatchMode: false,
@@ -1380,17 +1377,17 @@ PlacesTreeView.prototype = {
       PlacesControllerDragHelper.onDrop(ip, aDataTransfer)
                                 .then(null, Components.utils.reportError);
     }
 
     PlacesControllerDragHelper.currentDropTarget = null;
   },
 
   getParentIndex: function PTV_getParentIndex(aRow) {
-    let [parentNode, parentRow] = this._getParentByChildRow(aRow);
+    let [, parentRow] = this._getParentByChildRow(aRow);
     return parentRow;
   },
 
   hasNextSibling: function PTV_hasNextSibling(aRow, aAfterIndex) {
     if (aRow == this._rows.length - 1) {
       // The last row has no sibling.
       return false;
     }
--- a/browser/components/places/tests/browser/browser_425884.js
+++ b/browser/components/places/tests/browser/browser_425884.js
@@ -117,13 +117,11 @@ function validate(aNode) {
   PlacesUtils.asContainer(aNode);
   aNode.containerOpen = true;
   is(aNode.childCount, 1, "confirm child count match");
   var folderNode = aNode.getChild(0);
   is(folderNode.title, "test folder", "confirm folder title");
   PlacesUtils.asContainer(folderNode);
   folderNode.containerOpen = true;
   is(folderNode.childCount, 2, "confirm child count match");
-  var bookmarkNode = folderNode.getChild(0);
-  var separatorNode = folderNode.getChild(1);
   folderNode.containerOpen = false;
   aNode.containerOpen = false;
 }
--- a/browser/components/places/tests/browser/browser_bookmarkProperties_addFolderDefaultButton.js
+++ b/browser/components/places/tests/browser/browser_bookmarkProperties_addFolderDefaultButton.js
@@ -12,17 +12,16 @@ add_task(function* () {
     type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
     parentGuid: PlacesUtils.bookmarks.unfiledGuid,
     url: "http://example.com/",
   });
   let newBookmarkId = yield PlacesUtils.promiseItemId(newBookmark.guid);
 
   yield withSidebarTree("bookmarks", function* (tree) {
     // Select the new bookmark in the sidebar.
-    let itemId = PlacesUIUtils.leftPaneQueries["UnfiledBookmarks"];
     tree.selectItems([newBookmarkId]);
     ok(tree.controller.isCommandEnabled("placesCmd_new:folder"),
        "'placesCmd_new:folder' on current selected node is enabled");
 
     // Create a new folder.  Since the new bookmark is selected, and new items
     // are inserted at the index of the currently selected item, the new folder
     // will be inserted at index 0.
     yield withBookmarksDialog(
--- a/browser/components/places/tests/browser/browser_library_commands.js
+++ b/browser/components/places/tests/browser/browser_library_commands.js
@@ -133,21 +133,21 @@ add_task(function* test_query_on_toolbar
      "Query node bookmark has been correctly removed");
 
   toolbarNode.containerOpen = false;
 
   library.close();
 });
 
 add_task(function* test_search_contents() {
-  let item = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
-                                                  url: "http://example.com/",
-                                                  title: "example page",
-                                                  parentGuid: PlacesUtils.bookmarks.unfiledGuid,
-                                                  index: 0 });
+  yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
+                                       url: "http://example.com/",
+                                       title: "example page",
+                                       parentGuid: PlacesUtils.bookmarks.unfiledGuid,
+                                       index: 0 });
 
   let library = yield promiseLibrary();
   info("Ensure query contents can be cut or deleted");
 
   // Select and open the left pane "Bookmarks Toolbar" folder.
   let PO = library.PlacesOrganizer;
 
   PO.selectLeftPaneQuery('BookmarksToolbar');
@@ -170,21 +170,21 @@ add_task(function* test_search_contents(
      "Cut command is enabled");
   ok(library.ContentTree.view.controller.isCommandEnabled("cmd_delete"),
      "Delete command is enabled");
 
   library.close();
 });
 
 add_task(function* test_tags() {
-  let item = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
-                                                  url: "http://example.com/",
-                                                  title: "example page",
-                                                  parentGuid: PlacesUtils.bookmarks.unfiledGuid,
-                                                  index: 0 });
+  yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
+                                       url: "http://example.com/",
+                                       title: "example page",
+                                       parentGuid: PlacesUtils.bookmarks.unfiledGuid,
+                                       index: 0 });
   PlacesUtils.tagging.tagURI(NetUtil.newURI("http://example.com/"), ["test"]);
 
   let library = yield promiseLibrary();
   info("Ensure query contents can be cut or deleted");
 
   // Select and open the left pane "Bookmarks Toolbar" folder.
   let PO = library.PlacesOrganizer;
 
--- a/browser/components/places/tests/browser/browser_library_views_liveupdate.js
+++ b/browser/components/places/tests/browser/browser_library_views_liveupdate.js
@@ -182,18 +182,17 @@ var bookmarksObserver = {
       default:
         isnot(node, null, "Found new Places node in left pane");
         ok(index >= 0, "Node is at index " + index);
     }
   },
 
   onItemRemoved: function PSB_onItemRemoved(aItemId, aFolder, aIndex) {
     var node = null;
-    var index = null;
-    [node, index] = getNodeForTreeItem(aItemId, gLibrary.PlacesOrganizer._places);
+    [node, ] = getNodeForTreeItem(aItemId, gLibrary.PlacesOrganizer._places);
     is(node, null, "Places node not found in left pane");
   },
 
   onItemMoved: function(aItemId,
                         aOldFolderId, aOldIndex,
                         aNewFolderId, aNewIndex, aItemType) {
     var node = null;
     var index = null;
@@ -225,17 +224,17 @@ var bookmarksObserver = {
                                             aIsAnnotationProperty, aNewValue) {
     if (aProperty == "title") {
       let validator = function(aTreeRowIndex) {
         let tree = gLibrary.PlacesOrganizer._places;
         let cellText = tree.view.getCellText(aTreeRowIndex,
                                              tree.columns.getColumnAt(0));
         return cellText == aNewValue;
       }
-      let [node, index, valid] = getNodeForTreeItem(aItemId, gLibrary.PlacesOrganizer._places, validator);
+      let [node, , valid] = getNodeForTreeItem(aItemId, gLibrary.PlacesOrganizer._places, validator);
       if (node) // Only visible nodes.
         ok(valid, "Title cell value has been correctly updated");
     }
   }
 };
 
 
 /**
--- a/browser/components/places/tests/browser/browser_views_liveupdate.js
+++ b/browser/components/places/tests/browser/browser_views_liveupdate.js
@@ -213,18 +213,17 @@ var bookmarksObserver = {
 
   onItemRemoved: function PSB_onItemRemoved(aItemId, aFolderId, aIndex,
                                             aItemType) {
     var views = getViewsForFolder(aFolderId);
     ok(views.length > 0, "Found affected views (" + views.length + "): " + views);
     // Check that item has been removed.
     for (var i = 0; i < views.length; i++) {
       var node = null;
-      var index = null;
-      [node, index] = searchItemInView(aItemId, views[i]);
+      [node, ] = searchItemInView(aItemId, views[i]);
       is(node, null, "Places node not found in " + views[i]);
     }
   },
 
   onItemMoved: function(aItemId,
                         aOldFolderId, aOldIndex,
                         aNewFolderId, aNewIndex,
                         aItemType) {
@@ -268,17 +267,17 @@ var bookmarksObserver = {
       }
       if (!aNewValue && aElementOrTreeIndex.localName != "toolbarbutton") {
         return aElementOrTreeIndex.getAttribute("label") == PlacesUIUtils.getBestTitle(aElementOrTreeIndex._placesNode);
       }
       return aElementOrTreeIndex.getAttribute("label") == aNewValue;
     };
 
     for (var i = 0; i < views.length; i++) {
-      var [node, index, valid] = searchItemInView(aItemId, views[i], validator);
+      var [node, , valid] = searchItemInView(aItemId, views[i], validator);
       isnot(node, null, "Found changed Places node in " + views[i]);
       is(node.title, aNewValue, "Node has correct title: " + aNewValue);
       ok(valid, "Node element has correct label: " + aNewValue);
     }
   }
 };
 
 /**
--- a/browser/components/places/tests/unit/test_browserGlue_smartBookmarks.js
+++ b/browser/components/places/tests/unit/test_browserGlue_smartBookmarks.js
@@ -32,17 +32,17 @@ function countFolderChildren(aFolderItem
     print("Found child(" + i + "): " + title);
   }
   rootNode.containerOpen = false;
   return cc;
 }
 
 add_task(function* setup() {
   // Initialize browserGlue, but remove it's listener to places-init-complete.
-  let bg = Cc["@mozilla.org/browser/browserglue;1"].getService(Ci.nsIObserver);
+  Cc["@mozilla.org/browser/browserglue;1"].getService(Ci.nsIObserver);
 
   // Initialize Places.
   PlacesUtils.history;
 
   // Wait for Places init notification.
   yield promiseTopicObserved("places-browser-init-complete");
 
   // Ensure preferences status.
--- a/browser/components/preferences/cookies.js
+++ b/browser/components/preferences/cookies.js
@@ -466,18 +466,16 @@ var gCookiesWindow = {
       ++aHostCount.value;
     }
 
     var c = this._makeCookieObject(aStrippedHost, aCookie);
     this._hosts[aStrippedHost].cookies.push(c);
   },
 
   _makeCookieObject: function (aStrippedHost, aCookie) {
-    var host = aCookie.host;
-    var formattedHost = host.charAt(0) == "." ? host.substring(1, host.length) : host;
     var c = { name            : aCookie.name,
               value           : aCookie.value,
               isDomain        : aCookie.isDomain,
               host            : aCookie.host,
               rawHost         : aStrippedHost,
               path            : aCookie.path,
               isSecure        : aCookie.isSecure,
               expires         : aCookie.expires,
--- a/browser/components/preferences/in-content/content.js
+++ b/browser/components/preferences/in-content/content.js
@@ -38,17 +38,16 @@ var gContentPane = {
       row.removeAttribute("hidden");
       // Showing attribution only for Bing Translator.
       Components.utils.import("resource:///modules/translation/Translation.jsm");
       if (Translation.translationEngine == "bing") {
         document.getElementById("bingAttribution").removeAttribute("hidden");
       }
     }
 
-    let doNotDisturbAlertsEnabled = false;
     if (AlertsServiceDND) {
       let notificationsDoNotDisturbRow =
         document.getElementById("notificationsDoNotDisturbRow");
       notificationsDoNotDisturbRow.removeAttribute("hidden");
       if (AlertsServiceDND.manualDoNotDisturb) {
         let notificationsDoNotDisturb =
           document.getElementById("notificationsDoNotDisturb");
         notificationsDoNotDisturb.setAttribute("checked", true);
--- a/browser/components/preferences/in-content/main.js
+++ b/browser/components/preferences/in-content/main.js
@@ -291,19 +291,19 @@ var gMainPane = {
   /**
    * Displays a dialog in which the user can select a bookmark to use as home
    * page.  If the user selects a bookmark, that bookmark's name is displayed in
    * UI and the bookmark's address is stored to the home page preference.
    */
   setHomePageToBookmark: function ()
   {
     var rv = { urls: null, names: null };
-    var dialog = gSubDialog.open("chrome://browser/content/preferences/selectBookmark.xul",
-                                 "resizable=yes, modal=yes", rv,
-                                 this._setHomePageToBookmarkClosed.bind(this, rv));
+    gSubDialog.open("chrome://browser/content/preferences/selectBookmark.xul",
+                    "resizable=yes, modal=yes", rv,
+                    this._setHomePageToBookmarkClosed.bind(this, rv));
   },
 
   _setHomePageToBookmarkClosed: function(rv, aEvent) {
     if (aEvent.detail.button != "accept")
       return;
     if (rv.urls && rv.names) {
       var homePage = document.getElementById("browser.startup.homepage");
 
--- a/browser/components/preferences/permissions.js
+++ b/browser/components/preferences/permissions.js
@@ -396,17 +396,16 @@ var gPermissionManager = {
   },
 
   _loadPermissions: function ()
   {
     this._tree = document.getElementById("permissionsTree");
     this._permissions = [];
 
     // load permissions into a table
-    var count = 0;
     var enumerator = Services.perms.enumerator;
     while (enumerator.hasMoreElements()) {
       var nextPermission = enumerator.getNext().QueryInterface(Components.interfaces.nsIPermission);
       this._addPermissionToList(nextPermission);
     }
 
     this._view._rowCount = this._permissions.length;
 
--- a/browser/components/search/content/search.xml
+++ b/browser/components/search/content/search.xml
@@ -816,18 +816,16 @@
           return true;
         },
 
         doCommand: function (aCommand) {
           switch (aCommand) {
             case "cmd_clearhistory":
               var param = this._self.getAttribute("autocompletesearchparam");
 
-              let searchBar = this._self.parentNode;
-
               BrowserSearch.searchBar.FormHistory.update({ op : "remove", fieldname : param }, null);
               this._self.value = "";
               break;
             case "cmd_togglesuggest":
               // The pref observer will update _suggestEnabled and the menu
               // checkmark.
               Services.prefs.setBoolPref("browser.search.suggest.enabled",
                                          !this._self._suggestEnabled);
@@ -1677,19 +1675,16 @@
         @return True if the selection can continue to advance after this method
                 returns and false if not.
       -->
       <method name="advanceSelection">
         <parameter name="aForward"/>
         <parameter name="aWrapAround"/>
         <parameter name="aCycleEngines"/>
         <body><![CDATA[
-          let popup = this.popup;
-          let list = document.getAnonymousElementByAttribute(popup, "anonid",
-                                                             "search-panel-one-offs");
           let selectedButton = this.selectedButton;
           let buttons = this.getSelectableButtons(aCycleEngines);
 
           if (selectedButton) {
             // cycle through one-off buttons.
             let index = buttons.indexOf(selectedButton);
             if (aForward)
               ++index;
--- a/browser/components/search/test/browser_426329.js
+++ b/browser/components/search/test/browser_426329.js
@@ -158,17 +158,17 @@ add_task(function* testShiftAltReturn() 
   return;
   /*
   yield* prepareTest();
 
   let url = expectedURL(searchBar.value);
 
   let newTabPromise = BrowserTestUtils.waitForNewTab(gBrowser, url);
   EventUtils.synthesizeKey("VK_RETURN", { shiftKey: true, altKey: true });
-  let newTab = yield newTabPromise;
+  yield newTabPromise;
 
   is(gBrowser.tabs.length, preTabNo + 1, "Shift+Alt+Return key added new tab");
   is(gBrowser.currentURI.spec, url, "testShiftAltReturn opened correct search page");
   */
 });
 
 add_task(function* testLeftClick() {
   yield* prepareTest();
--- a/browser/components/search/test/browser_abouthome_behavior.js
+++ b/browser/components/search/test/browser_abouthome_behavior.js
@@ -6,27 +6,28 @@
  */
 
 "use strict";
 
 function test() {
   // Bug 992270: Ignore uncaught about:home exceptions (related to snippets from IndexedDB)
   ignoreAllUncaughtExceptions(true);
 
+  let previouslySelectedEngine = Services.search.currentEngine;
+
   function replaceUrl(base) {
     return base;
   }
 
   let gMutationObserver = null;
 
   function verify_about_home_search(engine_name) {
     let engine = Services.search.getEngineByName(engine_name);
     ok(engine, engine_name + " is installed");
 
-    let previouslySelectedEngine = Services.search.currentEngine;
     Services.search.currentEngine = engine;
 
     // load about:home, but remove the listener first so it doesn't
     // get in the way
     gBrowser.removeProgressListener(listener);
     gBrowser.loadURI("about:home");
     info("Waiting for about:home load");
     tab.linkedBrowser.addEventListener("load", function load(event) {
@@ -123,16 +124,17 @@ function test() {
 
       req.cancel(Components.results.NS_ERROR_FAILURE);
 
       executeSoon(nextTest);
     }
   }
 
   registerCleanupFunction(function () {
+    Services.search.currentEngine = previouslySelectedEngine;
     gBrowser.removeProgressListener(listener);
     gBrowser.removeTab(tab);
     if (gMutationObserver)
       gMutationObserver.disconnect();
   });
 
   tab.linkedBrowser.addEventListener("load", function load() {
     tab.linkedBrowser.removeEventListener("load", load, true);
--- a/browser/components/search/test/browser_private_search_perwindowpb.js
+++ b/browser/components/search/test/browser_private_search_perwindowpb.js
@@ -2,18 +2,16 @@
 // search in a private window, and then checks in the public window
 // whether there is an autocomplete entry for the private search.
 
 add_task(function* () {
   // Don't use about:home as the homepage for new windows
   Services.prefs.setIntPref("browser.startup.page", 0);
   registerCleanupFunction(() => Services.prefs.clearUserPref("browser.startup.page"));
 
-  let engineURL =
-    "http://mochi.test:8888/browser/browser/components/search/test/";
   let windowsToClose = [];
 
   function performSearch(aWin, aIsPrivate) {
     let searchBar = aWin.BrowserSearch.searchBar;
     ok(searchBar, "got search bar");
 
     let loadPromise = BrowserTestUtils.browserLoaded(aWin.gBrowser.selectedBrowser);
 
--- a/browser/components/search/test/browser_searchbar_keyboard_navigation.js
+++ b/browser/components/search/test/browser_searchbar_keyboard_navigation.js
@@ -366,17 +366,17 @@ add_task(function* test_tab_and_arrows()
   // Finally close the panel.
   let promise = promiseEvent(searchPopup, "popuphidden");
   searchPopup.hidePopup();
   yield promise;
 });
 
 add_task(function* test_open_search() {
   let rootDir = getRootDirectory(gTestPath);
-  let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, rootDir + "opensearch.html");
+  yield BrowserTestUtils.openNewForegroundTab(gBrowser, rootDir + "opensearch.html");
 
   let promise = promiseEvent(searchPopup, "popupshown");
   info("Opening search panel");
   searchbar.focus();
   yield promise;
 
   let engines = getOpenSearchItems();
   is(engines.length, 2, "the opensearch.html page exposes 2 engines")
--- a/browser/components/search/test/browser_searchbar_openpopup.js
+++ b/browser/components/search/test/browser_searchbar_openpopup.js
@@ -127,17 +127,16 @@ add_task(function* open_empty() {
   is(searchPopup.getAttribute("showonlysettings"), "true", "Should only show the settings");
   is(textbox.mController.searchString, "", "Should be an empty search string");
 
   // By giving the textbox some text any next attempt to open the search popup
   // from the click handler will try to search for this text.
   textbox.value = "foo";
 
   promise = promiseEvent(searchPopup, "popuphidden");
-  let clickPromise = promiseEvent(searchIcon, "click");
 
   info("Hiding popup");
   yield synthesizeNativeMouseClick(searchIcon);
   yield promise;
 
   is(textbox.mController.searchString, "", "Should not have started to search for the new text");
 
   // Cancel the search if it started.
--- a/browser/components/search/test/browser_searchbar_smallpanel_keyboard_navigation.js
+++ b/browser/components/search/test/browser_searchbar_smallpanel_keyboard_navigation.js
@@ -294,17 +294,17 @@ add_task(function* test_tab_and_arrows()
   // Finally close the panel.
   let promise = promiseEvent(searchPopup, "popuphidden");
   searchPopup.hidePopup();
   yield promise;
 });
 
 add_task(function* test_open_search() {
   let rootDir = getRootDirectory(gTestPath);
-  let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, rootDir + "opensearch.html");
+  yield BrowserTestUtils.openNewForegroundTab(gBrowser, rootDir + "opensearch.html");
 
   let promise = promiseEvent(searchPopup, "popupshown");
   info("Opening search panel");
   EventUtils.synthesizeMouseAtCenter(searchIcon, {});
   yield promise;
   is(searchPopup.getAttribute("showonlysettings"), "true", "Should show the small popup");
 
   let engines = getOpenSearchItems();
--- a/browser/components/shell/test/browser_420786.js
+++ b/browser/components/shell/test/browser_420786.js
@@ -65,25 +65,22 @@ function onPageLoad() {
   if (wpFileBackup.exists())
     wpFileBackup.moveTo(null, wpFile.leafName);
 
   gBrowser.removeCurrentTab();
   finish();
 }
 
 function test() {
-  var osString = Cc["@mozilla.org/xre/app-info;1"].
-                 getService(Ci.nsIXULRuntime).OS;
-
   try {
     // If GSettings is available, then the GConf tests
     // will fail
-    var gsettings = Cc["@mozilla.org/gsettings-service;1"].
-                    getService(Ci.nsIGSettingsService).
-                    getCollectionForSchema("org.gnome.desktop.background");
+    Cc["@mozilla.org/gsettings-service;1"].
+      getService(Ci.nsIGSettingsService).
+      getCollectionForSchema("org.gnome.desktop.background");
     todo(false, "This test doesn't work when GSettings is available");
     return;
   } catch (e) { }
 
   gBrowser.selectedTab = gBrowser.addTab();
   gBrowser.selectedBrowser.addEventListener("load", onPageLoad, true);
   content.location = "about:logo";
 
--- a/browser/components/shell/test/unit/test_421977.js
+++ b/browser/components/shell/test/unit/test_421977.js
@@ -65,19 +65,19 @@ function run_test() {
 
   // This test is Linux specific for now
   if (!("@mozilla.org/gnome-gconf-service;1" in Cc))
     return;
 
   try {
     // If GSettings is available, then the GConf tests
     // will fail
-    var gsettings = Cc["@mozilla.org/gsettings-service;1"].
-                    getService(Ci.nsIGSettingsService).
-                    getCollectionForSchema("org.gnome.desktop.background");
+    Cc["@mozilla.org/gsettings-service;1"].
+      getService(Ci.nsIGSettingsService).
+      getCollectionForSchema("org.gnome.desktop.background");
     return;
   } catch (e) { }
 
   gGConf = Cc["@mozilla.org/gnome-gconf-service;1"].
            getService(Ci.nsIGConfService);
 
   gShell = Cc["@mozilla.org/browser/shell-service;1"].
            getService(Ci.nsIShellService);
--- a/browser/components/syncedtabs/SyncedTabsListStore.js
+++ b/browser/components/syncedtabs/SyncedTabsListStore.js
@@ -121,17 +121,16 @@ Object.assign(SyncedTabsListStore.protot
     } else if (childRow < branch.tabs.length) {
       this.selectRow(branchRow, childRow + 1);
     }
   },
 
   moveSelectionUp() {
     let branchRow = this._selectedRow[0];
     let childRow = this._selectedRow[1];
-    let branch = this.data[branchRow];
 
     if (this.filter) {
       this.selectRow(branchRow - 1);
       return;
     }
 
     if (branchRow < 0) {
       this.selectRow(0, -1);
@@ -229,9 +228,8 @@ Object.assign(SyncedTabsListStore.protot
           this._SyncedTabs.sortTabClientsByLastUsed(result);
         }
         this.data = result;
         this._change(updateType);
       })
       .catch(Cu.reportError);
   }
 });
-
--- a/browser/components/syncedtabs/test/xpcshell/test_SyncedTabsDeckComponent.js
+++ b/browser/components/syncedtabs/test/xpcshell/test_SyncedTabsDeckComponent.js
@@ -180,17 +180,16 @@ add_task(function* testPanelStatus() {
 
   sinon.stub(component, "getPanelStatus", () => Promise.resolve("mock-panelId"));
   sinon.spy(deckStore, "selectPanel");
   yield component.updatePanel();
   Assert.ok(deckStore.selectPanel.calledWith("mock-panelId"));
 });
 
 add_task(function* testActions() {
-  let listComponent = {};
   let windowMock = {
     openUILink() {},
   };
   let chromeWindowMock = {
     gSyncUI: {
       openSetup() {}
     }
   };
--- a/browser/components/translation/BingTranslator.jsm
+++ b/browser/components/translation/BingTranslator.jsm
@@ -414,17 +414,17 @@ var BingTokenManager = {
       onError: function(e, responseText, xhr) {
         BingTokenManager._pendingRequest = null;
         deferred.reject(e);
       },
       postData: params
     };
 
     this._pendingRequest = deferred.promise;
-    let request = httpRequest(url, options);
+    httpRequest(url, options);
 
     return deferred.promise;
   }
 };
 
 /**
  * Escape a string to be valid XML content.
  */
--- a/browser/components/translation/TranslationDocument.jsm
+++ b/browser/components/translation/TranslationDocument.jsm
@@ -498,17 +498,16 @@ function parseResultNode(item, node) {
  * @param item     A TranslationItem object
  * @param target   A string that is either "translation"
  *                 or "original".
  */
 function swapTextForItem(item, target) {
   // visitStack is the stack of items that we still need to visit.
   // Let's start the process by adding the root item.
   let visitStack = [ item ];
-  let source = target == "translation" ? "original" : "translation";
 
   while (visitStack.length > 0) {
     let curItem = visitStack.shift();
 
     let domNode = curItem.nodeRef;
     if (!domNode) {
       // Skipping this item due to a missing node.
       continue;
--- a/browser/components/translation/test/browser_translation_infobar.js
+++ b/browser/components/translation/test/browser_translation_infobar.js
@@ -189,17 +189,16 @@ function run_tests(aFinishCallback) {
   notif._getAnonElt("translate").click();
   is(notif.state, Translation.STATE_TRANSLATING, "the infobar is in the translating state");
   ok(!!notif.translation.translatedFrom, "Translation.translate has been called");
   is(notif.translation.translatedFrom, "ja", "from language correct");
   notif.close();
 
   info("Reopen to check the 'Not Now' button closes the notification.");
   notif = showTranslationUI("fr");
-  let notificationBox = gBrowser.getNotificationBox();
   is(hasTranslationInfoBar(), true, "there's a 'translate' notification");
   notif._getAnonElt("notNow").click();
   is(hasTranslationInfoBar(), false, "no 'translate' notification after clicking 'not now'");
 
   info("Reopen to check the url bar icon closes the notification.");
   notif = showTranslationUI("fr");
   is(hasTranslationInfoBar(), true, "there's a 'translate' notification");
   PopupNotifications.getNotification("translate").anchorElement.click();
--- a/browser/components/translation/test/browser_translation_telemetry.js
+++ b/browser/components/translation/test/browser_translation_telemetry.js
@@ -213,17 +213,18 @@ add_task(function* test_show_original() 
     yield translate("<h1>Hallo Welt!</h1><h1>Bratwurst!</h1>", "de", false);
   yield MetricsChecker.checkAdditions({ pageCount: 1, showOriginal: 0 });
   getInfobarElement(tab.linkedBrowser, "showOriginal").doCommand();
   yield MetricsChecker.checkAdditions({ pageCount: 0, showOriginal: 1 });
   gBrowser.removeTab(tab);
 });
 
 add_task(function* test_language_change() {
-  for (let i of Array(4)) {
+  // This is run 4 times, the total additions are checked afterwards.
+  for (let i of Array(4)) { // eslint-disable-line no-unused-vars
     let tab = yield offerTranslationFor("<h1>Hallo Welt!</h1>", "fr");
     let browser = tab.linkedBrowser;
     // In the offer state, translation is executed by the Translate button,
     // so we expect just a single recoding.
     let detectedLangMenulist = getInfobarElement(browser, "detectedLanguage");
     simulateUserSelectInMenulist(detectedLangMenulist, "de");
     simulateUserSelectInMenulist(detectedLangMenulist, "it");
     simulateUserSelectInMenulist(detectedLangMenulist, "de");
--- a/browser/components/uitour/UITour.jsm
+++ b/browser/components/uitour/UITour.jsm
@@ -175,17 +175,16 @@ this.UITour = {
                                                         "anonid",
                                                         "searchbar-search-button");
       },
       widgetName: "search-container",
     }],
     ["searchPrefsLink", {
       query: (aDocument) => {
         let element = null;
-        let searchbar = aDocument.getElementById("searchbar");
         let popup = aDocument.getElementById("PopupSearchAutoComplete");
         if (popup.state != "open")
           return null;
         element = aDocument.getAnonymousElementByAttribute(popup,
                                                            "anonid",
                                                            "search-settings");
         if (!element || !UITour.isElementVisible(element)) {
           return null;
@@ -1827,17 +1826,17 @@ this.UITour = {
 
         let canSetDefaultBrowserInBackground = true;
         if (AppConstants.isPlatformAndVersionAtLeast("win", "6.2") ||
             AppConstants.isPlatformAndVersionAtLeast("macosx", "10.10")) {
           canSetDefaultBrowserInBackground = false;
         } else if (AppConstants.platform == "linux") {
           // The ShellService may not exist on some versions of Linux.
           try {
-            let shell = aWindow.getShellService();
+            aWindow.getShellService();
           } catch (e) {
             canSetDefaultBrowserInBackground = null;
           }
         }
 
         appinfo["canSetDefaultBrowserInBackground"] =
           canSetDefaultBrowserInBackground;
 
--- a/browser/components/uitour/test/browser_UITour3.js
+++ b/browser/components/uitour/test/browser_UITour3.js
@@ -114,17 +114,16 @@ add_UITour_task(function* test_info_butt
   ok(true, "Popup should close automatically");
 
   let returnValue = yield waitForCallbackResultPromise();
 
   is(returnValue.result, "button2", "Correct callback should have been called");
 }),
 
 add_UITour_task(function* test_info_close_button() {
-  let popup = document.getElementById("UITourTooltip");
   let closeButton = document.getElementById("UITourTooltipClose");
 
   yield showInfoPromise("urlbar", "Close me", "X marks the spot", null, null, "makeInfoOptions");
 
   EventUtils.synthesizeMouseAtCenter(closeButton, {}, window);
 
   let returnValue = yield waitForCallbackResultPromise();
 
--- a/browser/extensions/flyweb/bootstrap.js
+++ b/browser/extensions/flyweb/bootstrap.js
@@ -232,17 +232,16 @@ let FlyWebView = {
       onDestroyed(aDocument) {
         aDocument.defaultView.QueryInterface(Ci.nsIInterfaceRequestor).
             getInterface(Ci.nsIDOMWindowUtils).removeSheet(this._sheetURI, 1);
       },
 
       onViewShowing(aEvent) {
         let doc = aEvent.target.ownerDocument;
 
-        let panel = doc.getElementById("flyweb-panel");
         let items = doc.getElementById("flyweb-items");
         let empty = doc.getElementById("flyweb-items-empty");
 
         if (!gDiscoveryManagerInstance) {
           gDiscoveryManagerInstance = new DiscoveryManager(doc.defaultView);
         }
 
         gDiscoveryManagerInstance.start((services) => {
--- a/browser/modules/FormSubmitObserver.jsm
+++ b/browser/modules/FormSubmitObserver.jsm
@@ -190,17 +190,16 @@ FormSubmitObserver.prototype =
 
     // Note, this is relative to the browser and needs to be translated
     // in chrome.
     panelData.contentRect = BrowserUtils.getElementBoundingRect(aElement);
 
     // We want to show the popup at the middle of checkbox and radio buttons
     // and where the content begin for the other elements.
     let offset = 0;
-    let position = "";
 
     if (aElement.tagName == 'INPUT' &&
         (aElement.type == 'radio' || aElement.type == 'checkbox')) {
       panelData.position = "bottomcenter topleft";
     } else {
       let win = aElement.ownerGlobal;
       let style = win.getComputedStyle(aElement, null);
       if (style.direction == 'rtl') {
--- a/browser/modules/PluginContent.jsm
+++ b/browser/modules/PluginContent.jsm
@@ -130,17 +130,16 @@ PluginContent.prototype = {
 
   observe: function observe(aSubject, aTopic, aData) {
     switch (aTopic) {
       case "decoder-doctor-notification":
         let data = JSON.parse(aData);
         if (this.haveShownNotification &&
             aSubject.top.document == this.content.document &&
             data.formats.toLowerCase().includes("application/x-mpegurl", 0)) {
-          let pluginHost = Cc["@mozilla.org/plugin/host;1"].getService(Ci.nsIPluginHost);
           let principal = this.content.document.nodePrincipal;
           let location = this.content.document.location.href;
           this.global.content.pluginRequiresReload = true;
           this.global.sendAsyncMessage("PluginContent:ShowClickToPlayNotification",
                                        { plugins: [... this.pluginData.values()],
                                          showNow: true,
                                          location: location,
                                        }, null, principal);
@@ -448,17 +447,16 @@ PluginContent.prototype = {
           win.mozHiddenPluginTouched = true;
         } catch (e) {
           Cu.reportError("Error adding plugin replacement style sheet: " + e);
         }
       }
     }
 
     let plugin = event.target;
-    let doc = plugin.ownerDocument;
 
     if (eventType == "PluginPlaceholderReplaced") {
       plugin.removeAttribute("href");
       let overlay = this.getPluginUI(plugin, "main");
       this.setVisibility(plugin, overlay, true);
       let inIDOMUtils = Cc["@mozilla.org/inspector/dom-utils;1"]
                           .getService(Ci.inIDOMUtils);
       // Add psuedo class so our styling will take effect
@@ -509,17 +507,16 @@ PluginContent.prototype = {
         let { pluginTag } = this._getPluginInfo(plugin);
         this.addLinkClickCallback(updateLink, "forwardCallback",
                                   "openPluginUpdatePage", pluginTag);
         /* FALLTHRU */
 
       case "PluginVulnerableNoUpdate":
       case "PluginClickToPlay":
         this._handleClickToPlayEvent(plugin);
-        let overlay = this.getPluginUI(plugin, "main");
         let pluginName = this._getPluginInfo(plugin).pluginName;
         let messageString = gNavigatorBundle.formatStringFromName("PluginClickToActivate", [pluginName], 1);
         let overlayText = this.getPluginUI(plugin, "clickToPlay");
         overlayText.textContent = messageString;
         if (eventType == "PluginVulnerableUpdatable" ||
             eventType == "PluginVulnerableNoUpdate") {
           let vulnerabilityString = gNavigatorBundle.GetStringFromName(eventType);
           let vulnerabilityText = this.getPluginUI(plugin, "vulnerabilityStatus");
--- a/browser/modules/ProcessHangMonitor.jsm
+++ b/browser/modules/ProcessHangMonitor.jsm
@@ -208,17 +208,17 @@ var ProcessHangMonitor = {
     return null;
   },
 
   /**
    * Find a paused hang report for the given <browser> element.
    */
   findPausedReport: function(browser) {
     let frameLoader = browser.QueryInterface(Ci.nsIFrameLoaderOwner).frameLoader;
-    for (let [report, timer] of this._pausedReports) {
+    for (let [report, ] of this._pausedReports) {
       if (report.isReportForBrowser(frameLoader)) {
         return report;
       }
     }
     return null;
   },
 
   /**
@@ -283,17 +283,16 @@ var ProcessHangMonitor = {
   showNotification: function(win, report) {
     let nb = win.document.getElementById("high-priority-global-notificationbox");
     let notification = nb.getNotificationWithValue("process-hang");
     if (notification) {
       return;
     }
 
     let bundle = win.gNavigatorBundle;
-    let brandBundle = win.document.getElementById("bundle_brand");
 
     let buttons = [{
         label: bundle.getString("processHang.button_stop.label"),
         accessKey: bundle.getString("processHang.button_stop.accessKey"),
         callback: function() {
           ProcessHangMonitor.stopIt(win);
         }
       },
--- a/browser/modules/RemotePrompt.jsm
+++ b/browser/modules/RemotePrompt.jsm
@@ -32,17 +32,16 @@ var RemotePrompt = {
         }
         break;
     }
   },
 
   openTabPrompt: function(args, browser) {
     let window = browser.ownerGlobal;
     let tabPrompt = window.gBrowser.getTabModalPromptBox(browser)
-    let callbackInvoked = false;
     let newPrompt;
     let needRemove = false;
     let promptId = args._remoteId;
 
     function onPromptClose(forceCleanup) {
       // It's possible that we removed the prompt during the
       // appendPrompt call below. In that case, newPrompt will be
       // undefined. We set the needRemove flag to remember to remove
--- a/browser/modules/Windows8WindowFrameColor.jsm
+++ b/browser/modules/Windows8WindowFrameColor.jsm
@@ -28,17 +28,17 @@ var Windows8WindowFrameColor = {
     }
 
     // The color returned from the Registry is in decimal form.
     let customizationColorHex = customizationColor.toString(16);
 
     // Zero-pad the number just to make sure that it is 8 digits.
     customizationColorHex = ("00000000" + customizationColorHex).substr(-8);
     let customizationColorArray = customizationColorHex.match(/../g);
-    let [unused, fgR, fgG, fgB] = customizationColorArray.map(val => parseInt(val, 16));
+    let [, fgR, fgG, fgB] = customizationColorArray.map(val => parseInt(val, 16));
     let colorizationColorBalance = Registry.readRegKey(HKCU, dwmKey,
                                                        "ColorizationColorBalance");
     if (colorizationColorBalance == undefined) {
       colorizationColorBalance = 78;
     }
 
     // Window frame base color when Color Intensity is at 0, see bug 1004576.
     let frameBaseColor = 217;
--- a/browser/modules/WindowsPreviewPerTab.jsm
+++ b/browser/modules/WindowsPreviewPerTab.jsm
@@ -466,17 +466,17 @@ TabWindow.prototype = {
     return this._enabled;
   },
 
   set enabled (enable) {
     this._enabled = enable;
     // Because making a tab visible requires that the tab it is next to be
     // visible, it is far simpler to unset the 'next' tab and recreate them all
     // at once.
-    for (let [tab, preview] of this.previews) {
+    for (let [, preview] of this.previews) {
       preview.move(null);
       preview.visible = enable;
     }
     this.updateTabOrdering();
   },
 
   previewFromTab: function (tab) {
     return this.previews.get(tab);
@@ -830,17 +830,17 @@ this.AeroPeek = {
   onFrecencyChanged() {},
   onManyFrecenciesChanged() {},
   onDeleteURI() {},
   onClearHistory() {},
   onDeleteVisits() {},
   onPageChanged(uri, changedConst, newValue) {
     if (this.enabled && changedConst == Ci.nsINavHistoryObserver.ATTRIBUTE_FAVICON) {
       for (let win of this.windows) {
-        for (let [tab, preview] of win.previews) {
+        for (let [tab, ] of win.previews) {
           if (tab.getAttribute("image") == newValue) {
             win.onLinkIconAvailable(tab.linkedBrowser, newValue);
           }
         }
       }
     }
   },
 
--- a/browser/modules/test/browser_ContentSearch.js
+++ b/browser/modules/test/browser_ContentSearch.js
@@ -109,17 +109,16 @@ add_task(function* search() {
 });
 
 add_task(function* searchInBackgroundTab() {
   // This test is like search(), but it opens a new tab after starting a search
   // in another.  In other words, it performs a search in a background tab.  The
   // search page should be loaded in the same tab that performed the search, in
   // the background tab.
   yield addTab();
-  let searchBrowser = gBrowser.selectedBrowser;
   let engine = Services.search.currentEngine;
   let data = {
     engineName: engine.name,
     searchString: "ContentSearchTest",
     healthReportKey: "ContentSearchTest",
     searchPurpose: "ContentSearchTest",
   };
   let submissionURL =
--- a/browser/modules/test/browser_UnsubmittedCrashHandler.js
+++ b/browser/modules/test/browser_UnsubmittedCrashHandler.js
@@ -501,18 +501,17 @@ add_task(function* test_shutdown_while_n
   // We'll not wait for the notification to finish its transition -
   // we'll just remove it right away.
   gNotificationBox.removeNotification(notification, true);
 
   yield waitForIgnoredReports(reportIDs);
 
   UnsubmittedCrashHandler.uninit();
   Assert.throws(() => {
-    let shutdownWhileShowing =
-      UnsubmittedCrashHandler.prefs.getBoolPref("shutdownWhileShowing");
+    UnsubmittedCrashHandler.prefs.getBoolPref("shutdownWhileShowing");
   }, "We should have noticed that the notification had closed before " +
      "uninitting.");
   UnsubmittedCrashHandler.init();
 
   clearPendingCrashReports();
 });
 
 /**
--- a/browser/modules/test/browser_UsageTelemetry_private_and_restore.js
+++ b/browser/modules/test/browser_UsageTelemetry_private_and_restore.js
@@ -63,17 +63,16 @@ add_task(function* test_sessionRestore()
         selected: 1
       }
     ]
   };
 
   // Save the current session.
   let SessionStore =
     Cu.import("resource:///modules/sessionstore/SessionStore.jsm", {}).SessionStore;
-  let backupState = SessionStore.getBrowserState();
 
   // Load the custom state and wait for SSTabRestored, as we want to make sure
   // that the URI counting code was hit.
   let tabRestored = BrowserTestUtils.waitForEvent(gBrowser.tabContainer, "SSTabRestored");
   SessionStore.setBrowserState(JSON.stringify(state));
   yield tabRestored;
 
   // Check that the URI is not recorded.
--- a/browser/modules/test/browser_taskbar_preview.js
+++ b/browser/modules/test/browser_taskbar_preview.js
@@ -92,13 +92,9 @@ function test() {
 
   function getPreviewForTab(tab) {
     return window.gTaskbarTabGroup.previewFromTab(tab);
   }
 
   function checkSelectedTab() {
     return getPreviewForTab(gBrowser.selectedTab).active;
   }
-
-  function isTabSelected(idx) {
-    return gBrowser.tabs[idx].selected;
-  }
 }
--- a/browser/modules/test/xpcshell/test_DirectoryLinksProvider.js
+++ b/browser/modules/test/xpcshell/test_DirectoryLinksProvider.js
@@ -475,17 +475,17 @@ add_task(function* test_topSitesWithSugg
 
   // We start off with no top sites with suggested links.
   do_check_eq(DirectoryLinksProvider._topSitesWithSuggestedLinks.size, 0);
 
   let data = {"suggested": [suggestedTile1, suggestedTile2, suggestedTile3], "directory": [someOtherSite]};
   let dataURI = 'data:application/json,' + JSON.stringify(data);
 
   yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
-  let links = yield fetchData();
+  yield fetchData();
 
   // Check we've populated suggested links as expected.
   do_check_eq(DirectoryLinksProvider._suggestedLinks.size, 5);
 
   // When many sites change, we update _topSitesWithSuggestedLinks as expected.
   let expectedTopSitesWithSuggestedLinks = ["hrblock.com", "1040.com", "freetaxusa.com"];
   DirectoryLinksProvider._handleManyLinksChanged();
   isIdentical([...DirectoryLinksProvider._topSitesWithSuggestedLinks], expectedTopSitesWithSuggestedLinks);
@@ -1604,17 +1604,17 @@ add_task(function test_DirectoryLinksPro
 
 add_task(function* test_sanitizeExplanation() {
   // Note: this is a basic test to ensure we applied sanitization to the link explanation.
   // Full testing for appropriate sanitization is done in parser/xml/test/unit/test_sanitizer.js.
   let data = {"suggested": [suggestedTile5]};
   let dataURI = 'data:application/json,' + encodeURIComponent(JSON.stringify(data));
 
   yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
-  let links = yield fetchData();
+  yield fetchData();
 
   let suggestedSites = [...DirectoryLinksProvider._suggestedLinks.keys()];
   do_check_eq(suggestedSites.indexOf("eviltarget.com"), 0);
   do_check_eq(suggestedSites.length, 1);
 
   let suggestedLink = [...DirectoryLinksProvider._suggestedLinks.get(suggestedSites[0]).values()][0];
   do_check_eq(suggestedLink.explanation, "This is an evil tile X muhahaha");
   do_check_eq(suggestedLink.targetedName, "WE ARE EVIL ");
@@ -1791,17 +1791,16 @@ add_task(function* test_inadjecentSites(
   NewTabUtils.isTopPlacesSite = origIsTopPlacesSite;
   NewTabUtils.getProviderLinks = origGetProviderLinks;
   DirectoryLinksProvider._getCurrentTopSiteCount = origCurrentTopSiteCount;
   yield promiseCleanDirectoryLinksProvider();
 });
 
 add_task(function* test_blockSuggestedTiles() {
   // Initial setup
-  let suggestedTile = suggestedTile1;
   let topSites = ["site0.com", "1040.com", "site2.com", "hrblock.com", "site4.com", "freetaxusa.com", "site6.com"];
   let data = {"suggested": [suggestedTile1, suggestedTile2, suggestedTile3], "directory": [someOtherSite]};
   let dataURI = 'data:application/json,' + JSON.stringify(data);
 
   yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
   let links = yield fetchData();
 
   let origIsTopPlacesSite = NewTabUtils.isTopPlacesSite;
--- a/build/mozconfig.cache
+++ b/build/mozconfig.cache
@@ -24,17 +24,17 @@ if test -z "$SCCACHE_DISABLE" -a -z "$no
         *use1.mozilla.com*)
             bucket=mozilla-releng-s3-cache-us-east-1-try
             ;;
         *usw2.mozilla.com*)
             bucket=mozilla-releng-s3-cache-us-west-2-try
             ;;
         esac
         ;;
-    mozilla-inbound|fx-team)
+    autoland|mozilla-inbound)
         case "${master}" in
         *use1.mozilla.com*)
             bucket=mozilla-releng-s3-cache-us-east-1-prod
             ;;
         *usw2.mozilla.com*)
             bucket=mozilla-releng-s3-cache-us-west-2-prod
             ;;
         esac
@@ -55,17 +55,17 @@ elif test -z "$CCACHE_DIR" -a -z "$SCCAC
         else
             # region is az with last letter trimmed
             region=${availability_zone%?}
             # set S3 bucket according to tree (level)
             case "${GECKO_HEAD_REPOSITORY}" in
             *hg.mozilla.org/try*)
                 bucket=taskcluster-level-1-sccache-${region}
                 ;;
-            *hg.mozilla.org/integration/mozilla-inbound*|*hg.mozilla.org/integration/fx-team*)
+            *hg.mozilla.org/integration/autoland*|*hg.mozilla.org/integration/mozilla-inbound*)
                 bucket=taskcluster-level-3-sccache-${region}
                 ;;
             esac
 
             # set a dummy master
             case "${region}" in
             eu-central-1)
                 master=dummy.euc1.mozilla.com
--- a/config/recurse.mk
+++ b/config/recurse.mk
@@ -167,11 +167,14 @@ endif
 ifdef MOZ_LDAP_XPCOM
 ldap/target: config/external/nss/target mozglue/build/target
 toolkit/library/target: ldap/target
 endif
 ifeq ($(MOZ_REPLACE_MALLOC_LINKAGE),dummy library)
 mozglue/build/target memory/replace/logalloc/replay/target: memory/replace/dummy/target
 endif
 endif
+ifeq (,$(MOZ_SYSTEM_NSS)$(MOZ_FOLD_LIBS))
+config/external/nss/target: config/external/nspr/pr/target config/external/nspr/ds/target config/external/nspr/libc/target
+endif
 # Most things are built during compile (target/host), but some things happen during export
 # Those need to depend on config/export for system wrappers.
 $(addprefix build/unix/stdc++compat/,target host) build/clang-plugin/target: config/export
--- a/db/sqlite3/src/moz.build
+++ b/db/sqlite3/src/moz.build
@@ -75,14 +75,18 @@ if CONFIG['OS_TARGET'] == 'Android':
     DEFINES['SQLITE_DEFAULT_FILE_PERMISSIONS'] = '0600'
 
 # Force using malloc_usable_size when building with jemalloc because _msize
 # causes assertions on Win64. See bug 719579.
 if CONFIG['OS_ARCH'] == 'WINNT' and CONFIG['MOZ_MEMORY']:
     DEFINES['HAVE_MALLOC_USABLE_SIZE'] = True
     DEFINES['SQLITE_WITHOUT_MSIZE'] = True
 
+# Omit unused functions to save some library footprint.
+DEFINES['SQLITE_OMIT_DEPRECATED'] = True
+DEFINES['SQLITE_OMIT_BUILTIN_TEST'] = True
+
 # Suppress warnings in third-party code.
 if CONFIG['GNU_CC']:
     CFLAGS += [
         '-Wno-sign-compare',
         '-Wno-type-limits',
     ]
--- a/db/sqlite3/src/sqlite.symbols
+++ b/db/sqlite3/src/sqlite.symbols
@@ -1,14 +1,13 @@
 # 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/.
 
 sqlite3_aggregate_context
-sqlite3_aggregate_count
 sqlite3_auto_extension
 sqlite3_bind_blob
 sqlite3_bind_double
 sqlite3_bind_int
 sqlite3_bind_int64
 sqlite3_bind_null
 sqlite3_bind_parameter_count
 sqlite3_bind_parameter_index
@@ -54,34 +53,32 @@ sqlite3_db_mutex
 sqlite3_db_status
 sqlite3_declare_vtab
 sqlite3_enable_load_extension
 sqlite3_enable_shared_cache
 sqlite3_errcode
 sqlite3_errmsg
 sqlite3_errmsg16
 sqlite3_exec
-sqlite3_expired
+sqlite3_expanded_sql
 sqlite3_extended_result_codes
 sqlite3_file_control
 sqlite3_finalize
 sqlite3_free
 sqlite3_free_table
 sqlite3_get_autocommit
 sqlite3_get_auxdata
 sqlite3_get_table
-sqlite3_global_recover
 sqlite3_initialize
 sqlite3_interrupt
 sqlite3_last_insert_rowid
 sqlite3_libversion
 sqlite3_libversion_number
 sqlite3_load_extension
 sqlite3_malloc
-sqlite3_memory_alarm
 sqlite3_memory_highwater
 sqlite3_memory_used
 sqlite3_mutex_alloc
 sqlite3_mutex_enter
 sqlite3_mutex_free
 sqlite3_mutex_leave
 sqlite3_mutex_try
 sqlite3_mprintf
@@ -89,17 +86,16 @@ sqlite3_next_stmt
 sqlite3_open
 sqlite3_open_v2
 sqlite3_open16
 sqlite3_overload_function
 sqlite3_prepare
 sqlite3_prepare16
 sqlite3_prepare16_v2
 sqlite3_prepare_v2
-sqlite3_profile
 sqlite3_progress_handler
 sqlite3_realloc
 sqlite3_release_memory
 sqlite3_reset
 sqlite3_reset_auto_extension
 sqlite3_result_blob
 sqlite3_result_double
 sqlite3_result_error
@@ -123,20 +119,18 @@ sqlite3_snprintf
 sqlite3_sql
 sqlite3_status
 sqlite3_step
 sqlite3_stmt_readonly
 sqlite3_stmt_status
 #ifdef XP_UNIX
 sqlite3_temp_directory
 #endif
-sqlite3_thread_cleanup
 sqlite3_total_changes
-sqlite3_trace
-sqlite3_transfer_bindings
+sqlite3_trace_v2
 sqlite3_unlock_notify
 sqlite3_update_hook
 sqlite3_uri_parameter
 sqlite3_user_data
 sqlite3_value_blob
 sqlite3_value_bytes
 sqlite3_value_bytes16
 sqlite3_value_double
--- a/devtools/client/inspector/inspector-search.js
+++ b/devtools/client/inspector/inspector-search.js
@@ -107,21 +107,19 @@ InspectorSearch.prototype = {
       this.searchBox.classList.add("devtools-style-searchbox-no-match");
       this.emit("search-result");
     }
   }),
 
   _onInput: function () {
     if (this.searchBox.value.length === 0) {
       this.searchClearButton.hidden = true;
-      this.searchBox.removeAttribute("filled");
       this._onSearch();
     } else {
       this.searchClearButton.hidden = false;
-      this.searchBox.setAttribute("filled", true);
     }
   },
 
   _onKeyDown: function (event) {
     if (event.keyCode === KeyCodes.DOM_VK_RETURN) {
       this._onSearch(event.shiftKey);
     }
 
--- a/devtools/client/netmonitor/netmonitor.xul
+++ b/devtools/client/netmonitor/netmonitor.xul
@@ -27,18 +27,16 @@
         <html:div xmlns="http://www.w3.org/1999/xhtml"
                   id="react-filter-buttons-hook"/>
         <spacer id="requests-menu-spacer"
                 flex="1"/>
         <toolbarbutton id="requests-menu-network-summary-button"
                        class="devtools-toolbarbutton icon-and-text"
                        data-localization="tooltiptext=netmonitor.toolbar.perf"/>
         <html:div xmlns="http://www.w3.org/1999/xhtml"
-                  id="react-details-pane-toggle-hook"/>
-        <html:div xmlns="http://www.w3.org/1999/xhtml"
                   id="react-search-box-hook"/>
         <html:div xmlns="http://www.w3.org/1999/xhtml"
                   id="react-details-pane-toggle-hook"/>
       </hbox>
       <hbox id="network-table-and-sidebar"
             class="devtools-responsive-container"
             flex="1">
         <vbox id="network-table" flex="1" class="devtools-main-content">
@@ -142,17 +140,17 @@
                         data-key="waterfall"
                         pack="start"
                         data-localization="label=netmonitor.toolbar.waterfall"
                         flex="1">
                   <image id="requests-menu-waterfall-image"/>
                   <box id="requests-menu-waterfall-label-wrapper">
                     <label id="requests-menu-waterfall-label"
                            class="plain requests-menu-waterfall"
-                           data-localization="label=netmonitor.toolbar.waterfall"/>
+                           data-localization="value=netmonitor.toolbar.waterfall"/>
                   </box>
                 </button>
               </hbox>
             </hbox>
           </toolbar>
 
           <vbox id="requests-menu-empty-notice"
                 class="side-menu-widget-empty-text">
--- a/devtools/client/preferences/devtools.js
+++ b/devtools/client/preferences/devtools.js
@@ -357,15 +357,10 @@ pref("devtools.telemetry.tools.opened.ve
 // Enable the JSON View tool (an inspector for application/json documents) on
 // Nightly and Dev. Edition.
 #ifdef RELEASE_OR_BETA
 pref("devtools.jsonview.enabled", false);
 #else
 pref("devtools.jsonview.enabled", true);
 #endif
 
-// Enable the HTML responsive design tool in Nightly only.  Disabled by default for all
-// other channels.
-#ifdef NIGHTLY_BUILD
+// Enable the HTML responsive design mode for all channels.
 pref("devtools.responsive.html.enabled", true);
-#else
-pref("devtools.responsive.html.enabled", false);
-#endif
--- a/devtools/client/themes/common.css
+++ b/devtools/client/themes/common.css
@@ -629,17 +629,16 @@ checkbox:-moz-focusring {
   padding-inline-end: 0;
 }
 
 .devtools-rule-searchbox {
   -moz-box-flex: 1;
   width: 100%;
 }
 
-.devtools-searchinput:-moz-any([filled],.filled),
 .devtools-filterinput:-moz-any([filled],.filled) {
   background-color: var(--searchbox-background-color);
   border-color: var(--searchbox-border-color);
 }
 
 .devtools-style-searchbox-no-match {
   background-color: var(--searcbox-no-match-background-color) !important;
   border-color: var(--searcbox-no-match-border-color) !important;
--- a/gfx/layers/apz/src/AsyncPanZoomController.cpp
+++ b/gfx/layers/apz/src/AsyncPanZoomController.cpp
@@ -828,45 +828,63 @@ AsyncPanZoomController::ArePointerEvents
   bool consumable = (aTouchPoints == 1 ? pannable : zoomable);
   if (!consumable) {
     return false;
   }
 
   return true;
 }
 
-template <typename T>
-static float GetAxisStart(AsyncDragMetrics::DragDirection aDir, T aValue) {
+template <typename Units>
+static CoordTyped<Units> GetAxisStart(AsyncDragMetrics::DragDirection aDir, const PointTyped<Units>& aValue) {
+  if (aDir == AsyncDragMetrics::HORIZONTAL) {
+    return aValue.x;
+  } else {
+    return aValue.y;
+  }
+}
+
+template <typename Units>
+static CoordTyped<Units> GetAxisStart(AsyncDragMetrics::DragDirection aDir, const RectTyped<Units>& aValue) {
   if (aDir == AsyncDragMetrics::HORIZONTAL) {
     return aValue.x;
   } else {
     return aValue.y;
   }
 }
 
-template <typename T>
-static float GetAxisEnd(AsyncDragMetrics::DragDirection aDir, T aValue) {
+template <typename Units>
+static IntCoordTyped<Units> GetAxisStart(AsyncDragMetrics::DragDirection aDir, const IntRectTyped<Units>& aValue) {
+  if (aDir == AsyncDragMetrics::HORIZONTAL) {
+    return aValue.x;
+  } else {
+    return aValue.y;
+  }
+}
+
+template <typename Units>
+static IntCoordTyped<Units> GetAxisEnd(AsyncDragMetrics::DragDirection aDir, const IntRectTyped<Units>& aValue) {
   if (aDir == AsyncDragMetrics::HORIZONTAL) {
     return aValue.x + aValue.width;
   } else {
     return aValue.y + aValue.height;
   }
 }
 
-template <typename T>
-static float GetAxisSize(AsyncDragMetrics::DragDirection aDir, T aValue) {
+template <typename Units>
+static CoordTyped<Units> GetAxisSize(AsyncDragMetrics::DragDirection aDir, const RectTyped<Units>& aValue) {
   if (aDir == AsyncDragMetrics::HORIZONTAL) {
     return aValue.width;
   } else {
     return aValue.height;
   }
 }
 
-template <typename T>
-static float GetAxisScale(AsyncDragMetrics::DragDirection aDir, T aValue) {
+template <typename FromUnits, typename ToUnits>
+static float GetAxisScale(AsyncDragMetrics::DragDirection aDir, const ScaleFactors2D<FromUnits, ToUnits>& aValue) {
   if (aDir == AsyncDragMetrics::HORIZONTAL) {
     return aValue.xScale;
   } else {
     return aValue.yScale;
   }
 }
 
 nsEventStatus AsyncPanZoomController::HandleDragEvent(const MouseInput& aEvent,
@@ -891,34 +909,34 @@ nsEventStatus AsyncPanZoomController::Ha
 
   ReentrantMonitorAutoEnter lock(mMonitor);
   CSSPoint scrollFramePoint = aEvent.mLocalOrigin / GetFrameMetrics().GetZoom();
   // The scrollbar can be transformed with the frame but the pres shell
   // resolution is only applied to the scroll frame.
   CSSPoint scrollbarPoint = scrollFramePoint * mFrameMetrics.GetPresShellResolution();
   CSSRect cssCompositionBound = mFrameMetrics.CalculateCompositedRectInCssPixels();
 
-  float mousePosition = GetAxisStart(aDragMetrics.mDirection, scrollbarPoint) -
-                        aDragMetrics.mScrollbarDragOffset -
+  CSSCoord mousePosition = GetAxisStart(aDragMetrics.mDirection, scrollbarPoint) -
+                        CSSCoord(aDragMetrics.mScrollbarDragOffset) -
                         GetAxisStart(aDragMetrics.mDirection, cssCompositionBound) -
-                        GetAxisStart(aDragMetrics.mDirection, aDragMetrics.mScrollTrack);
-
-  float scrollMax = GetAxisEnd(aDragMetrics.mDirection, aDragMetrics.mScrollTrack);
+                        CSSCoord(GetAxisStart(aDragMetrics.mDirection, aDragMetrics.mScrollTrack));
+
+  CSSCoord scrollMax = CSSCoord(GetAxisEnd(aDragMetrics.mDirection, aDragMetrics.mScrollTrack));
   scrollMax -= node->GetScrollSize() /
                GetAxisScale(aDragMetrics.mDirection, mFrameMetrics.GetZoom()) *
                mFrameMetrics.GetPresShellResolution();
 
   float scrollPercent = mousePosition / scrollMax;
 
-  float minScrollPosition =
+  CSSCoord minScrollPosition =
     GetAxisStart(aDragMetrics.mDirection, mFrameMetrics.GetScrollableRect().TopLeft());
-  float maxScrollPosition =
+  CSSCoord maxScrollPosition =
     GetAxisSize(aDragMetrics.mDirection, mFrameMetrics.GetScrollableRect()) -
-    GetAxisSize(aDragMetrics.mDirection, mFrameMetrics.GetCompositionBounds());
-  float scrollPosition = scrollPercent * maxScrollPosition;
+    GetAxisSize(aDragMetrics.mDirection, cssCompositionBound);
+  CSSCoord scrollPosition = scrollPercent * maxScrollPosition;
 
   scrollPosition = std::max(scrollPosition, minScrollPosition);
   scrollPosition = std::min(scrollPosition, maxScrollPosition);
 
   CSSPoint scrollOffset = mFrameMetrics.GetScrollOffset();
   if (aDragMetrics.mDirection == AsyncDragMetrics::HORIZONTAL) {
     scrollOffset.x = scrollPosition;
   } else {
--- a/layout/base/nsLayoutUtils.cpp
+++ b/layout/base/nsLayoutUtils.cpp
@@ -151,17 +151,17 @@ using namespace mozilla::gfx;
 #define FLOAT_LOGICAL_VALUES_ENABLED_PREF_NAME "layout.css.float-logical-values.enabled"
 #define BG_CLIP_TEXT_ENABLED_PREF_NAME "layout.css.background-clip-text.enabled"
 
 // The time in number of frames that we estimate for a refresh driver
 // to be quiescent
 #define DEFAULT_QUIESCENT_FRAMES 2
 // The time (milliseconds) we estimate is needed between the end of an
 // idle time and the next Tick.
-#define DEFAULT_IDLE_PERIOD_TIME_LIMIT 3.0f
+#define DEFAULT_IDLE_PERIOD_TIME_LIMIT 1.0f
 
 #ifdef DEBUG
 // TODO: remove, see bug 598468.
 bool nsLayoutUtils::gPreventAssertInCompareTreePosition = false;
 #endif // DEBUG
 
 typedef FrameMetrics::ViewID ViewID;
 typedef nsStyleTransformMatrix::TransformReferenceBox TransformReferenceBox;
--- a/modules/libpref/init/all.js
+++ b/modules/libpref/init/all.js
@@ -2688,17 +2688,17 @@ pref("layout.spammy_warnings.enabled", f
 pref("layout.float-fragments-inside-column.enabled", true);
 
 // The number of frames times the frame rate is the time required to
 // pass without painting used to guess that we'll not paint again soon
 pref("layout.idle_period.required_quiescent_frames", 2);
 
 // The amount of time (milliseconds) needed between an idle period's
 // end and the start of the next tick to avoid jank.
-pref("layout.idle_period.time_limit", 3);
+pref("layout.idle_period.time_limit", 1);
 
 // Is support for the Web Animations API enabled?
 // Before enabling this by default, make sure also CSSPseudoElement interface
 // has been spec'ed properly, or we should add a separate pref for
 // CSSPseudoElement interface. See Bug 1174575 for further details.
 #ifdef RELEASE_OR_BETA
 pref("dom.animations-api.core.enabled", false);
 #else
@@ -2745,16 +2745,24 @@ pref("dom.global_stop_script", true);
 pref("dom.archivereader.enabled", false);
 
 // Time (milliseconds) between throttled idle callbacks.
 pref("dom.idle_period.throttled_length", 10000);
 
 // The amount of idle time (milliseconds) reserved for a long idle period
 pref("idle_queue.long_period", 50);
 
+// The minimum amount of time (milliseconds) required for an idle
+// period to be scheduled on the main thread. N.B. that
+// layout.idle_period.time_limit adds padding at the end of the idle
+// period, which makes the point in time that we expect to become busy
+// again be:
+// now + idle_queue.min_period + layout.idle_period.time_limit
+pref("idle_queue.min_period", 3);
+
 // Hang monitor timeout after which we kill the browser, in seconds
 // (0 is disabled)
 // Disabled on all platforms per bug 705748 until the found issues are
 // resolved.
 pref("hangmonitor.timeout", 0);
 
 pref("plugins.load_appdir_plugins", false);
 // If true, plugins will be click to play
--- a/mozglue/build/SSE.cpp
+++ b/mozglue/build/SSE.cpp
@@ -2,28 +2,33 @@
 /* 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/. */
 
 /* compile-time and runtime tests for whether to use SSE instructions */
 
 #include "SSE.h"
 
+#ifdef HAVE_CPUID_H
+// cpuid.h is available on gcc 4.3 and higher on i386 and x86_64
+#include <cpuid.h>
+#elif defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_AMD64))
+// MSVC 2005 or newer on x86-32 or x86-64
+#include <intrin.h>
+#endif
+
 namespace {
 
 // SSE.h has parallel #ifs which declare MOZILLA_SSE_HAVE_CPUID_DETECTION.
 // We can't declare these functions in the header file, however, because
 // <intrin.h> conflicts with <windows.h> on MSVC 2005, and some files want to
 // include both SSE.h and <windows.h>.
 
 #ifdef HAVE_CPUID_H
 
-// cpuid.h is available on gcc 4.3 and higher on i386 and x86_64
-#include <cpuid.h>
-
 enum CPUIDRegister { eax = 0, ebx = 1, ecx = 2, edx = 3 };
 
 static bool
 has_cpuid_bits(unsigned int level, CPUIDRegister reg, unsigned int bits)
 {
   unsigned int regs[4];
   unsigned int eax, ebx, ecx, edx;
   unsigned max = __get_cpuid_max(0, NULL);
@@ -40,19 +45,16 @@ has_cpuid_bits(unsigned int level, CPUID
 static uint64_t xgetbv(uint32_t xcr) {
     uint32_t eax, edx;
     __asm__ ( ".byte 0x0f, 0x01, 0xd0" : "=a"(eax), "=d"(edx) : "c"(xcr));
     return (uint64_t)(edx) << 32 | eax;
 }
 
 #elif defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_AMD64))
 
-// MSVC 2005 or newer on x86-32 or x86-64
-#include <intrin.h>
-
 enum CPUIDRegister { eax = 0, ebx = 1, ecx = 2, edx = 3 };
 
 static bool
 has_cpuid_bits(unsigned int level, CPUIDRegister reg, unsigned int bits)
 {
   // Check that the level in question is supported.
   int regs[4];
   __cpuid(regs, level & 0x80000000u);
--- a/security/manager/ssl/tests/mochitest/stricttransportsecurity/test_sts_privatebrowsing_perwindowpb.html
+++ b/security/manager/ssl/tests/mochitest/stricttransportsecurity/test_sts_privatebrowsing_perwindowpb.html
@@ -92,20 +92,20 @@
   function startRound(win, isPrivate, round) {
     currentround = round;
     testsleftinround = NUM_TEST_FRAMES;
     SimpleTest.info("TESTS LEFT IN ROUND " + currentround + ": " + testsleftinround);
 
     let browser = win.gBrowser.selectedBrowser;
     let src = "https://example.com" + STSPATH + "/" + round + "_bootstrap.html";
 
-    ContentTask.spawn(browser, src, function* (src) {
+    ContentTask.spawn(browser, src, function* (contentSrc) {
       let frame = content.document.createElement("iframe");
       frame.setAttribute('id', 'ifr_bootstrap');
-      frame.setAttribute('src', src);
+      frame.setAttribute('src', contentSrc);
 
       return new Promise(resolve => {
         frame.addEventListener("load", resolve);
         content.document.body.appendChild(frame);
       });
     }).then(() => {
       onMessageReceived(win, isPrivate, "BOOTSTRAP " + round);
     });
@@ -121,20 +121,20 @@
     });
   }
 
   function loadVerifyFrame(win, isPrivate, test, testName, aCallback) {
     let id = 'ifr_' + testName;
     let src = test.url + '?id=' + testName;
     let browser = win.gBrowser.selectedBrowser;
 
-    ContentTask.spawn(browser, [id, src], function* ([id, src]) {
+    ContentTask.spawn(browser, [id, src], function* ([contentId, contentSrc]) {
       let frame = content.document.createElement("iframe");
-      frame.setAttribute('id', id);
-      frame.setAttribute('src', src);
+      frame.setAttribute('id', contentId);
+      frame.setAttribute('src', contentSrc);
 
       return new Promise(resolve => {
         frame.addEventListener("load", () => {
           resolve(frame.contentDocument.location.protocol);
         });
 
         content.document.body.appendChild(frame);
       });
@@ -177,20 +177,20 @@
                              ", test " + result[1]);
     testsleftinround--;
 
     // if this round is complete...
     if (testsleftinround < 1) {
       SimpleTest.info("DONE WITH ROUND " + currentround);
       // remove all the iframes in the document
       let browser = win.gBrowser.selectedBrowser;
-      ContentTask.spawn(browser, testframes, function* (testframes) {
+      ContentTask.spawn(browser, testframes, function* (contentTestFrames) {
         content.document.body.removeChild(
           content.document.getElementById('ifr_bootstrap'));
-        for (let test in testframes) {
+        for (let test in contentTestFrames) {
           content.document.body.removeChild(
             content.document.getElementById('ifr_' + test));
         }
       }).then(() => {
         currentround = "";
 
         if (!isPrivate) {
           clean_up_sts_state(isPrivate);
--- a/storage/mozStorageConnection.cpp
+++ b/storage/mozStorageConnection.cpp
@@ -189,20 +189,49 @@ struct Module
 
 Module gModules[] = {
   { "filesystem", RegisterFileSystemModule }
 };
 
 ////////////////////////////////////////////////////////////////////////////////
 //// Local Functions
 
-void tracefunc (void *aClosure, const char *aStmt)
+int tracefunc (unsigned aReason, void *aClosure, void *aP, void *aX)
 {
-  MOZ_LOG(gStorageLog, LogLevel::Debug, ("sqlite3_trace on %p for '%s'", aClosure,
-                                     aStmt));
+  switch (aReason) {
+    case SQLITE_TRACE_STMT: {
+      // aP is a pointer to the prepared statement.
+      sqlite3_stmt* stmt = static_cast<sqlite3_stmt*>(aP);
+      // aX is a pointer to a string containing the unexpanded SQL or a comment,
+      // starting with "--"" in case of a trigger.
+      char* expanded = static_cast<char*>(aX);
+      // Simulate what sqlite_trace was doing.
+      if (!::strncmp(expanded, "--", 2)) {
+        MOZ_LOG(gStorageLog, LogLevel::Debug,
+          ("TRACE_STMT on %p: '%s'", aClosure, expanded));
+      } else {
+        char* sql = ::sqlite3_expanded_sql(stmt);
+        MOZ_LOG(gStorageLog, LogLevel::Debug,
+          ("TRACE_STMT on %p: '%s'", aClosure, sql));
+        ::sqlite3_free(sql);
+      }
+      break;
+    }
+    case SQLITE_TRACE_PROFILE: {
+      // aX is pointer to a 64bit integer containing nanoseconds it took to
+      // execute the last command.
+      sqlite_int64 time = *(static_cast<sqlite_int64*>(aX)) / 1000000;
+      if (time > 0) {
+        MOZ_LOG(gStorageLog, LogLevel::Debug,
+          ("TRACE_TIME on %p: %dms", aClosure, time));
+      }
+      break;
+    }
+  }
+  return 0;
 }
 
 void
 basicFunctionHelper(sqlite3_context *aCtx,
                     int aArgc,
                     sqlite3_value **aArgv)
 {
   void *userData = ::sqlite3_user_data(aCtx);
@@ -696,17 +725,19 @@ Connection::initializeInternal()
   }
 
   // Properly wrap the database handle's mutex.
   sharedDBMutex.initWithMutex(sqlite3_db_mutex(mDBConn));
 
   // SQLite tracing can slow down queries (especially long queries)
   // significantly. Don't trace unless the user is actively monitoring SQLite.
   if (MOZ_LOG_TEST(gStorageLog, LogLevel::Debug)) {
-    ::sqlite3_trace(mDBConn, tracefunc, this);
+    ::sqlite3_trace_v2(mDBConn,
+                       SQLITE_TRACE_STMT | SQLITE_TRACE_PROFILE,
+                       tracefunc, this);
 
     MOZ_LOG(gStorageLog, LogLevel::Debug, ("Opening connection to '%s' (%p)",
                                         mTelemetryFilename.get(), this));
   }
 
   int64_t pageSize = Service::getDefaultPageSize();
 
   // Set page_size to the preferred default value.  This is effective only if
--- a/storage/mozStorageService.cpp
+++ b/storage/mozStorageService.cpp
@@ -151,17 +151,17 @@ Service::CollectReports(nsIHandleReportC
                  NS_LITERAL_CSTRING("stmt"), stmtDesc,
                  SQLITE_DBSTATUS_STMT_USED, &totalConnSize);
 
       NS_NAMED_LITERAL_CSTRING(cacheDesc,
         "Memory (approximate) used by all pager caches used by connections "
         "to this database.");
       ReportConn(aHandleReport, aData, conn, pathHead,
                  NS_LITERAL_CSTRING("cache"), cacheDesc,
-                 SQLITE_DBSTATUS_CACHE_USED, &totalConnSize);
+                 SQLITE_DBSTATUS_CACHE_USED_SHARED, &totalConnSize);
 
       NS_NAMED_LITERAL_CSTRING(schemaDesc,
         "Memory (approximate) used to store the schema for all databases "
         "associated with connections to this database.");
       ReportConn(aHandleReport, aData, conn, pathHead,
                  NS_LITERAL_CSTRING("schema"), schemaDesc,
                  SQLITE_DBSTATUS_SCHEMA_USED, &totalConnSize);
     }
--- a/testing/firefox-ui/harness/firefox_ui_harness/testcases.py
+++ b/testing/firefox-ui/harness/firefox_ui_harness/testcases.py
@@ -257,17 +257,17 @@ class UpdateTestCase(FirefoxTestCase):
                                                              ]),
                                                     message='Final wizard page has been selected.')
 
                 else:
                     raise Exception('Invalid wizard page for downloading an update: {}'.format(
                                     dialog.wizard.selected_panel))
 
             finally:
-                prefs.restore_pref(self.PREF_APP_UPDATE_ALTWINDOWTYPE)
+                self.marionette.clear_pref(self.PREF_APP_UPDATE_ALTWINDOWTYPE)
 
         # The old update wizard dialog has to be handled differently. It's necessary
         # for fallback updates and invalid add-on versions.
         if isinstance(window, UpdateWizardDialog):
             download_via_update_wizard(window)
             return
 
         if window.deck.selected_panel == window.deck.download_and_install:
--- a/testing/mochitest/mochitest.eslintrc.js
+++ b/testing/mochitest/mochitest.eslintrc.js
@@ -1,13 +1,14 @@
 // Parent config file for all mochitest files.
 module.exports = {
   rules: {
     "mozilla/import-headjs-globals": 1,
     "mozilla/mark-test-function-used": 1,
+    "no-shadow": 2,
   },
 
   "env": {
     "browser": true,
   },
 
   // All globals made available in the test environment.
   "globals": {
--- a/testing/mozharness/mozharness/base/python.py
+++ b/testing/mozharness/mozharness/base/python.py
@@ -6,28 +6,26 @@
 # ***** END LICENSE BLOCK *****
 '''Python usage, esp. virtualenv.
 '''
 
 import distutils.version
 import os
 import subprocess
 import sys
-import time
 import json
 import socket
 import traceback
 import urlparse
 
 import mozharness
 from mozharness.base.script import (
     PostScriptAction,
     PostScriptRun,
     PreScriptAction,
-    PreScriptRun,
 )
 from mozharness.base.errors import VirtualenvErrorList
 from mozharness.base.log import WARNING, FATAL
 from mozharness.mozilla.proxxy import Proxxy
 
 external_tools_path = os.path.join(
     os.path.abspath(os.path.dirname(os.path.dirname(mozharness.__file__))),
     'external_tools',
@@ -752,228 +750,14 @@ class ResourceMonitoringMixin(object):
             start_time, end_time = rm.phases[phase]
             cpu_percent, cpu_times, io, swap = resources(phase)
             log_usage(phase, end_time - start_time, cpu_percent, cpu_times, io)
 
     def _tinderbox_print(self, message):
         self.info('TinderboxPrint: %s' % message)
 
 
-class InfluxRecordingMixin(object):
-    """Provides InfluxDB stat recording to scripts.
-
-    This class records stats to an InfluxDB server, if enabled. Stat recording
-    is enabled in a script by inheriting from this class, and adding an
-    influxdb_credentials line to the influx_credentials_file (usually oauth.txt
-    in automation).  This line should look something like:
-
-        influxdb_credentials = 'http://goldiewilson-onepointtwentyone-1.c.influxdb.com:8086/db/DBNAME/series?u=DBUSERNAME&p=DBPASSWORD'
-
-    Where DBNAME, DBUSERNAME, and DBPASSWORD correspond to the database name,
-    and user/pw credentials for recording to the database. The stats from
-    mozharness are recorded in the 'mozharness' table.
-    """
-
-    @PreScriptRun
-    def influxdb_recording_init(self):
-        self.recording = False
-        self.post = None
-        self.posturl = None
-        self.build_metrics_summary = None
-        self.res_props = self.config.get('build_resources_path') % self.query_abs_dirs()
-        self.info("build_resources.json path: %s" % self.res_props)
-        if self.res_props:
-            self.rmtree(self.res_props)
-
-        try:
-            site_packages_path = self.query_python_site_packages_path()
-            if site_packages_path not in sys.path:
-                sys.path.append(site_packages_path)
-
-            self.post = get_tlsv1_post()
-
-            auth = os.path.join(os.getcwd(), self.config['influx_credentials_file'])
-            if not os.path.exists(auth):
-                self.warning("Unable to start influxdb recording: %s not found" % (auth,))
-                return
-            credentials = {}
-            execfile(auth, credentials)
-            if 'influxdb_credentials' in credentials:
-                self.posturl = credentials['influxdb_credentials']
-                self.recording = True
-            else:
-                self.warning("Unable to start influxdb recording: no credentials")
-                return
-
-        except Exception:
-            # The exact reason for failing to start stats doesn't really matter.
-            # If anything fails, we just won't record stats for this job.
-            self.warning("Unable to start influxdb recording: %s" %
-                         traceback.format_exc())
-            return
-
-    @PreScriptAction
-    def influxdb_recording_pre_action(self, action):
-        if not self.recording:
-            return
-
-        self.start_time = time.time()
-
-    @PostScriptAction
-    def influxdb_recording_post_action(self, action, success=None):
-        if not self.recording:
-            return
-
-        elapsed_time = time.time() - self.start_time
-
-        c = {}
-        p = {}
-        if self.buildbot_config:
-            c = self.buildbot_config.get('properties', {})
-        if self.buildbot_properties:
-            p = self.buildbot_properties
-        self.record_influx_stat([{
-            "points": [[
-                action,
-                elapsed_time,
-                c.get('buildername'),
-                c.get('product'),
-                c.get('platform'),
-                c.get('branch'),
-                c.get('slavename'),
-                c.get('revision'),
-                p.get('gaia_revision'),
-                c.get('buildid'),
-            ]],
-            "name": "mozharness",
-            "columns": [
-                "action",
-                "runtime",
-                "buildername",
-                "product",
-                "platform",
-                "branch",
-                "slavename",
-                "gecko_revision",
-                "gaia_revision",
-                "buildid",
-            ],
-        }])
-
-    def _get_resource_usage(self, res, name, iolen, cpulen):
-        c = {}
-        p = {}
-        if self.buildbot_config:
-            c = self.buildbot_config.get('properties', {})
-        if self.buildbot_properties:
-            p = self.buildbot_properties
-
-        data = [
-            # Build properties
-            c.get('buildername'),
-            c.get('product'),
-            c.get('platform'),
-            c.get('branch'),
-            c.get('slavename'),
-            c.get('revision'),
-            p.get('gaia_revision'),
-            c.get('buildid'),
-
-            # Mach step properties
-            name,
-            res.get('start'),
-            res.get('end'),
-            res.get('duration'),
-            res.get('cpu_percent'),
-        ]
-        # The io and cpu_times fields are arrays, though they aren't always
-        # present if a step completes before resource utilization is measured.
-        # We add the arrays if they exist, otherwise we just do an array of None
-        # to fill up the stat point.
-        data.extend(res.get('io', [None] * iolen))
-        data.extend(res.get('cpu_times', [None] * cpulen))
-        return data
-
-    @PostScriptAction('build')
-    def record_mach_stats(self, action, success=None):
-        if not os.path.exists(self.res_props):
-            self.info('No build_resources.json found, not logging stats')
-            return
-        with open(self.res_props) as fh:
-            resources = json.load(fh)
-            data = {
-                "points": [
-                ],
-                "name": "mach",
-                "columns": [
-                    # Build properties
-                    "buildername",
-                    "product",
-                    "platform",
-                    "branch",
-                    "slavename",
-                    "gecko_revision",
-                    "gaia_revision",
-                    "buildid",
-
-                    # Mach step properties
-                    "name",
-                    "start",
-                    "end",
-                    "duration",
-                    "cpu_percent",
-                ],
-            }
-
-            # The io and cpu_times fields aren't static - they may vary based
-            # on the specific platform being measured. Mach records the field
-            # names, which we use as the column names here.
-            data['columns'].extend(resources['io_fields'])
-            data['columns'].extend(resources['cpu_times_fields'])
-            iolen = len(resources['io_fields'])
-            cpulen = len(resources['cpu_times_fields'])
-
-            if 'duration' in resources:
-                self.build_metrics_summary = {
-                    'name': 'build times',
-                    'value': resources['duration'],
-                    'subtests': [],
-                }
-
-            # The top-level data has the overall resource usage, which we record
-            # under the name 'TOTAL' to separate it from the individual phases.
-            data['points'].append(self._get_resource_usage(resources, 'TOTAL', iolen, cpulen))
-
-            # Each phases also has the same resource stats as the top-level.
-            for phase in resources['phases']:
-                data['points'].append(self._get_resource_usage(phase, phase['name'], iolen, cpulen))
-                if 'duration' not in phase:
-                    self.build_metrics_summary = None
-                elif self.build_metrics_summary:
-                    self.build_metrics_summary['subtests'].append({
-                        'name': phase['name'],
-                        'value': phase['duration'],
-                    })
-
-            self.record_influx_stat([data])
-
-    def record_influx_stat(self, json_data):
-        if not self.recording:
-            return
-        try:
-            r = self.post(self.posturl, data=json.dumps(json_data), timeout=5)
-            if r.status_code != 200:
-                self.warning("Failed to log stats. Return code = %i, stats = %s" % (r.status_code, json_data))
-
-                # Disable recording for the rest of this job. Even if it's just
-                # intermittent, we don't want to keep the build from progressing.
-                self.recording = False
-        except Exception, e:
-            self.warning('Failed to log stats. Exception = %s' % str(e))
-            self.recording = False
-
-
 # __main__ {{{1
 
 if __name__ == '__main__':
     '''TODO: unit tests.
     '''
     pass
--- a/testing/mozharness/mozharness/mozilla/building/buildbase.py
+++ b/testing/mozharness/mozharness/mozilla/building/buildbase.py
@@ -46,17 +46,16 @@ from mozharness.mozilla.mock import Mock
 from mozharness.mozilla.secrets import SecretsMixin
 from mozharness.mozilla.signing import SigningMixin
 from mozharness.mozilla.mock import ERROR_MSGS as MOCK_ERROR_MSGS
 from mozharness.mozilla.testing.errors import TinderBoxPrintRe
 from mozharness.mozilla.testing.unittest import tbox_print_summary
 from mozharness.mozilla.updates.balrog import BalrogMixin
 from mozharness.mozilla.taskcluster_helper import Taskcluster
 from mozharness.base.python import VirtualenvMixin
-from mozharness.base.python import InfluxRecordingMixin
 
 AUTOMATION_EXIT_CODES = EXIT_STATUS_DICT.values()
 AUTOMATION_EXIT_CODES.sort()
 
 MISSING_CFG_KEY_MSG = "The key '%s' could not be determined \
 Please add this to your config."
 
 ERROR_MSGS = {
@@ -583,17 +582,17 @@ def generate_build_ID():
 
 
 def generate_build_UID():
     return uuid.uuid4().hex
 
 
 class BuildScript(BuildbotMixin, PurgeMixin, MockMixin, BalrogMixin,
                   SigningMixin, VirtualenvMixin, MercurialScript,
-                  InfluxRecordingMixin, SecretsMixin):
+                  SecretsMixin):
     def __init__(self, **kwargs):
         # objdir is referenced in _query_abs_dirs() so let's make sure we
         # have that attribute before calling BaseScript.__init__
         self.objdir = None
         super(BuildScript, self).__init__(**kwargs)
         # epoch is only here to represent the start of the buildbot build
         # that this mozharn script came from. until I can grab bbot's
         # status.build.gettime()[0] this will have to do as a rough estimate
@@ -903,25 +902,25 @@ or run without that action (ie: --no-{ac
 
     def query_mach_build_env(self, multiLocale=None):
         c = self.config
         if multiLocale is None and self.query_is_nightly():
             multiLocale = c.get('multi_locale', False)
         mach_env = {}
         if c.get('upload_env'):
             mach_env.update(c['upload_env'])
-            if 'UPLOAD_HOST' in mach_env:
+            if 'UPLOAD_HOST' in mach_env and 'stage_server' in c:
                 mach_env['UPLOAD_HOST'] = mach_env['UPLOAD_HOST'] % {
                     'stage_server': c['stage_server']
                 }
-            if 'UPLOAD_USER' in mach_env:
+            if 'UPLOAD_USER' in mach_env and 'stage_username' in c:
                 mach_env['UPLOAD_USER'] = mach_env['UPLOAD_USER'] % {
                     'stage_username': c['stage_username']
                 }
-            if 'UPLOAD_SSH_KEY' in mach_env:
+            if 'UPLOAD_SSH_KEY' in mach_env and 'stage_ssh_key' in c:
                 mach_env['UPLOAD_SSH_KEY'] = mach_env['UPLOAD_SSH_KEY'] % {
                     'stage_ssh_key': c['stage_ssh_key']
                 }
 
         if self.query_is_nightly():
             mach_env['LATEST_MAR_DIR'] = c['latest_mar_dir'] % {
                 'branch': self.branch
             }
--- a/testing/mozharness/scripts/fx_desktop_build.py
+++ b/testing/mozharness/scripts/fx_desktop_build.py
@@ -71,17 +71,16 @@ class FxDesktopBuild(BuildScript, TryToo
                     "%(objdir)s/dist/fennec*",
                     "%(objdir)s/dist/seamonkey*",
                     "%(objdir)s/dist/thunderbird*",
                     "%(objdir)s/dist/install/sea/*.exe"
                 ],
                 'stage_product': 'firefox',
                 'platform_supports_post_upload_to_latest': True,
                 'latest_mar_dir': '/pub/mozilla.org/firefox/nightly/latest-%(branch)s',
-                'influx_credentials_file': 'oauth.txt',
                 'build_resources_path': '%(abs_src_dir)s/obj-firefox/.mozbuild/build_resources.json',
                 'nightly_promotion_branches': ['mozilla-central', 'mozilla-aurora'],
 
                 # try will overwrite these
                 'clone_with_purge': False,
                 'clone_by_revision': False,
                 'tinderbox_build_dir': None,
                 'to_tinderbox_dated': True,
--- a/toolkit/components/alerts/test/test_alerts_noobserve.html
+++ b/toolkit/components/alerts/test/test_alerts_noobserve.html
@@ -18,17 +18,17 @@
 
 <pre id="test">
 <script class="testbody" type="text/javascript">
 
 const Cc = SpecialPowers.Cc;
 const Ci = SpecialPowers.Ci;
 
 const chromeScript = SpecialPowers.loadChromeScript(_ => {
-  const { classes: Cc, interfaces: Ci, utils: Cu } = Components;
+  const { utils: Cu } = Components;
 
   Cu.import("resource://gre/modules/Services.jsm");
   Cu.import("resource://gre/modules/Timer.jsm");
 
   function anyXULAlertsVisible() {
     var windows = Services.wm.getEnumerator("alert:alert");
     return windows.hasMoreElements();
   }
--- a/toolkit/components/alerts/test/test_alerts_requireinteraction.html
+++ b/toolkit/components/alerts/test/test_alerts_requireinteraction.html
@@ -9,33 +9,33 @@
 <body>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 
 const Cc = SpecialPowers.Cc;
 const Ci = SpecialPowers.Ci;
 
 const chromeScript = SpecialPowers.loadChromeScript(_ => {
-  const { classes: Cc, interfaces: Ci, utils: Cu } = Components;
+  const { utils: Cu } = Components;
 
   Cu.import("resource://gre/modules/Services.jsm");
   Cu.import("resource://gre/modules/Timer.jsm");
 
   addMessageListener("waitForXULAlert", function() {
     var timer = setTimeout(function() {
       Services.ww.unregisterNotification(windowObserver);
       sendAsyncMessage("waitForXULAlert", false);
     }, 2000);
 
     var windowObserver = function(aSubject, aTopic, aData) {
       if (aTopic != "domwindowopened") {
         return;
       }
 
-      var win = aSubject.QueryInterface(Ci.nsIDOMWindow);
+      var win = aSubject.QueryInterface(Components.interfaces.nsIDOMWindow);
       win.addEventListener("load", function onLoad() {
         win.removeEventListener("load", onLoad);
         let windowType = win.document.documentElement.getAttribute("windowtype");
         if (windowType == "alert:alert") {
           clearTimeout(timer);
           Services.ww.unregisterNotification(windowObserver);
 
           sendAsyncMessage("waitForXULAlert", true);
--- a/toolkit/components/alerts/test/test_image.html
+++ b/toolkit/components/alerts/test/test_image.html
@@ -30,21 +30,21 @@ function promiseImage(alert, timeout = 0
   return new Promise(resolve => {
     var isDone = false;
     function done(value) {
       ok(!isDone, "Should call the image listener once");
       isDone = true;
       resolve(value);
     }
     alert.loadImage(timeout, SpecialPowers.wrapCallbackObject({
-      onImageReady(userData, request) {
-        done([true, request, userData]);
+      onImageReady(aUserData, aRequest) {
+        done([true, aRequest, aUserData]);
       },
-      onImageMissing(userData) {
-        done([false, userData]);
+      onImageMissing(aUserData) {
+        done([false, aUserData]);
       },
     }), SpecialPowers.wrap(userData));
   });
 }
 
 add_task(function* testContext() {
   var inUserData = Cc["@mozilla.org/supports-PRInt64;1"]
                      .createInstance(Ci.nsISupportsPRInt64);
@@ -80,20 +80,20 @@ add_task(function* testAnimatedGIF() {
   is(request.image.width, 256, "GIF width should be 256px");
   is(request.image.height, 256, "GIF height should be 256px");
 });
 
 add_task(function* testCancel() {
   var alert = makeAlert(null, imageServerURL + "?f=image.gif&t=180");
   yield new Promise((resolve, reject) => {
     var request = alert.loadImage(0, SpecialPowers.wrapCallbackObject({
-      onImageReady(userData, request) {
+      onImageReady() {
         reject(new Error("Should not load cancelled request"));
       },
-      onImageMissing(userData) {
+      onImageMissing() {
         resolve();
       },
     }), null);
     request.cancel(SpecialPowers.Cr.NS_BINDING_ABORTED);
   });
 });
 
 add_task(function* testMixedContent() {
--- a/toolkit/components/alerts/test/test_multiple_alerts.html
+++ b/toolkit/components/alerts/test/test_multiple_alerts.html
@@ -9,23 +9,21 @@
 <body>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 
 const Cc = SpecialPowers.Cc;
 const Ci = SpecialPowers.Ci;
 
 const chromeScript = SpecialPowers.loadChromeScript(_ => {
-  const { classes: Cc, interfaces: Ci, utils: Cu } = Components;
+  Components.utils.import("resource://gre/modules/Services.jsm");
+  Components.utils.import("resource://gre/modules/Timer.jsm");
 
-  Cu.import("resource://gre/modules/Services.jsm");
-  Cu.import("resource://gre/modules/Timer.jsm");
-
-  const alertService = Cc["@mozilla.org/alerts-service;1"]
-                         .getService(Ci.nsIAlertsService);
+  const alertService = Components.classes["@mozilla.org/alerts-service;1"]
+                                 .getService(Components.interfaces.nsIAlertsService);
 
   addMessageListener("waitForPosition", function() {
     var timer = setTimeout(function() {
       Services.ww.unregisterNotification(windowObserver);
       sendAsyncMessage("waitedForPosition", null);
     }, 2000);
 
     var windowObserver = function(aSubject, aTopic, aData) {
@@ -33,17 +31,17 @@ const chromeScript = SpecialPowers.loadC
         return;
       }
 
       // Alerts are implemented using XUL.
       clearTimeout(timer);
 
       Services.ww.unregisterNotification(windowObserver);
 
-      var win = aSubject.QueryInterface(Ci.nsIDOMWindow);
+      var win = aSubject.QueryInterface(Components.interfaces.nsIDOMWindow);
       win.addEventListener("pageshow", function onPageShow() {
         win.removeEventListener("pageshow", onPageShow, false);
 
         var x = win.screenX;
         var y = win.screenY;
 
         win.addEventListener("pagehide", function onPageHide() {
           win.removeEventListener("pagehide", onPageHide, false);
--- a/toolkit/components/alerts/test/test_principal.html
+++ b/toolkit/components/alerts/test/test_principal.html
@@ -16,19 +16,17 @@
 const Cc = SpecialPowers.Cc;
 const Ci = SpecialPowers.Ci;
 const Services = SpecialPowers.Services;
 
 const notifier = Cc["@mozilla.org/alerts-service;1"]
                    .getService(Ci.nsIAlertsService);
 
 const chromeScript = SpecialPowers.loadChromeScript(_ => {
-  const { classes: Cc, interfaces: Ci, utils: Cu } = Components;
-
-  Cu.import("resource://gre/modules/Services.jsm");
+  Components.utils.import("resource://gre/modules/Services.jsm");
 
   addMessageListener("anyXULAlertsVisible", function() {
     var windows = Services.wm.getEnumerator("alert:alert");
     return windows.hasMoreElements();
   });
 
   addMessageListener("getAlertSource", function() {
     var alertWindows = Services.wm.getEnumerator("alert:alert");
--- a/toolkit/components/extensions/test/mochitest/test_chrome_ext_background_debug_global.html
+++ b/toolkit/components/extensions/test/mochitest/test_chrome_ext_background_debug_global.html
@@ -59,17 +59,17 @@ add_task(function* () {
           is("test!", context.testThing, "global context is the background script context");
           resolve();
         }
       },
     });
   });
 
   let addon = yield new Promise((resolve, reject) => {
-    AddonManager.getAddonByID(ID, addon => addon ? resolve(addon) : reject());
+    AddonManager.getAddonByID(ID, aAddon => aAddon ? resolve(aAddon) : reject());
   });
 
   ok(addon, `Got the addon wrapper for ${addon.id}`);
 
   function waitForDebugGlobalChanges(times, initialAddonInstanceID) {
     return new Promise((resolve) => {
       AddonManager.addAddonListener({
         count: 0,
--- a/toolkit/components/extensions/test/mochitest/test_chrome_ext_downloads_saveAs.html
+++ b/toolkit/components/extensions/test/mochitest/test_chrome_ext_downloads_saveAs.html
@@ -8,19 +8,18 @@
   <link rel="stylesheet" href="chrome://mochikit/contents/tests/SimpleTest/test.css"/>
 </head>
 <body>
 
 <script type="text/javascript">
 "use strict";
 
 add_task(function* test_downloads_saveAs() {
-
   function background() {
-    const url = URL.createObjectURL(new Blob(['file content']));
+    const url = URL.createObjectURL(new Blob(["file content"]));
     browser.test.onMessage.addListener(() =>
       browser.downloads.download({url, saveAs: true})
         .then(id => browser.downloads.onChanged.addListener(delta => {
           if (delta.state.current === "complete") {
             browser.test.sendMessage("done", {ok: true, id});
           }
         })).catch(({message}) => {
           browser.test.sendMessage("done", {ok: false, message});
--- a/toolkit/components/extensions/test/mochitest/test_chrome_ext_storage_cleanup.html
+++ b/toolkit/components/extensions/test/mochitest/test_chrome_ext_storage_cleanup.html
@@ -31,20 +31,20 @@ add_task(function* test_uninstall() {
         db.createObjectStore("store", {keyPath: "name"});
       };
 
       req.onsuccess = e => {
         let db = e.target.result;
         let transaction = db.transaction("store", "readwrite");
         let addreq = transaction.objectStore("store")
                                 .add({name: "hello", value: "world"});
-        addreq.onerror = e => {
-          reject(new Error(`add to indexedDB failed with ${e.errorCode}`));
+        addreq.onerror = addreqError => {
+          reject(new Error(`add to indexedDB failed with ${addreqError.errorCode}`));
         };
-        addreq.onsuccess = e => {
+        addreq.onsuccess = () => {
           resolve();
         };
       };
     });
 
     let browserStoragePromise = browser.storage.local.set({hello: "world"});
 
     Promise.all([idbPromise, browserStoragePromise]).then(() => {
@@ -65,20 +65,20 @@ add_task(function* test_uninstall() {
         // no database, data is not present
         resolve(false);
       };
 
       req.onsuccess = e => {
         let db = e.target.result;
         let transaction = db.transaction("store", "readwrite");
         let addreq = transaction.objectStore("store").get("hello");
-        addreq.onerror = e => {
-          reject(new Error(`read from indexedDB failed with ${e.errorCode}`));
+        addreq.onerror = addreqError => {
+          reject(new Error(`read from indexedDB failed with ${addreqError.errorCode}`));
         };
-        addreq.onsuccess = e => {
+        addreq.onsuccess = () => {
           let match = (addreq.result.value == "world");
           resolve(match);
         };
       };
     });
 
     let browserStoragePromise = browser.storage.local.get("hello").then(result => {
       return (Object.keys(result).length == 1 && result.hello == "world");
--- a/toolkit/components/extensions/test/mochitest/test_ext_content_security_policy.html
+++ b/toolkit/components/extensions/test/mochitest/test_ext_content_security_policy.html
@@ -74,24 +74,24 @@ function* testPolicy(customCSP = null) {
   }
 
 
   function getCSP(window) {
     let {cspJSON} = SpecialPowers.Cu.getObjectPrincipal(window);
     return JSON.parse(cspJSON);
   }
 
-  function background(getCSP) {
+  function background(getCSPFn) {
     browser.test.sendMessage("base-url", browser.extension.getURL("").replace(/\/$/, ""));
 
-    browser.test.sendMessage("background-csp", getCSP(window));
+    browser.test.sendMessage("background-csp", getCSPFn(window));
   }
 
-  function tabScript(getCSP) {
-    browser.test.sendMessage("tab-csp", getCSP(window));
+  function tabScript(getCSPFn) {
+    browser.test.sendMessage("tab-csp", getCSPFn(window));
   }
 
   let extension = ExtensionTestUtils.loadExtension({
     background: `(${background})(${getCSP})`,
 
     files: {
       "tab.html": `<html><head><meta charset="utf-8">
                    <script src="tab.js"></${"script"}></head></html>`,
--- a/toolkit/components/extensions/test/mochitest/test_ext_cookies_permissions.html
+++ b/toolkit/components/extensions/test/mochitest/test_ext_cookies_permissions.html
@@ -14,17 +14,17 @@
 <script type="text/javascript">
 "use strict";
 
 function* testCookies(options) {
   // Changing the options object is a bit of a hack, but it allows us to easily
   // pass an expiration date to the background script.
   options.expiry = Date.now() / 1000 + 3600;
 
-  function background(options) {
+  function background(backgroundOptions) {
     // Ask the parent scope to change some cookies we may or may not have
     // permission for.
     let awaitChanges = new Promise(resolve => {
       browser.test.onMessage.addListener(msg => {
         browser.test.assertEq("cookies-changed", msg, "browser.test.onMessage");
         resolve();
       });
     });
@@ -32,43 +32,43 @@ function* testCookies(options) {
     let changed = [];
     browser.cookies.onChanged.addListener(event => {
       changed.push(`${event.cookie.name}:${event.cause}`);
     });
     browser.test.sendMessage("change-cookies");
 
 
     // Try to access some cookies in various ways.
-    let {url, domain, secure} = options;
+    let {url, domain, secure} = backgroundOptions;
 
     let failures = 0;
     let tallyFailure = error => {
       failures++;
     };
 
     awaitChanges.then(() => {
       return browser.cookies.get({url, name: "foo"});
     }).then(cookie => {
-      browser.test.assertEq(options.shouldPass, cookie != null, "should pass == get cookie");
+      browser.test.assertEq(backgroundOptions.shouldPass, cookie != null, "should pass == get cookie");
 
       return browser.cookies.getAll({domain});
     }).then(cookies => {
-      if (options.shouldPass) {
+      if (backgroundOptions.shouldPass) {
         browser.test.assertEq(2, cookies.length, "expected number of cookies");
       } else {
         browser.test.assertEq(0, cookies.length, "expected number of cookies");
       }
 
       return Promise.all([
-        browser.cookies.set({url, domain, secure, name: "foo", "value": "baz", expirationDate: options.expiry}).catch(tallyFailure),
-        browser.cookies.set({url, domain, secure, name: "bar", "value": "quux", expirationDate: options.expiry}).catch(tallyFailure),
+        browser.cookies.set({url, domain, secure, name: "foo", "value": "baz", expirationDate: backgroundOptions.expiry}).catch(tallyFailure),
+        browser.cookies.set({url, domain, secure, name: "bar", "value": "quux", expirationDate: backgroundOptions.expiry}).catch(tallyFailure),
         browser.cookies.remove({url, name: "deleted"}),
       ]);
     }).then(() => {
-      if (options.shouldPass) {
+      if (backgroundOptions.shouldPass) {
         // The order of eviction events isn't guaranteed, so just check that
         // it's there somewhere.
         let evicted = changed.indexOf("evicted:evicted");
         if (evicted < 0) {
           browser.test.fail("got no eviction event");
         } else {
           browser.test.succeed("got eviction event");
           changed.splice(evicted, 1);
@@ -77,17 +77,17 @@ function* testCookies(options) {
         browser.test.assertEq("x:explicit,x:overwrite,x:explicit,x:explicit,foo:overwrite,foo:explicit,bar:explicit,deleted:explicit",
                               changed.join(","), "expected changes");
       } else {
         browser.test.assertEq("", changed.join(","), "expected no changes");
       }
 
       browser.test.notifyPass("cookie-permissions");
     }).then(() => {
-      if (!(options.shouldPass || options.shouldWrite)) {
+      if (!(backgroundOptions.shouldPass || backgroundOptions.shouldWrite)) {
         browser.test.assertEq(2, failures, "Expected failures");
       } else {
         browser.test.assertEq(0, failures, "Expected no failures");
       }
     }).catch(error => {
       browser.test.fail(`Error: ${error} :: ${error.stack}`);
     });
   }
--- a/toolkit/components/extensions/test/mochitest/test_ext_i18n.html
+++ b/toolkit/components/extensions/test/mochitest/test_ext_i18n.html
@@ -125,35 +125,35 @@ add_task(function* test_i18n() {
         },
 
         "bar": {
           "message": "(bar)",
           "description": "bar",
         },
       },
 
-      "content.js": "new " + function(runTests) {
-        runTests((...args) => {
+      "content.js": "new " + function(runTestsFn) {
+        runTestsFn((...args) => {
           browser.runtime.sendMessage(["assertEq", ...args]);
         });
 
         browser.runtime.sendMessage(["content-script-finished"]);
       } + `(${runTests})`,
     },
 
-    background: "new " + function(runTests) {
+    background: "new " + function(runTestsFn) {
       browser.runtime.onMessage.addListener(([msg, ...args]) => {
         if (msg == "assertEq") {
           browser.test.assertEq(...args);
         } else {
           browser.test.sendMessage(msg, ...args);
         }
       });
 
-      runTests(browser.test.assertEq.bind(browser.test));
+      runTestsFn(browser.test.assertEq.bind(browser.test));
     } + `(${runTests})`,
   });
 
   yield extension.startup();
 
   let win = window.open("file_sample.html");
   yield extension.awaitMessage("content-script-finished");
   win.close();
@@ -243,17 +243,17 @@ add_task(function* test_get_accept_langu
 add_task(function* test_get_ui_language() {
   function getResults() {
     return {
       getUILanguage: browser.i18n.getUILanguage(),
       getMessage: browser.i18n.getMessage("@@ui_locale"),
     };
   }
 
-  function background(getResults) {
+  function background(getResultsFn) {
     function checkResults(source, results, expected) {
       browser.test.assertEq(
         expected,
         results.getUILanguage,
         `Got expected getUILanguage result in ${source}`
       );
       browser.test.assertEq(
         expected,
@@ -262,31 +262,31 @@ add_task(function* test_get_ui_language(
       );
     }
 
     let tabId;
 
     browser.test.onMessage.addListener(([msg, expected]) => {
       browser.tabs.sendMessage(tabId, "get-results", result => {
         checkResults("contentScript", result, expected);
-        checkResults("background", getResults(), expected);
+        checkResults("background", getResultsFn(), expected);
 
         browser.test.sendMessage("done");
       });
     });
 
     browser.tabs.query({currentWindow: true, active: true}, tabs => {
       tabId = tabs[0].id;
       browser.test.sendMessage("ready");
     });
   }
 
-  function content(getResults) {
+  function content(getResultsFn) {
     browser.runtime.onMessage.addListener((msg, sender, respond) => {
-      respond(getResults());
+      respond(getResultsFn());
     });
   }
 
   let extension = ExtensionTestUtils.loadExtension({
     manifest: {
       "content_scripts": [{
         "matches": ["http://mochi.test/*/file_sample.html"],
         "run_at": "document_start",
--- a/toolkit/components/extensions/test/mochitest/test_ext_i18n_css.html
+++ b/toolkit/components/extensions/test/mochitest/test_ext_i18n_css.html
@@ -11,27 +11,27 @@
 <body>
 
 <script type="text/javascript">
 "use strict";
 
 add_task(function* test_i18n_css() {
   let extension = ExtensionTestUtils.loadExtension({
     background: function() {
-      function fetch(url) {
+      function backgroundFetch(url) {
         return new Promise((resolve, reject) => {
           let xhr = new XMLHttpRequest();
           xhr.open("GET", url);
           xhr.onload = () => { resolve(xhr.responseText); };
           xhr.onerror = reject;
           xhr.send();
         });
       }
 
-      Promise.all([fetch("foo.css"), fetch("bar.CsS?x#y"), fetch("foo.txt")]).then(results => {
+      Promise.all([backgroundFetch("foo.css"), backgroundFetch("bar.CsS?x#y"), backgroundFetch("foo.txt")]).then(results => {
         browser.test.assertEq("body { max-width: 42px; }", results[0], "CSS file localized");
         browser.test.assertEq("body { max-width: 42px; }", results[1], "CSS file localized");
 
         browser.test.assertEq("body { __MSG_foo__; }", results[2], "Text file not localized");
 
         browser.test.notifyPass("i18n-css");
       });
 
--- a/toolkit/components/extensions/test/mochitest/test_ext_permission_xhr.html
+++ b/toolkit/components/extensions/test/mochitest/test_ext_permission_xhr.html
@@ -56,34 +56,34 @@ add_task(function* test_simple() {
       .then(() => run(true, window.fetch))
       .then(() => run(false, window.fetch))
       .catch(err => {
         browser.test.fail(`Error: ${err} :: ${err.stack}`);
         browser.test.notifyFail("permission_xhr");
       });
   }
 
-  function background(runTests) {
-    runTests("bg").then(() => {
+  function background(runTestsFn) {
+    runTestsFn("bg").then(() => {
       browser.test.notifyPass("permission_xhr");
     });
   }
 
   let extensionData = {
     background: `(${background})(${runTests})`,
     manifest: {
       permissions: ["http://example.com/"],
       content_scripts: [{
         "matches": ["http://mochi.test/*/file_permission_xhr.html"],
         "js": ["content.js"],
       }],
     },
     files: {
-      "content.js": "new " + function(runTests) {
-        runTests("content").then(() => {
+      "content.js": "new " + function(runTestsFn) {
+        runTestsFn("content").then(() => {
           window.wrappedJSObject.privilegedFetch = fetch;
           window.wrappedJSObject.privilegedXHR = XMLHttpRequest;
 
           window.addEventListener("message", function rcv({data}) {
             switch (data.msg) {
               case "test":
                 break;
 
--- a/toolkit/components/extensions/test/mochitest/test_ext_storage_content.html
+++ b/toolkit/components/extensions/test/mochitest/test_ext_storage_content.html
@@ -30,19 +30,19 @@ function contentScript() {
       return storage.get({[prop]: undefined});
     }).then(data => {
       browser.test.assertEq(value, data[prop], "object getter worked for " + prop);
     });
   }
 
   let globalChanges = {};
 
-  browser.storage.onChanged.addListener((changes, storage) => {
-    browser.test.assertEq("local", storage, "storage is local");
-    Object.assign(globalChanges, changes);
+  browser.storage.onChanged.addListener((aChanges, aStorage) => {
+    browser.test.assertEq("local", aStorage, "storage is local");
+    Object.assign(globalChanges, aChanges);
   });
 
   function checkChanges(changes) {
     function checkSub(obj1, obj2) {
       for (let prop in obj1) {
         browser.test.assertEq(obj1[prop].oldValue, obj2[prop].oldValue);
         browser.test.assertEq(obj1[prop].newValue, obj2[prop].newValue);
       }
--- a/toolkit/components/extensions/test/mochitest/test_ext_storage_tab.html
+++ b/toolkit/components/extensions/test/mochitest/test_ext_storage_tab.html
@@ -35,18 +35,18 @@ add_task(function* test_multiple_pages()
           setTimeout(resolve, 0);
         }
       });
     });
 
     let storage = browser.storage.local;
 
     browser.test.log("create");
-    browser.tabs.create({url: "tab.html"}).then(tab => {
-      tabId = tab.id;
+    browser.tabs.create({url: "tab.html"}).then(tabObj => {
+      tabId = tabObj.id;
 
       return tabReady;
     }).then(() => {
       return storage.get("key");
     }).then(result => {
       browser.test.assertEq(undefined, result.key, "Key should be undefined");
 
       return browser.runtime.sendMessage("tab-set-key");
--- a/toolkit/components/extensions/test/mochitest/test_ext_web_accessible_resources.html
+++ b/toolkit/components/extensions/test/mochitest/test_ext_web_accessible_resources.html
@@ -204,19 +204,19 @@ add_task(function* test_web_accessible_r
   function content() {
     window.addEventListener("message", function rcv(event) {
       browser.runtime.sendMessage("script-ran");
       window.removeEventListener("message", rcv, false);
     }, false);
 
     testImageLoading(browser.extension.getURL("image.png"), "loaded");
 
-    let testScript = document.createElement("script");
-    testScript.setAttribute("src", browser.extension.getURL("test_script.js"));
-    document.head.appendChild(testScript);
+    let testScriptElement = document.createElement("script");
+    testScriptElement.setAttribute("src", browser.extension.getURL("test_script.js"));
+    document.head.appendChild(testScriptElement);
     browser.runtime.sendMessage("script-loaded");
   }
 
   function testScript() {
     window.postMessage("test-script-loaded", "*");
   }
 
   let extension = ExtensionTestUtils.loadExtension({
@@ -296,19 +296,19 @@ add_task(function* test_web_accessible_r
 
     browser.test.sendMessage("background-ready");
   }
 
   function content() {
     testImageLoading("http://example.com/tests/toolkit/components/extensions/test/mochitest/file_image_bad.png", "blocked");
     testImageLoading(browser.extension.getURL("image.png"), "loaded");
 
-    let testScript = document.createElement("script");
-    testScript.setAttribute("src", browser.extension.getURL("test_script.js"));
-    document.head.appendChild(testScript);
+    let testScriptElement = document.createElement("script");
+    testScriptElement.setAttribute("src", browser.extension.getURL("test_script.js"));
+    document.head.appendChild(testScriptElement);
 
     window.addEventListener("message", event => {
       browser.runtime.sendMessage(event.data);
     });
   }
 
   function testScript() {
     window.postMessage("accessible-script-loaded", "*");
--- a/toolkit/components/extensions/test/mochitest/test_ext_webrequest_upload.html
+++ b/toolkit/components/extensions/test/mochitest/test_ext_webrequest_upload.html
@@ -41,18 +41,18 @@
 <input type="text" name="textInput" value="value2">
 </form>
 <script>
 "use strict";
 
 let files, testFile, blob, file, uploads;
 add_task(function* test_setup() {
   files = yield new Promise(resolve => {
-    SpecialPowers.createFiles([{name: "testFile.pdf", data: "Not really a PDF file :)", "type": "application/x-pdf"}], (files) => {
-      resolve(files);
+    SpecialPowers.createFiles([{name: "testFile.pdf", data: "Not really a PDF file :)", "type": "application/x-pdf"}], (result) => {
+      resolve(result);
     });
   });
   testFile = files[0];
   blob = {
     name: "blobAsFile",
     content: new Blob(["A blob sent as a file"], {type: "text/csv"}),
     fileName: "blobAsFile.csv",
   };
--- a/toolkit/components/passwordmgr/test/browser/browser_DOMFormHasPassword.js
+++ b/toolkit/components/passwordmgr/test/browser/browser_DOMFormHasPassword.js
@@ -1,16 +1,16 @@
 const ids = {
   INPUT_ID: "input1",
   FORM1_ID: "form1",
   FORM2_ID: "form2",
   CHANGE_INPUT_ID: "input2",
 };
 
-function task(ids) {
+function task(contentIds) {
   let resolve;
   let promise = new Promise(r => { resolve = r; });
 
   function unexpectedContentEvent(evt) {
     ok(false, "Received a " + evt.type + " event on content");
   }
 
   var gDoc = null;
@@ -26,50 +26,50 @@ function task(ids) {
     gDoc.addEventListener("DOMFormHasPassword", unexpectedContentEvent, false);
     gDoc.defaultView.setTimeout(test_inputAdd, 0);
   }
 
   function test_inputAdd() {
     addEventListener("DOMFormHasPassword", test_inputAddHandler, false);
     let input = gDoc.createElementNS("http://www.w3.org/1999/xhtml", "input");
     input.setAttribute("type", "password");
-    input.setAttribute("id", ids.INPUT_ID);
+    input.setAttribute("id", contentIds.INPUT_ID);
     input.setAttribute("data-test", "unique-attribute");
-    gDoc.getElementById(ids.FORM1_ID).appendChild(input);
+    gDoc.getElementById(contentIds.FORM1_ID).appendChild(input);
   }
 
   function test_inputAddHandler(evt) {
     removeEventListener(evt.type, test_inputAddHandler, false);
-    is(evt.target.id, ids.FORM1_ID,
+    is(evt.target.id, contentIds.FORM1_ID,
        evt.type + " event targets correct form element (added password element)");
     gDoc.defaultView.setTimeout(test_inputChangeForm, 0);
   }
 
   function test_inputChangeForm() {
     addEventListener("DOMFormHasPassword", test_inputChangeFormHandler, false);
-    let input = gDoc.getElementById(ids.INPUT_ID);
-    input.setAttribute("form", ids.FORM2_ID);
+    let input = gDoc.getElementById(contentIds.INPUT_ID);
+    input.setAttribute("form", contentIds.FORM2_ID);
   }
 
   function test_inputChangeFormHandler(evt) {
     removeEventListener(evt.type, test_inputChangeFormHandler, false);
-    is(evt.target.id, ids.FORM2_ID,
+    is(evt.target.id, contentIds.FORM2_ID,
        evt.type + " event targets correct form element (changed form)");
     gDoc.defaultView.setTimeout(test_inputChangesType, 0);
   }
 
   function test_inputChangesType() {
     addEventListener("DOMFormHasPassword", test_inputChangesTypeHandler, false);
-    let input = gDoc.getElementById(ids.CHANGE_INPUT_ID);
+    let input = gDoc.getElementById(contentIds.CHANGE_INPUT_ID);
     input.setAttribute("type", "password");
   }
 
   function test_inputChangesTypeHandler(evt) {
     removeEventListener(evt.type, test_inputChangesTypeHandler, false);
-    is(evt.target.id, ids.FORM1_ID,
+    is(evt.target.id, contentIds.FORM1_ID,
        evt.type + " event targets correct form element (changed type)");
     gDoc.defaultView.setTimeout(finish, 0);
   }
 
   function finish() {
     gDoc.removeEventListener("DOMFormHasPassword", unexpectedContentEvent, false);
     resolve();
   }
--- a/toolkit/components/passwordmgr/test/browser/browser_DOMInputPasswordAdded.js
+++ b/toolkit/components/passwordmgr/test/browser/browser_DOMInputPasswordAdded.js
@@ -3,17 +3,17 @@ const consts = {
 
   INPUT_ID: "input1",
   FORM1_ID: "form1",
   FORM2_ID: "form2",
   CHANGE_INPUT_ID: "input2",
   BODY_INPUT_ID: "input3",
 };
 
-function task(consts) {
+function task(contentConsts) {
   let resolve;
   let promise = new Promise(r => { resolve = r; });
 
   function unexpectedContentEvent(evt) {
     Assert.ok(false, "Received a " + evt.type + " event on content");
   }
 
   var gDoc = null;
@@ -25,57 +25,57 @@ function task(consts) {
     gDoc = content.document;
     // These events shouldn't escape to content.
     gDoc.addEventListener("DOMInputPasswordAdded", unexpectedContentEvent, false);
     gDoc.defaultView.setTimeout(test_inputAdd, 0);
   }
 
   function test_inputAdd() {
     addEventListener("DOMInputPasswordAdded", test_inputAddHandler, false);
-    let input = gDoc.createElementNS(consts.HTML_NS, "input");
+    let input = gDoc.createElementNS(contentConsts.HTML_NS, "input");
     input.setAttribute("type", "password");
-    input.setAttribute("id", consts.INPUT_ID);
+    input.setAttribute("id", contentConsts.INPUT_ID);
     input.setAttribute("data-test", "unique-attribute");
-    gDoc.getElementById(consts.FORM1_ID).appendChild(input);
+    gDoc.getElementById(contentConsts.FORM1_ID).appendChild(input);
     info("Done appending the input element");
   }
 
   function test_inputAddHandler(evt) {
     removeEventListener(evt.type, test_inputAddHandler, false);
-    Assert.equal(evt.target.id, consts.INPUT_ID,
+    Assert.equal(evt.target.id, contentConsts.INPUT_ID,
       evt.type + " event targets correct input element (added password element)");
     gDoc.defaultView.setTimeout(test_inputAddOutsideForm, 0);
   }
 
   function test_inputAddOutsideForm() {
     addEventListener("DOMInputPasswordAdded", test_inputAddOutsideFormHandler, false);
-    let input = gDoc.createElementNS(consts.HTML_NS, "input");
+    let input = gDoc.createElementNS(contentConsts.HTML_NS, "input");
     input.setAttribute("type", "password");
-    input.setAttribute("id", consts.BODY_INPUT_ID);
+    input.setAttribute("id", contentConsts.BODY_INPUT_ID);
     input.setAttribute("data-test", "unique-attribute");
     gDoc.body.appendChild(input);
     info("Done appending the input element to the body");
   }
 
   function test_inputAddOutsideFormHandler(evt) {
     removeEventListener(evt.type, test_inputAddOutsideFormHandler, false);
-    Assert.equal(evt.target.id, consts.BODY_INPUT_ID,
+    Assert.equal(evt.target.id, contentConsts.BODY_INPUT_ID,
       evt.type + " event targets correct input element (added password element outside form)");
     gDoc.defaultView.setTimeout(test_inputChangesType, 0);
   }
 
   function test_inputChangesType() {
     addEventListener("DOMInputPasswordAdded", test_inputChangesTypeHandler, false);
-    let input = gDoc.getElementById(consts.CHANGE_INPUT_ID);
+    let input = gDoc.getElementById(contentConsts.CHANGE_INPUT_ID);
     input.setAttribute("type", "password");
   }
 
   function test_inputChangesTypeHandler(evt) {
     removeEventListener(evt.type, test_inputChangesTypeHandler, false);
-    Assert.equal(evt.target.id, consts.CHANGE_INPUT_ID,
+    Assert.equal(evt.target.id, contentConsts.CHANGE_INPUT_ID,
       evt.type + " event targets correct input element (changed type)");
     gDoc.defaultView.setTimeout(completeTest, 0);
   }
 
   function completeTest() {
     Assert.ok(true, "Test completed");
     gDoc.removeEventListener("DOMInputPasswordAdded", unexpectedContentEvent, false);
     resolve();
--- a/toolkit/components/passwordmgr/test/browser/browser_http_autofill.js
+++ b/toolkit/components/passwordmgr/test/browser/browser_http_autofill.js
@@ -18,60 +18,60 @@ add_task(function* setup() {
   yield SpecialPowers.pushPrefEnv({ "set": [["signon.autofillForms.http", false]] });
 });
 
 add_task(function* test_http_autofill() {
   for (let scheme of ["http", "https"]) {
     let tab = yield BrowserTestUtils
       .openNewForegroundTab(gBrowser, `${scheme}${TEST_URL_PATH}form_basic.html`);
 
-    let {username, password} = yield ContentTask.spawn(gBrowser.selectedBrowser, null, function* () {
+    let [username, password] = yield ContentTask.spawn(gBrowser.selectedBrowser, null, function* () {
       let doc = content.document;
-      let username = doc.getElementById("form-basic-username").value;
-      let password = doc.getElementById("form-basic-password").value;
-      return { username, password };
+      let contentUsername = doc.getElementById("form-basic-username").value;
+      let contentPassword = doc.getElementById("form-basic-password").value;
+      return [contentUsername, contentPassword];
     });
 
     is(username, scheme == "http" ? "" : "username", "Username filled correctly");
     is(password, scheme == "http" ? "" : "password", "Password filled correctly");
 
     gBrowser.removeTab(tab);
   }
 });
 
 add_task(function* test_iframe_in_http_autofill() {
   for (let scheme of ["http", "https"]) {
     let tab = yield BrowserTestUtils
       .openNewForegroundTab(gBrowser, `${scheme}${TEST_URL_PATH}form_basic_iframe.html`);
 
-    let {username, password} = yield ContentTask.spawn(gBrowser.selectedBrowser, null, function* () {
+    let [username, password] = yield ContentTask.spawn(gBrowser.selectedBrowser, null, function* () {
       let doc = content.document;
       let iframe = doc.getElementById("test-iframe");
-      let username = iframe.contentWindow.document.getElementById("form-basic-username").value;
-      let password = iframe.contentWindow.document.getElementById("form-basic-password").value;
-      return { username, password };
+      let contentUsername = iframe.contentWindow.document.getElementById("form-basic-username").value;
+      let contentPassword = iframe.contentWindow.document.getElementById("form-basic-password").value;
+      return [contentUsername, contentPassword];
     });
 
     is(username, scheme == "http" ? "" : "username", "Username filled correctly");
     is(password, scheme == "http" ? "" : "password", "Password filled correctly");
 
     gBrowser.removeTab(tab);
   }
 });
 
 add_task(function* test_http_action_autofill() {
   for (let type of ["insecure", "secure"]) {
     let tab = yield BrowserTestUtils
       .openNewForegroundTab(gBrowser, `https${TEST_URL_PATH}form_cross_origin_${type}_action.html`);
 
-    let {username, password} = yield ContentTask.spawn(gBrowser.selectedBrowser, null, function* () {
+    let [username, password] = yield ContentTask.spawn(gBrowser.selectedBrowser, null, function* () {
       let doc = content.document;
-      let username = doc.getElementById("form-basic-username").value;
-      let password = doc.getElementById("form-basic-password").value;
-      return { username, password };
+      let contentUsername = doc.getElementById("form-basic-username").value;
+      let contentPassword = doc.getElementById("form-basic-password").value;
+      return [contentUsername, contentPassword];
     });
 
     is(username, type == "insecure" ? "" : "username", "Username filled correctly");
     is(password, type == "insecure" ? "" : "password", "Password filled correctly");
 
     gBrowser.removeTab(tab);
   }
 });
--- a/toolkit/components/passwordmgr/test/browser/browser_insecurePasswordWarning.js
+++ b/toolkit/components/passwordmgr/test/browser/browser_insecurePasswordWarning.js
@@ -8,31 +8,31 @@ const WARNING_PATTERN = [{
 }, {
   key: "INSECURE_PAGE",
   msg: 'JavaScript Warning: "Password fields present on an insecure (http://) page. This is a security risk that allows user login credentials to be stolen."'
 }];
 
 add_task(function* testInsecurePasswordWarning() {
   let warningPatternHandler;
 
-  function messageHandler(msg) {
+  function messageHandler(msgObj) {
     function findWarningPattern(msg) {
       return WARNING_PATTERN.find(patternPair => {
         return msg.indexOf(patternPair.msg) !== -1;
       });
     }
 
-    let warning = findWarningPattern(msg.message);
+    let warning = findWarningPattern(msgObj.message);
 
     // Only handle the insecure password related warning messages.
     if (warning) {
       // Prevent any unexpected or redundant matched warning message coming after
       // the test case is ended.
       ok(warningPatternHandler, "Invoke a valid warning message handler");
-      warningPatternHandler(warning, msg.message);
+      warningPatternHandler(warning, msgObj.message);
     }
   }
   Services.console.registerListener(messageHandler);
   registerCleanupFunction(function() {
     Services.console.unregisterListener(messageHandler);
   });
 
   for (let [origin, testFile, expectWarnings] of [
--- a/toolkit/components/passwordmgr/test/browser/browser_notifications.js
+++ b/toolkit/components/passwordmgr/test/browser/browser_notifications.js
@@ -35,21 +35,21 @@ add_task(function* test_save_change() {
       url: "https://example.com/browser/toolkit/components/" +
            "passwordmgr/test/browser/form_basic.html",
     }, function* (browser) {
       // Submit the form in the content page with the credentials from the test
       // case. This will cause the doorhanger notification to be displayed.
       let promiseShown = BrowserTestUtils.waitForEvent(PopupNotifications.panel,
                                                        "popupshown",
                                                        (event) => event.target == PopupNotifications.panel);
-      yield ContentTask.spawn(browser, { username, password },
-        function* ({ username, password }) {
+      yield ContentTask.spawn(browser, [username, password],
+        function* ([contentUsername, contentPassword]) {
           let doc = content.document;
-          doc.getElementById("form-basic-username").value = username;
-          doc.getElementById("form-basic-password").value = password;
+          doc.getElementById("form-basic-username").value = contentUsername;
+          doc.getElementById("form-basic-password").value = contentPassword;
           doc.getElementById("form-basic").submit();
         });
       yield promiseShown;
       let notificationElement = PopupNotifications.panel.childNodes[0];
       // Style flush to make sure binding is attached
       notificationElement.querySelector("#password-notification-password").clientTop;
 
       // Check the actual content of the popup notification.
--- a/toolkit/components/passwordmgr/test/browser/browser_notifications_password.js
+++ b/toolkit/components/passwordmgr/test/browser/browser_notifications_password.js
@@ -76,20 +76,20 @@ add_task(function* test_edit_password() 
            "passwordmgr/test/browser/form_basic.html",
     }, function* (browser) {
       // Submit the form in the content page with the credentials from the test
       // case. This will cause the doorhanger notification to be displayed.
       let promiseShown = BrowserTestUtils.waitForEvent(PopupNotifications.panel,
                                                        "popupshown",
                                                        (event) => event.target == PopupNotifications.panel);
       yield ContentTask.spawn(browser, testCase,
-        function* (testCase) {
+        function* (contentTestCase) {
           let doc = content.document;
-          doc.getElementById("form-basic-username").value = testCase.usernameInPage;
-          doc.getElementById("form-basic-password").value = testCase.passwordInPage;
+          doc.getElementById("form-basic-username").value = contentTestCase.usernameInPage;
+          doc.getElementById("form-basic-password").value = contentTestCase.passwordInPage;
           doc.getElementById("form-basic").submit();
         });
       yield promiseShown;
       let notificationElement = PopupNotifications.panel.childNodes[0];
       // Style flush to make sure binding is attached
       notificationElement.querySelector("#password-notification-password").clientTop;
 
       // Modify the username in the dialog if requested.
--- a/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_sort.js
+++ b/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_sort.js
@@ -73,20 +73,20 @@ function test() {
             let showMode = (toggleCalls++ % 2) == 0;
 
             // only watch for a confirmation dialog every other time being called
             if (showMode) {
                 Services.ww.registerNotification(function (aSubject, aTopic, aData) {
                     if (aTopic == "domwindowclosed")
                         Services.ww.unregisterNotification(arguments.callee);
                     else if (aTopic == "domwindowopened") {
-                        let win = aSubject.QueryInterface(Ci.nsIDOMEventTarget);
+                        let targetWin = aSubject.QueryInterface(Ci.nsIDOMEventTarget);
                         SimpleTest.waitForFocus(function() {
-                            EventUtils.sendKey("RETURN", win);
-                        }, win);
+                            EventUtils.sendKey("RETURN", targetWin);
+                        }, targetWin);
                     }
                 });
             }
 
             Services.obs.addObserver(function (aSubject, aTopic, aData) {
                 if (aTopic == "passwordmgr-password-toggle-complete") {
                     Services.obs.removeObserver(arguments.callee, aTopic);
                     func();
--- a/toolkit/components/passwordmgr/test/browser/browser_passwordmgrdlg.js
+++ b/toolkit/components/passwordmgr/test/browser/browser_passwordmgrdlg.js
@@ -84,20 +84,20 @@ function test() {
             let showMode = (toggleCalls++ % 2) == 0;
 
             // only watch for a confirmation dialog every other time being called
             if (showMode) {
                 Services.ww.registerNotification(function (aSubject, aTopic, aData) {
                     if (aTopic == "domwindowclosed")
                         Services.ww.unregisterNotification(arguments.callee);
                     else if (aTopic == "domwindowopened") {
-                        let win = aSubject.QueryInterface(Ci.nsIDOMEventTarget);
+                        let targetWin = aSubject.QueryInterface(Ci.nsIDOMEventTarget);
                         SimpleTest.waitForFocus(function() {
-                            EventUtils.sendKey("RETURN", win);
-                        }, win);
+                            EventUtils.sendKey("RETURN", targetWin);
+                        }, targetWin);
                     }
                 });
             }
 
             Services.obs.addObserver(function (aSubject, aTopic, aData) {
                 if (aTopic == "passwordmgr-password-toggle-complete") {
                     Services.obs.removeObserver(arguments.callee, aTopic);
                     func();
@@ -110,34 +110,34 @@ function test() {
         function runTests(mode, endFunction) {
             let testCounter = 0;
 
             function setFilter(string) {
                 filter.value = string;
                 filter.doCommand();
             }
 
-            function runOneTest(test) {
+            function runOneTest(testCase) {
                 function tester() {
-                    is(view.rowCount, expected, expected + " logins should match '" + test.filter + "'");
+                    is(view.rowCount, expected, expected + " logins should match '" + testCase.filter + "'");
                 }
 
                 let expected;
                 switch (mode) {
                 case 1: // without showing passwords
-                    expected = test.count;
+                    expected = testCase.count;
                     break;
                 case 2: // showing passwords
-                    expected = ("count2" in test) ? test.count2 : test.count;
+                    expected = ("count2" in testCase) ? testCase.count2 : testCase.count;
                     break;
                 case 3: // toggle
-                    expected = test.count;
+                    expected = testCase.count;
                     tester();
                     toggleShowPasswords(function () {
-                        expected = ("count2" in test) ? test.count2 : test.count;
+                        expected = ("count2" in testCase) ? testCase.count2 : testCase.count;
                         tester();
                         toggleShowPasswords(proceed);
                     });
                     return;
                 }
                 tester();
                 proceed();
             }
@@ -146,19 +146,19 @@ function test() {
                 // run the next test if necessary or proceed with the tests
                 if (testCounter != tests.length)
                     runNextTest();
                 else
                     endFunction();
             }
 
             function runNextTest() {
-                let test = tests[testCounter++];
-                setFilter(test.filter);
-                setTimeout(runOneTest, 0, test);
+                let testCase = tests[testCounter++];
+                setFilter(testCase.filter);
+                setTimeout(runOneTest, 0, testCase);
             }
 
             runNextTest();
         }
 
         function step1() {
             runTests(1, step2);
         }
--- a/toolkit/components/passwordmgr/test/browser/head.js
+++ b/toolkit/components/passwordmgr/test/browser/head.js
@@ -6,17 +6,17 @@ Cu.import("resource://testing-common/Con
 registerCleanupFunction(function* cleanup_removeAllLoginsAndResetRecipes() {
   Services.logins.removeAllLogins();
 
   let recipeParent = LoginTestUtils.recipes.getRecipeParent();
   if (!recipeParent) {
     // No need to reset the recipes if the recipe module wasn't even loaded.
     return;
   }
-  yield recipeParent.then(recipeParent => recipeParent.reset());
+  yield recipeParent.then(recipeParentResult => recipeParentResult.reset());
 });
 
 /**
  * Loads a test page in `DIRECTORY_URL` which automatically submits to formsubmit.sjs and returns a
  * promise resolving with the field values when the optional `aTaskFn` is done.
  *
  * @param {String} aPageFile - test page file name which auto-submits to formsubmit.sjs
  * @param {Function} aTaskFn - task which can be run before the tab closes.
--- a/toolkit/components/passwordmgr/test/chrome/test_privbrowsing_perwindowpb.html
+++ b/toolkit/components/passwordmgr/test/chrome/test_privbrowsing_perwindowpb.html
@@ -199,19 +199,19 @@ var mainWindow = window.QueryInterface(C
                     .QueryInterface(Ci.nsIDocShellTreeItem)
                     .rootTreeItem
                     .QueryInterface(Ci.nsIInterfaceRequestor)
                     .getInterface(Ci.nsIDOMWindow);
 var contentPage = "http://mochi.test:8888/chrome/toolkit/components/passwordmgr/test/chrome/privbrowsing_perwindowpb_iframe.html";
 var testWindows = [];
 
 function whenDelayedStartupFinished(aWindow, aCallback) {
-  Services.obs.addObserver(function observer(aSubject, aTopic) {
+  Services.obs.addObserver(function obs(aSubject, aTopic) {
     if (aWindow == aSubject) {
-      Services.obs.removeObserver(observer, aTopic);
+      Services.obs.removeObserver(obs, aTopic);
       setTimeout(aCallback, 0);
     }
   }, "browser-delayed-startup-finished", false);
 }
 
 function testOnWindow(aIsPrivate, aCallback) {
   var win = mainWindow.OpenBrowserWindow({private: aIsPrivate});
   win.addEventListener("load", function onLoad() {
--- a/toolkit/components/passwordmgr/test/mochitest/test_bug_627616.html
+++ b/toolkit/components/passwordmgr/test/mochitest/test_bug_627616.html
@@ -59,67 +59,67 @@
       mm.addMessageListener("prepareForNextTestDone", function prepared(msg) {
         mm.removeMessageListener("prepareForNextTestDone", prepared);
         if (pendingTests.length > 0) {
           ({expectedDialogs: gExpectedDialogs,
             test: gCurrentTest} = pendingTests.shift());
           gCurrentTest.call(this);
         } else {
           mm.sendAsyncMessage("cleanup");
-          mm.addMessageListener("cleanupDone", msg => {
+          mm.addMessageListener("cleanupDone", () => {
             // mm.destroy() is called as a cleanup function by runInParent(), no
             // need to do it here.
             SimpleTest.finish();
           });
         }
       });
     }
 
     var pendingTests = [{expectedDialogs: 2, test: testNonAnonymousCredentials},
                         {expectedDialogs: 1, test: testAnonymousCredentials},
                         {expectedDialogs: 0, test: testAnonymousNoAuth}];
 
     let mm = runInParent(() => {
-      const { classes: Cc, interfaces: Ci, utils: Cu } = Components;
+      const { classes: parentCc, interfaces: parentCi, utils: parentCu } = Components;
 
-      Cu.import("resource://gre/modules/Services.jsm");
-      Cu.import("resource://gre/modules/NetUtil.jsm");
-      Cu.import("resource://gre/modules/Timer.jsm");
-      Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+      parentCu.import("resource://gre/modules/Services.jsm");
+      parentCu.import("resource://gre/modules/NetUtil.jsm");
+      parentCu.import("resource://gre/modules/Timer.jsm");
+      parentCu.import("resource://gre/modules/XPCOMUtils.jsm");
 
       let channel = NetUtil.newChannel({
         uri: "http://example.com",
         loadUsingSystemPrincipal: true
       });
 
-      let pps = Cc["@mozilla.org/network/protocol-proxy-service;1"].
-                getService(Ci.nsIProtocolProxyService);
+      let pps = parentCc["@mozilla.org/network/protocol-proxy-service;1"].
+                getService(parentCi.nsIProtocolProxyService);
       pps.asyncResolve(channel, 0, {
         onProxyAvailable(req, uri, pi, status) {
           let mozproxy = "moz-proxy://" + pi.host + ":" + pi.port;
-          let login = Cc["@mozilla.org/login-manager/loginInfo;1"].
-                      createInstance(Ci.nsILoginInfo);
+          let login = parentCc["@mozilla.org/login-manager/loginInfo;1"].
+                      createInstance(parentCi.nsILoginInfo);
           login.init(mozproxy, null, "proxy_realm", "proxy_user", "proxy_pass",
                      "", "");
           Services.logins.addLogin(login);
 
-          let login2 = Cc["@mozilla.org/login-manager/loginInfo;1"].
-                       createInstance(Ci.nsILoginInfo);
+          let login2 = parentCc["@mozilla.org/login-manager/loginInfo;1"].
+                       createInstance(parentCi.nsILoginInfo);
           login2.init("http://mochi.test:8888", null, "mochirealm", "user1name",
                        "user1pass", "", "");
           Services.logins.addLogin(login2);
 
           sendAsyncMessage("setupDone");
         },
-        QueryInterface: XPCOMUtils.generateQI([Ci.nsIProtocolProxyCallback]),
+        QueryInterface: XPCOMUtils.generateQI([parentCi.nsIProtocolProxyCallback]),
       });
 
       addMessageListener("prepareForNextTest", message => {
-        Cc["@mozilla.org/network/http-auth-manager;1"].
-          getService(Ci.nsIHttpAuthManager).
+        parentCc["@mozilla.org/network/http-auth-manager;1"].
+          getService(parentCi.nsIHttpAuthManager).
           clearAll();
         sendAsyncMessage("prepareForNextTestDone");
       });
 
       let dialogObserverTopic = "common-dialog-loaded";
 
       function dialogObserver(subj, topic, data) {
         subj.Dialog.ui.prompt.document.documentElement.acceptDialog();
--- a/toolkit/components/passwordmgr/test/mochitest/test_prompt_http.html
+++ b/toolkit/components/passwordmgr/test/mochitest/test_prompt_http.html
@@ -13,17 +13,16 @@
 <p id="display"></p>
 
 <div id="content" style="display: none">
   <iframe id="iframe"></iframe>
 </div>
 
 <pre id="test">
 <script class="testbody" type="text/javascript">
-var state, action;
 var iframe = document.getElementById("iframe");
 
 // Force parent to not look for tab-modal prompts, as they're not used for auth prompts.
 isTabModal = false;
 
 const AUTHENTICATE_PATH = new URL("authenticate.sjs", window.location.href).pathname;
 
 let chromeScript = runInParent(SimpleTest.getTestFileURL("pwmgr_common.js"));
@@ -75,32 +74,32 @@ runInParent(() => {
   pwmgr.addLogin(login4);
   pwmgr.addLogin(httpUpgradeLogin);
   pwmgr.addLogin(httpsDowngradeLogin);
   pwmgr.addLogin(dedupeHttpUpgradeLogin);
   pwmgr.addLogin(dedupeHttpsUpgradeLogin);
 });
 
 add_task(function* test_iframe() {
-  state = {
+  let state = {
     msg         : "http://mochi.test:8888 is requesting your username and password. The site says: “mochitest”",
     title       : "Authentication Required",
     textValue   : "mochiuser1",
     passValue   : "mochipass1",
     iconClass   : "authentication-icon question-icon",
     titleHidden : true,
     textHidden  : false,
     passHidden  : false,
     checkHidden : true,
     checkMsg    : "",
     checked     : false,
     focused     : "textField",
     defButton   : "button0",
   };
-  action = {
+  let action = {
     buttonClick : "ok",
   };
   promptDone = handlePrompt(state, action);
 
   // The following tests are driven by iframe loads
 
   var iframeLoaded = onloadPromiseFor("iframe");
   iframe.src = "authenticate.sjs?user=mochiuser1&pass=mochipass1";
--- a/toolkit/components/passwordmgr/test/mochitest/test_prompt_noWindow.html
+++ b/toolkit/components/passwordmgr/test/mochitest/test_prompt_noWindow.html
@@ -53,20 +53,20 @@ add_task(function* test_sandbox_xhr() {
   let action = {
     buttonClick : "ok",
   };
   let promptDone = handlePrompt(state, action);
 
   let url = new URL("authenticate.sjs?user=mochiuser1&pass=mochipass1", window.location.href);
   let sandboxConstructor = SpecialPowers.Cu.Sandbox;
   let sandbox = new sandboxConstructor(this, {wantXrays: true});
-  function sandboxedRequest(url) {
+  function sandboxedRequest(sandboxedUrl) {
     let req = SpecialPowers.Cc["@mozilla.org/xmlextras/xmlhttprequest;1"]
                            .createInstance(SpecialPowers.Ci.nsIXMLHttpRequest);
-    req.open("GET", url, true);
+    req.open("GET", sandboxedUrl, true);
     req.send(null);
   }
 
   let loginModifiedPromise = promiseStorageChanged(["modifyLogin"]);
   sandbox.sandboxedRequest = sandboxedRequest(url);
   info("send the XHR request in the sandbox");
   SpecialPowers.Cu.evalInSandbox("sandboxedRequest;", sandbox);
 
--- a/toolkit/components/passwordmgr/test/pwmgr_common.js
+++ b/toolkit/components/passwordmgr/test/pwmgr_common.js
@@ -183,18 +183,18 @@ function registerRunTests() {
 
     var observer = SpecialPowers.wrapCallback(function(subject, topic, data) {
       var formLikeRoot = subject.QueryInterface(SpecialPowers.Ci.nsIDOMNode);
       if (formLikeRoot.id !== 'observerforcer')
         return;
       SpecialPowers.removeObserver(observer, "passwordmgr-processed-form");
       formLikeRoot.remove();
       SimpleTest.executeSoon(() => {
-        var event = new Event("runTests");
-        window.dispatchEvent(event);
+        var runTestEvent = new Event("runTests");
+        window.dispatchEvent(runTestEvent);
       });
     });
     SpecialPowers.addObserver(observer, "passwordmgr-processed-form", false);
 
     document.body.appendChild(form);
   });
 }
 
@@ -396,24 +396,23 @@ if (this.addMessageListener) {
     // Force LoginManagerParent to init for the tests since it's normally delayed
     // by apps such as on Android.
     LoginManagerParent.init();
 
     commonInit(selfFilling);
     sendAsyncMessage("doneSetup");
   });
 
-  addMessageListener("loadRecipes", Task.async(function* loadRecipes(recipes) {
-
+  addMessageListener("loadRecipes", Task.async(function*(recipes) {
     var recipeParent = yield LoginManagerParent.recipeParentPromise;
     yield recipeParent.load(recipes);
     sendAsyncMessage("loadedRecipes", recipes);
   }));
 
-  addMessageListener("resetRecipes", Task.async(function* resetRecipes() {
+  addMessageListener("resetRecipes", Task.async(function*() {
     let recipeParent = yield LoginManagerParent.recipeParentPromise;
     yield recipeParent.reset();
     sendAsyncMessage("recipesReset");
   }));
 
   addMessageListener("proxyLoginManager", msg => {
     // Recreate nsILoginInfo objects from vanilla JS objects.
     let recreatedArgs = msg.args.map((arg, index) => {
--- a/toolkit/components/passwordmgr/test/test_master_password.html
+++ b/toolkit/components/passwordmgr/test/test_master_password.html
@@ -68,25 +68,25 @@ addEventListener("message", () => {
 /*
  * handleDialog
  *
  * Invoked a short period of time after calling startCallbackTimer(), and
  * allows testing the actual auth dialog while it's being displayed. Tests
  * should call startCallbackTimer() each time the auth dialog is expected (the
  * timer is a one-shot).
  */
-function handleDialog(doc, testNum) {
-  ok(true, "handleDialog running for test " + testNum);
+function handleDialog(doc, testNumber) {
+  ok(true, "handleDialog running for test " + testNumber);
 
   var clickOK   = true;
   var doNothing = false;
   var passfield = doc.getElementById("password1Textbox");
   var dialog    = doc.getElementById("commonDialog");
 
-    switch (testNum) {
+    switch (testNumber) {
       case 1:
         is(passfield.getAttribute("value"), "", "Checking empty prompt");
         passfield.setAttribute("value", masterPassword);
         is(passfield.getAttribute("value"), masterPassword, "Checking filled prompt");
         break;
 
       case 2:
         clickOK = false;
@@ -102,33 +102,33 @@ function handleDialog(doc, testNum) {
         break;
 
       case 5:
         is(passfield.getAttribute("value"), "", "Checking empty prompt");
         passfield.setAttribute("value", masterPassword);
         break;
 
       default:
-        ok(false, "Uhh, unhandled switch for testNum #" + testNum);
+        ok(false, "Uhh, unhandled switch for testNum #" + testNumber);
         break;
     }
 
     didDialog = true;
 
     if (!doNothing) {
         SpecialPowers.addObserver(outerWindowObserver, "outer-window-destroyed", false);
         if (clickOK)
             dialog.acceptDialog();
         else
             dialog.cancelDialog();
     }
 
-    ok(true, "handleDialog done for test " + testNum);
+    ok(true, "handleDialog done for test " + testNumber);
 
-    if (testNum == 4)
+    if (testNumber == 4)
         checkTest4A();
 }
 
 var outerWindowObserver = {
   observe: function(id) {
     SpecialPowers.removeObserver(outerWindowObserver, "outer-window-destroyed");
     var func;
     if (testNum == 1)
--- a/toolkit/components/passwordmgr/test/test_prompt_async.html
+++ b/toolkit/components/passwordmgr/test/test_prompt_async.html
@@ -184,31 +184,31 @@
                 doCheck(testNum);
                 monitor.reset();
 
                 testNum++;
                 doTest(testNum);
             }
         }
 
-        function doTest(testNum)
+        function doTest(testNumber)
         {
             /*
              * These contentDocument variables are located here,
              * rather than in the global scope, because SpecialPowers threw
              * errors (complaining that the objects were deleted)
              * when these were in the global scope.
              */
             var iframe1Doc = SpecialPowers.wrap(iframe1).contentDocument;
             var iframe2aDoc = SpecialPowers.wrap(iframe2a).contentDocument;
             var iframe2bDoc = SpecialPowers.wrap(iframe2b).contentDocument;
             var exampleCom = "http://example.com/tests/toolkit/components/passwordmgr/test/";
             var exampleOrg = "http://example.org/tests/toolkit/components/passwordmgr/test/";
 
-            switch (testNum)
+            switch (testNumber)
             {
             case 1:
                 // Load through a single proxy with authentication required 3 different
                 // pages, first with one login, other two with their own different login.
                 // We expect to show just a single dialog for proxy authentication and
                 // then two dialogs to authenticate to login 1 and then login 2.
                 ok(true, "doTest testNum 1");
                 expectedLoads = 3;
@@ -351,21 +351,21 @@
             case 9:
                 finishTest();
                 return;
             }
 
             startCallbackTimer();
         }
 
-        function handleDialog(doc, testNum)
+        function handleDialog(doc, testNumber)
         {
             var dialog        = doc.getElementById("commonDialog");
 
-            switch (testNum)
+            switch (testNumber)
             {
                 case 1:
                 case 2:
                     dialog.acceptDialog();
                     break;
 
                 case 3:
                     dialog.cancelDialog();
@@ -398,32 +398,32 @@
                 case 8:
                     if (expectedDialogs == 3 || expectedDialogs == 1)
                         dialog.acceptDialog();
                     else
                         dialog.cancelDialog();
                     break;
 
                 default:
-                    ok(false, "Unhandled testNum " + testNum + " in handleDialog");
+                    ok(false, "Unhandled testNum " + testNumber + " in handleDialog");
             }
 
             if (--expectedDialogs > 0)
                 startCallbackTimer();
         }
 
-        function doCheck(testNum)
+        function doCheck(testNumber)
         {
             var iframe1Doc = SpecialPowers.wrap(iframe1).contentDocument;
             var iframe2aDoc = SpecialPowers.wrap(iframe2a).contentDocument;
             var iframe2bDoc = SpecialPowers.wrap(iframe2b).contentDocument;
             var authok1;
             var proxyok1;
             var footnote;
-            switch (testNum)
+            switch (testNumber)
             {
                 case 1:
                     ok(true, "doCheck testNum 1");
                     is(monitor.windowsRegistered, 3, "Registered 3 open dialogs");
 
                     authok1 = iframe1Doc.getElementById("ok").textContent;
                     proxyok1 = iframe1Doc.getElementById("proxy").textContent;
 
@@ -521,17 +521,17 @@
 
                     is(authok1, "PASS", "WWW Authorization OK, frame1");
                     is(proxyok1, "PASS", "Proxy Authorization OK, frame1");
                     is(footnote, "This is a footnote after the huge content fill",
                         "Footnote present and loaded completely");
                     break;
 
                 default:
-                    ok(false, "Unhandled testNum " + testNum + " in doCheck");
+                    ok(false, "Unhandled testNum " + testNumber + " in doCheck");
             }
         }
 
     </script>
 </head>
 <body>
     <iframe id="iframe1"></iframe>
     <iframe id="iframe2a"></iframe>
--- a/toolkit/components/passwordmgr/test/unit/test_context_menu.js
+++ b/toolkit/components/passwordmgr/test/unit/test_context_menu.js
@@ -84,20 +84,20 @@ function createLoginsFragment(url, conte
   };
 }
 
 /**
  * Check if every login have it's corresponding menuitem.
  * Duplicates and empty usernames have a date appended.
  */
 function checkLoginItems(logins, items) {
-  function findDuplicates(loginList) {
+  function findDuplicates(unfilteredLoginList) {
     var seen = new Set();
     var duplicates = new Set();
-    for (let login of loginList) {
+    for (let login of unfilteredLoginList) {
       if (seen.has(login.username)) {
         duplicates.add(login.username);
       }
       seen.add(login.username);
     }
     return duplicates;
   }
   let duplicates = findDuplicates(logins);
--- a/toolkit/components/places/tests/bookmarks/test_bookmarks.js
+++ b/toolkit/components/places/tests/bookmarks/test_bookmarks.js
@@ -180,17 +180,17 @@ add_task(function* test_bookmarks() {
   let title = bs.getItemTitle(newId);
   do_check_eq(title, "Google");
 
   // test getItemType for bookmarks
   do_check_eq(bs.getItemType(newId), bs.TYPE_BOOKMARK);
 
   // get item title bad input
   try {
-    let title = bs.getItemTitle(-3);
+    bs.getItemTitle(-3);
     do_throw("getItemTitle accepted bad input");
   } catch (ex) {}
 
   // get the folder that the bookmark is in
   let folderId = bs.getFolderIdForItem(newId);
   do_check_eq(folderId, testRoot);
 
   // test getItemIndex for bookmarks
@@ -365,18 +365,18 @@ add_task(function* test_bookmarks() {
   } catch (ex) {
     do_throw("removeFolderChildren(): " + ex);
   }
 
   // XXX - test folderReadOnly
 
   // test bookmark id in query output
   try {
-    let options = hs.getNewQueryOptions();
-    let query = hs.getNewQuery();
+    options = hs.getNewQueryOptions();
+    query = hs.getNewQuery();
     query.setFolders([testRoot], 1);
     let result = hs.executeQuery(query, options);
     let rootNode = result.root;
     rootNode.containerOpen = true;
     let cc = rootNode.childCount;
     do_print("bookmark itemId test: CC = " + cc);
     do_check_true(cc > 0);
     for (let i=0; i < cc; ++i) {
@@ -404,18 +404,18 @@ add_task(function* test_bookmarks() {
     let mURI = uri("http://multiple.uris.in.query");
 
     let testFolder = bs.createFolder(testRoot, "test Folder", bs.DEFAULT_INDEX);
     // add 2 bookmarks
     bs.insertBookmark(testFolder, mURI, bs.DEFAULT_INDEX, "title 1");
     bs.insertBookmark(testFolder, mURI, bs.DEFAULT_INDEX, "title 2");
 
     // query
-    let options = hs.getNewQueryOptions();
-    let query = hs.getNewQuery();
+    options = hs.getNewQueryOptions();
+    query = hs.getNewQuery();
     query.setFolders([testFolder], 1);
     let result = hs.executeQuery(query, options);
     let rootNode = result.root;
     rootNode.containerOpen = true;
     let cc = rootNode.childCount;
     do_check_eq(cc, 2);
     do_check_eq(rootNode.getChild(0).title, "title 1");
     do_check_eq(rootNode.getChild(1).title, "title 2");
@@ -494,20 +494,20 @@ add_task(function* test_bookmarks() {
   anno.setItemAnnotation(newId3, "test-annotation", "foo", 0, 0);
   do_check_eq(bookmarksObserver._itemChangedId, newId3);
   do_check_eq(bookmarksObserver._itemChangedProperty, "test-annotation");
   do_check_true(bookmarksObserver._itemChanged_isAnnotationProperty);
   do_check_eq(bookmarksObserver._itemChangedValue, "");
 
   // test search on bookmark title ZZZXXXYYY
   try {
-    let options = hs.getNewQueryOptions();
+    options = hs.getNewQueryOptions();
     options.excludeQueries = 1;
     options.queryType = Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS;
-    let query = hs.getNewQuery();
+    query = hs.getNewQuery();
     query.searchTerms = "ZZZXXXYYY";
     let result = hs.executeQuery(query, options);
     let rootNode = result.root;
     rootNode.containerOpen = true;
     let cc = rootNode.childCount;
     do_check_eq(cc, 1);
     let node = rootNode.getChild(0);
     do_check_eq(node.title, "ZZZXXXYYY");
@@ -516,20 +516,20 @@ add_task(function* test_bookmarks() {
   }
   catch (ex) {
     do_throw("bookmarks query: " + ex);
   }
 
   // test dateAdded and lastModified properties
   // for a search query
   try {
-    let options = hs.getNewQueryOptions();
+    options = hs.getNewQueryOptions();
     options.excludeQueries = 1;
     options.queryType = Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS;
-    let query = hs.getNewQuery();
+    query = hs.getNewQuery();
     query.searchTerms = "ZZZXXXYYY";
     let result = hs.executeQuery(query, options);
     let rootNode = result.root;
     rootNode.containerOpen = true;
     let cc = rootNode.childCount;
     do_check_eq(cc, 1);
     let node = rootNode.getChild(0);
 
@@ -543,18 +543,18 @@ add_task(function* test_bookmarks() {
   }
   catch (ex) {
     do_throw("bookmarks query: " + ex);
   }
 
   // test dateAdded and lastModified properties
   // for a folder query
   try {
-    let options = hs.getNewQueryOptions();
-    let query = hs.getNewQuery();
+    options = hs.getNewQueryOptions();
+    query = hs.getNewQuery();
     query.setFolders([testRoot], 1);
     let result = hs.executeQuery(query, options);
     let rootNode = result.root;
     rootNode.containerOpen = true;
     let cc = rootNode.childCount;
     do_check_true(cc > 0);
     for (let i = 0; i < cc; i++) {
       let node = rootNode.getChild(i);
--- a/toolkit/components/places/tests/browser/browser_favicon_setAndFetchFaviconForPage.js
+++ b/toolkit/components/places/tests/browser/browser_favicon_setAndFetchFaviconForPage.js
@@ -131,22 +131,22 @@ function test() {
     // we can set the preference back to true immediately.  We don't clear the
     // preference because not all products enable Places by default.
     aWindow.Services.prefs.setBoolPref("places.history.enabled", true);
   }
 
   getIconFile(function () {
     testOnWindow({}, function(aWin) {
       testNormal(aWin, function () {
-        testOnWindow({}, function(aWin) {
-          testAboutURIBookmarked(aWin, function () {
-            testOnWindow({private: true}, function(aWin) {
-              testPrivateBrowsingBookmarked(aWin, function () {
-                testOnWindow({}, function(aWin) {
-                  testDisabledHistoryBookmarked(aWin, finish);
+        testOnWindow({}, function(aWin2) {
+          testAboutURIBookmarked(aWin2, function () {
+            testOnWindow({private: true}, function(aWin3) {
+              testPrivateBrowsingBookmarked(aWin3, function () {
+                testOnWindow({}, function(aWin4) {
+                  testDisabledHistoryBookmarked(aWin4, finish);
                 });
               });
             });
           });
         });
       });
     });
   });
--- a/toolkit/components/places/tests/browser/browser_favicon_setAndFetchFaviconForPage_failures.js
+++ b/toolkit/components/places/tests/browser/browser_favicon_setAndFetchFaviconForPage_failures.js
@@ -17,17 +17,16 @@ function test() {
   let favIcon16URI = NetUtil.newURI(favIcon16Location);
   let favIcon32URI = NetUtil.newURI(favIcon32Location);
   let lastPageURI = NetUtil.newURI("http://example.com/verification");
   // This error icon must stay in sync with FAVICON_ERRORPAGE_URL in
   // nsIFaviconService.idl, aboutCertError.xhtml and netError.xhtml.
   let favIconErrorPageURI =
     NetUtil.newURI("chrome://global/skin/icons/warning-16.png");
   let favIconsResultCount = 0;
-  let pageURI;
 
   function testOnWindow(aOptions, aCallback) {
     whenNewWindowLoaded(aOptions, function(aWin) {
       windowsToClose.push(aWin);
       executeSoon(() => aCallback(aWin));
     });
   }
 
@@ -223,30 +222,30 @@ function test() {
           aWindow.PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE, null,
           Services.scriptSecurityManager.getSystemPrincipal());
     });
   }
 
   checkFavIconsDBCount(function () {
     testOnWindow({}, function(aWin) {
       testNullPageURI(aWin, function () {
-        testOnWindow({}, function(aWin) {
-          testNullFavIconURI(aWin, function() {
-            testOnWindow({}, function(aWin) {
-              testAboutURI(aWin, function() {
-                testOnWindow({private: true}, function(aWin) {
-                  testPrivateBrowsingNonBookmarkedURI(aWin, function () {
-                    testOnWindow({}, function(aWin) {
-                      testDisabledHistory(aWin, function () {
-                        testOnWindow({}, function(aWin) {
-                          testErrorIcon(aWin, function() {
-                            testOnWindow({}, function(aWin) {
-                              testNonExistingPage(aWin, function() {
-                                testOnWindow({}, function(aWin) {
-                                  testFinalVerification(aWin, function() {
+        testOnWindow({}, function(aWin2) {
+          testNullFavIconURI(aWin2, function() {
+            testOnWindow({}, function(aWin3) {
+              testAboutURI(aWin3, function() {
+                testOnWindow({private: true}, function(aWin4) {
+                  testPrivateBrowsingNonBookmarkedURI(aWin4, function () {
+                    testOnWindow({}, function(aWin5) {
+                      testDisabledHistory(aWin5, function () {
+                        testOnWindow({}, function(aWin6) {
+                          testErrorIcon(aWin6, function() {
+                            testOnWindow({}, function(aWin7) {
+                              testNonExistingPage(aWin7, function() {
+                                testOnWindow({}, function(aWin8) {
+                                  testFinalVerification(aWin8, function() {
                                     finish();
                                   });
                                 });
                               });
                             });
                           });
                         });
                       });
--- a/toolkit/components/places/tests/browser/browser_redirect.js
+++ b/toolkit/components/places/tests/browser/browser_redirect.js
@@ -25,21 +25,21 @@ add_task(function* () {
         ok(this._redirectNotified, "The redirect should have been notified");
 
         fieldForUrl(REDIRECT_URI, "frecency", function (aFrecency) {
           ok(aFrecency != 0, "Frecency or the redirecting page should not be 0");
 
           fieldForUrl(REDIRECT_URI, "hidden", function (aHidden) {
             is(aHidden, 1, "The redirecting page should be hidden");
 
-            fieldForUrl(TARGET_URI, "frecency", function (aFrecency) {
-              ok(aFrecency != 0, "Frecency of the target page should not be 0");
+            fieldForUrl(TARGET_URI, "frecency", function (aFrecency2) {
+              ok(aFrecency2 != 0, "Frecency of the target page should not be 0");
 
-              fieldForUrl(TARGET_URI, "hidden", function (aHidden) {
-                is(aHidden, 0, "The target page should not be hidden");
+              fieldForUrl(TARGET_URI, "hidden", function (aHidden2) {
+                is(aHidden2, 0, "The target page should not be hidden");
                 resolve();
               });
             });
           });
         });
       },
       onBeginUpdateBatch: function () {},
       onEndUpdateBatch: function () {},
--- a/toolkit/components/places/tests/browser/browser_visituri_privatebrowsing_perwindowpb.js
+++ b/toolkit/components/places/tests/browser/browser_visituri_privatebrowsing_perwindowpb.js
@@ -59,16 +59,16 @@ function test() {
       aWin.close();
     });
   });
 
   // test first when on private mode
   testOnWindow({private: true}, function(aWin) {
     doTest(true, aWin, initialURL, function() {
       // then test when not on private mode
-      testOnWindow({}, function(aWin) {
-        doTest(false, aWin, finalURL, function () {
+      testOnWindow({}, function(aWin2) {
+        doTest(false, aWin2, finalURL, function () {
           PlacesTestUtils.clearHistory().then(finish);
         });
       });
     });
   });
 }
--- a/toolkit/components/places/tests/browser/head.js
+++ b/toolkit/components/places/tests/browser/head.js
@@ -283,17 +283,17 @@ function whenNewWindowLoaded(aOptions, a
  * @param aURI The URI.
  * @param aExpectedValue The expected value.
  * @return {Promise}
  * @resolves When the check has been added successfully.
  * @rejects JavaScript exception.
  */
 function promiseIsURIVisited(aURI, aExpectedValue) {
   return new Promise(resolve => {
-    PlacesUtils.asyncHistory.isURIVisited(aURI, function(aURI, aIsVisited) {
+    PlacesUtils.asyncHistory.isURIVisited(aURI, function(unused, aIsVisited) {
       resolve(aIsVisited);
     });
   });
 }
 
 function waitForCondition(condition, nextTest, errorMsg) {
   let tries = 0;
   let interval = setInterval(function() {
--- a/toolkit/components/places/tests/expiration/test_annos_expire_policy.js
+++ b/toolkit/components/places/tests/expiration/test_annos_expire_policy.js
@@ -77,21 +77,21 @@ function run_test() {
 
 add_task(function* test_annos_expire_policy() {
   // Set interval to a large value so we don't expire on it.
   setInterval(3600); // 1h
 
   // Expire all expirable pages.
   setMaxPages(0);
 
-  let now = getExpirablePRTime();
+  let now_specific_to_test = getExpirablePRTime();
   // Add some bookmarked page and timed annotations for each.
   for (let i = 0; i < 5; i++) {
     let pageURI = uri("http://item_anno." + i + ".mozilla.org/");
-    yield PlacesTestUtils.addVisits({ uri: pageURI, visitDate: now++ });
+    yield PlacesTestUtils.addVisits({ uri: pageURI, visitDate: now_specific_to_test++ });
     let bm = yield PlacesUtils.bookmarks.insert({
       parentGuid: PlacesUtils.bookmarks.unfiledGuid,
       url: pageURI,
       title: null
     });
     let id = yield PlacesUtils.promiseItemId(bm.guid);
     // Add a 6 days old anno.
     add_old_anno(id, "persist_days", "test", as.EXPIRE_DAYS, 6);
@@ -134,17 +134,17 @@ add_task(function* test_annos_expire_pol
     add_old_anno(pageURI, "persist_lm_months", "test", as.EXPIRE_MONTHS, 181, 179);
     // Add a 181 days old anno.
     add_old_anno(pageURI, "expire_months", "test", as.EXPIRE_MONTHS, 181);
   }
 
   // Add some visited page and timed annotations for each.
   for (let i = 0; i < 5; i++) {
     let pageURI = uri("http://page_anno." + i + ".mozilla.org/");
-    yield PlacesTestUtils.addVisits({ uri: pageURI, visitDate: now++ });
+    yield PlacesTestUtils.addVisits({ uri: pageURI, visitDate: now_specific_to_test++ });
     // Add a 6 days old anno.
     add_old_anno(pageURI, "persist_days", "test", as.EXPIRE_DAYS, 6);
     // Add a 8 days old anno, modified 5 days ago.
     add_old_anno(pageURI, "persist_lm_days", "test", as.EXPIRE_DAYS, 8, 6);
     // Add a 8 days old anno.
     add_old_anno(pageURI, "expire_days", "test", as.EXPIRE_DAYS, 8);
 
     // Add a 29 days old anno.
--- a/toolkit/components/places/tests/expiration/test_pref_interval.js
+++ b/toolkit/components/places/tests/expiration/test_pref_interval.js
@@ -36,18 +36,16 @@ var tests = [
 
   { desc: "Set interval to a large value.",
     interval: 100,
     expectedTimerDelay: 100
   },
 
 ];
 
-var currentTest;
-
 add_task(function* test() {
   // The pref should not exist by default.
   Assert.throws(() => getInterval());
 
   // Force the component, so it will start observing preferences.
   force_expiration_start();
 
   for (let currentTest of tests) {
--- a/toolkit/components/places/tests/head_common.js
+++ b/toolkit/components/places/tests/head_common.js
@@ -365,19 +365,19 @@ function check_no_bookmarks() {
  *
  * @return {Promise}
  * @resolves The array [aSubject, aData] from the observed notification.
  * @rejects Never.
  */
 function promiseTopicObserved(aTopic)
 {
   return new Promise(resolve => {
-    Services.obs.addObserver(function observe(aSubject, aTopic, aData) {
-      Services.obs.removeObserver(observe, aTopic);
-      resolve([aSubject, aData]);
+    Services.obs.addObserver(function observe(aObsSubject, aObsTopic, aObsData) {
+      Services.obs.removeObserver(observe, aObsTopic);
+      resolve([aObsSubject, aObsData]);
     }, aTopic, false);
   });
 }
 
 /**
  * Simulates a Places shutdown.
  */
 var shutdownPlaces = function() {
@@ -816,17 +816,17 @@ NavHistoryResultObserver.prototype = {
  * @param aURI The URI.
  * @return {Promise}
  * @resolves When the check has been added successfully.
  * @rejects JavaScript exception.
  */
 function promiseIsURIVisited(aURI) {
   let deferred = Promise.defer();
 
-  PlacesUtils.asyncHistory.isURIVisited(aURI, function(aURI, aIsVisited) {
+  PlacesUtils.asyncHistory.isURIVisited(aURI, function(unused, aIsVisited) {
     deferred.resolve(aIsVisited);
   });
 
   return deferred.promise;
 }
 
 /**
  * Asynchronously set the favicon associated with a page.
--- a/toolkit/components/places/tests/history/test_remove.js
+++ b/toolkit/components/places/tests/history/test_remove.js
@@ -39,27 +39,27 @@ add_task(function* test_remove_single() 
     }
 
     let shouldRemove = !options.addBookmark;
     let observer;
     let promiseObserved = new Promise((resolve, reject) => {
       observer = {
         onBeginUpdateBatch: function() {},
         onEndUpdateBatch: function() {},
-        onVisit: function(uri) {
-          reject(new Error("Unexpected call to onVisit " + uri.spec));
+        onVisit: function(aUri) {
+          reject(new Error("Unexpected call to onVisit " + aUri.spec));
         },
-        onTitleChanged: function(uri) {
-          reject(new Error("Unexpected call to onTitleChanged " + uri.spec));
+        onTitleChanged: function(aUri) {
+          reject(new Error("Unexpected call to onTitleChanged " + aUri.spec));
         },
         onClearHistory: function() {
           reject("Unexpected call to onClearHistory");
         },
-        onPageChanged: function(uri) {
-          reject(new Error("Unexpected call to onPageChanged " + uri.spec));
+        onPageChanged: function(aUri) {
+          reject(new Error("Unexpected call to onPageChanged " + aUri.spec));
         },
         onFrecencyChanged: function(aURI) {
           try {
             Assert.ok(!shouldRemove, "Observing onFrecencyChanged");
             Assert.equal(aURI.spec, uri.spec, "Observing effect on the right uri");
           } finally {
             resolve();
           }
--- a/toolkit/components/places/tests/queries/head_queries.js
+++ b/toolkit/components/places/tests/queries/head_queries.js
@@ -36,21 +36,21 @@ const olderthansixmonths = today - (DAY_
  * Generalized function to pull in an array of objects of data and push it into
  * the database.  It does NOT do any checking to see that the input is
  * appropriate.  This function is an asynchronous task, it can be called using
  * "Task.spawn" or using the "yield" function inside another task.
  */
 function* task_populateDB(aArray)
 {
   // Iterate over aArray and execute all instructions.
-  for (let data of aArray) {
+  for (let arrayItem of aArray) {
     try {
       // make the data object into a query data object in order to create proper
       // default values for anything left unspecified
-      var qdata = new queryData(data);
+      var qdata = new queryData(arrayItem);
       if (qdata.isVisit) {
         // Then we should add a visit for this node
         yield PlacesTestUtils.addVisits({
           uri: uri(qdata.uri),
           transition: qdata.transType,
           visitDate: qdata.lastVisit,
           referrer: qdata.referrer ? uri(qdata.referrer) : null,
           title: qdata.title
@@ -179,18 +179,18 @@ function* task_populateDB(aArray)
       if (qdata.isSeparator) {
         yield PlacesUtils.bookmarks.insert({
           parentGuid: qdata.parentGuid,
           type: PlacesUtils.bookmarks.TYPE_SEPARATOR,
           index: qdata.index
         });
       }
     } catch (ex) {
-      // use the data object here in case instantiation of qdata failed
-      do_print("Problem with this URI: " + data.uri);
+      // use the arrayItem object here in case instantiation of qdata failed
+      do_print("Problem with this URI: " + arrayItem.uri);
       do_throw("Error creating database: " + ex + "\n");
     }
   }
 }
 
 
 /**
  * The Query Data Object - this object encapsulates data for our queries and is
--- a/toolkit/components/places/tests/queries/test_results-as-visit.js
+++ b/toolkit/components/places/tests/queries/test_results-as-visit.js
@@ -56,17 +56,17 @@ add_task(function* test_results_as_visit
    options.resultType = options.RESULTS_AS_VISIT;
 
    // Results
    var result = PlacesUtils.history.executeQuery(query, options);
    var root = result.root;
    root.containerOpen = true;
 
    do_print("Number of items in result set: " + root.childCount);
-   for (var i=0; i < root.childCount; ++i) {
+   for (let i=0; i < root.childCount; ++i) {
      do_print("result: " + root.getChild(i).uri + " Title: " + root.getChild(i).title);
    }
 
    // Check our inital result set
    compareArrayToResult(testData, root);
 
    // If that passes, check liveupdate
    // Add to the query set
--- a/toolkit/components/places/tests/unit/test_408221.js
+++ b/toolkit/components/places/tests/unit/test_408221.js
@@ -87,17 +87,17 @@ function ensure_tag_results(uris, search
   };
 
   input.onSearchComplete = function() {
     do_check_eq(numSearchesStarted, 1);
     do_check_eq(controller.searchStatus,
                 Ci.nsIAutoCompleteController.STATUS_COMPLETE_MATCH);
     do_check_eq(controller.matchCount, uris.length);
     let vals = [];
-    for (var i=0; i<controller.matchCount; i++) {
+    for (let i=0; i<controller.matchCount; i++) {
       // Keep the URL for later because order of tag results is undefined
       vals.push(controller.getValueAt(i));
       do_check_eq(controller.getStyleAt(i), "bookmark-tag");
     }
     // Sort the results then check if we have the right items
     vals.sort().forEach((val, i) => do_check_eq(val, uris[i].spec))
 
     if (current_test < (tests.length - 1)) {
--- a/toolkit/components/places/tests/unit/test_415757.js
+++ b/toolkit/components/places/tests/unit/test_415757.js
@@ -66,17 +66,17 @@ add_task(function* test_execute()
                                             testAnnoRetainedName,
                                             testAnnoRetainedValue, 0,
                                             PlacesUtils.annotations.EXPIRE_WITH_HISTORY);
 
   // remove pages from www.test.com
   PlacesUtils.history.removePagesFromHost("www.test.com", false);
 
   // check that all pages in www.test.com have been removed
-  for (var i = 0; i < TOTAL_SITES; i++) {
+  for (let i = 0; i < TOTAL_SITES; i++) {
     let site = "http://www.test.com/" + i + "/";
     let testURI = uri(site);
     do_check_false(uri_in_db(testURI));
   }
 
   // check that all pages in www.test-X.com have NOT been removed
   for (let i = 0; i < TOTAL_SITES; i++) {
     let site = "http://www.test-" + i + ".com/";
--- a/toolkit/components/places/tests/unit/test_async_transactions.js
+++ b/toolkit/components/places/tests/unit/test_async_transactions.js
@@ -446,32 +446,32 @@ add_task(function* test_new_bookmark() {
 });
 
 add_task(function* test_merge_create_folder_and_item() {
   let folder_info = createTestFolderInfo();
   let bm_info = { url: NetUtil.newURI("http://test_create_item_to_folder.com")
                 , title: "Test Bookmark"
                 , index: bmStartIndex };
 
-  let { folderTxn, bkmTxn } = yield PT.batch(function* () {
+  let [folderTxnResult, bkmTxnResult] = yield PT.batch(function* () {
     let folderTxn = PT.NewFolder(folder_info);
     folder_info.guid = bm_info.parentGuid = yield folderTxn.transact();
     let bkmTxn = PT.NewBookmark(bm_info);
     bm_info.guid = yield bkmTxn.transact();
-    return { folderTxn, bkmTxn };
+    return [folderTxn, bkmTxn];
   });
 
   let ensureDo = function* () {
-    ensureUndoState([[bkmTxn, folderTxn]], 0);
+    ensureUndoState([[bkmTxnResult, folderTxnResult]], 0);
     yield ensureItemsAdded(folder_info, bm_info);
     observer.reset();
   };
 
   let ensureUndo = () => {
-    ensureUndoState([[bkmTxn, folderTxn]], 1);
+    ensureUndoState([[bkmTxnResult, folderTxnResult]], 1);
     ensureItemsRemoved(folder_info, bm_info);
     observer.reset();
   };
 
   yield ensureDo();
   yield PT.undo();
   ensureUndo();
   yield PT.redo();
@@ -486,45 +486,45 @@ add_task(function* test_merge_create_fol
 add_task(function* test_move_items_to_folder() {
   let folder_a_info = createTestFolderInfo("Folder A");
   let bkm_a_info = { url: new URL("http://test_move_items.com")
                    , title: "Bookmark A" };
   let bkm_b_info = { url: NetUtil.newURI("http://test_move_items.com")
                    , title: "Bookmark B" };
 
   // Test moving items within the same folder.
-  let [folder_a_txn, bkm_a_txn, bkm_b_txn] = yield PT.batch(function* () {
+  let [folder_a_txn_result, bkm_a_txn_result, bkm_b_txn_result] = yield PT.batch(function* () {
     let folder_a_txn = PT.NewFolder(folder_a_info);
 
     folder_a_info.guid = bkm_a_info.parentGuid = bkm_b_info.parentGuid =
       yield folder_a_txn.transact();
     let bkm_a_txn = PT.NewBookmark(bkm_a_info);
     bkm_a_info.guid = yield bkm_a_txn.transact();
     let bkm_b_txn = PT.NewBookmark(bkm_b_info);
     bkm_b_info.guid = yield bkm_b_txn.transact();
     return [folder_a_txn, bkm_a_txn, bkm_b_txn];
   });
 
-  ensureUndoState([[bkm_b_txn, bkm_a_txn, folder_a_txn]], 0);
+  ensureUndoState([[bkm_b_txn_result, bkm_a_txn_result, folder_a_txn_result]], 0);
 
   let moveTxn = PT.Move({ guid:          bkm_a_info.guid
                         , newParentGuid: folder_a_info.guid });
   yield moveTxn.transact();
 
   let ensureDo = () => {
-    ensureUndoState([[moveTxn], [bkm_b_txn, bkm_a_txn, folder_a_txn]], 0);
+    ensureUndoState([[moveTxn], [bkm_b_txn_result, bkm_a_txn_result, folder_a_txn_result]], 0);
     ensureItemsMoved({ guid:          bkm_a_info.guid
                      , oldParentGuid: folder_a_info.guid
                      , newParentGuid: folder_a_info.guid
                      , oldIndex:      0
                      , newIndex:      1 });
     observer.reset();
   };
   let ensureUndo = () => {
-    ensureUndoState([[moveTxn], [bkm_b_txn, bkm_a_txn, folder_a_txn]], 1);
+    ensureUndoState([[moveTxn], [bkm_b_txn_result, bkm_a_txn_result, folder_a_txn_result]], 1);
     ensureItemsMoved({ guid:          bkm_a_info.guid
                      , oldParentGuid: folder_a_info.guid
                      , newParentGuid: folder_a_info.guid
                      , oldIndex:      1
                      , newIndex:      0 });
     observer.reset();
   };
 
@@ -532,45 +532,45 @@ add_task(function* test_move_items_to_fo
   yield PT.undo();
   ensureUndo();
   yield PT.redo();
   ensureDo();
   yield PT.undo();
   ensureUndo();
 
   yield PT.clearTransactionsHistory(false, true);
-  ensureUndoState([[bkm_b_txn, bkm_a_txn, folder_a_txn]], 0);
+  ensureUndoState([[bkm_b_txn_result, bkm_a_txn_result, folder_a_txn_result]], 0);
 
   // Test moving items between folders.
   let folder_b_info = createTestFolderInfo("Folder B");
   let folder_b_txn = PT.NewFolder(folder_b_info);
   folder_b_info.guid = yield folder_b_txn.transact();
   ensureUndoState([ [folder_b_txn]
-                  , [bkm_b_txn, bkm_a_txn, folder_a_txn] ], 0);
+                  , [bkm_b_txn_result, bkm_a_txn_result, folder_a_txn_result] ], 0);
 
   moveTxn = PT.Move({ guid:          bkm_a_info.guid
                     , newParentGuid: folder_b_info.guid
                     , newIndex:      bmsvc.DEFAULT_INDEX });
   yield moveTxn.transact();
 
   ensureDo = () => {
     ensureUndoState([ [moveTxn]
                     , [folder_b_txn]
-                    , [bkm_b_txn, bkm_a_txn, folder_a_txn] ], 0);
+                    , [bkm_b_txn_result, bkm_a_txn_result, folder_a_txn_result] ], 0);
     ensureItemsMoved({ guid:          bkm_a_info.guid
                      , oldParentGuid: folder_a_info.guid
                      , newParentGuid: folder_b_info.guid
                      , oldIndex:      0
                      , newIndex:      0 });
     observer.reset();
   };
   ensureUndo = () => {
     ensureUndoState([ [moveTxn]
                     , [folder_b_txn]
-                    , [bkm_b_txn, bkm_a_txn, folder_a_txn] ], 1);
+                    , [bkm_b_txn_result, bkm_a_txn_result, folder_a_txn_result] ], 1);
     ensureItemsMoved({ guid:          bkm_a_info.guid
                      , oldParentGuid: folder_b_info.guid
                      , newParentGuid: folder_a_info.guid
                      , oldIndex:      0
                      , newIndex:      0 });
     observer.reset();
   };
 
@@ -583,101 +583,101 @@ add_task(function* test_move_items_to_fo
   ensureUndo();
 
   // Clean up
   yield PT.undo();  // folder_b_txn
   yield PT.undo();  // folder_a_txn + the bookmarks;
   do_check_eq(observer.itemsRemoved.size, 4);
   ensureUndoState([ [moveTxn]
                   , [folder_b_txn]
-                  , [bkm_b_txn, bkm_a_txn, folder_a_txn] ], 3);
+                  , [bkm_b_txn_result, bkm_a_txn_result, folder_a_txn_result] ], 3);
   yield PT.clearTransactionsHistory();
   ensureUndoState();
 });
 
 add_task(function* test_remove_folder() {
   let folder_level_1_info = createTestFolderInfo("Folder Level 1");
   let folder_level_2_info = { title: "Folder Level 2" };
-  let [folder_level_1_txn,
-       folder_level_2_txn] = yield PT.batch(function* () {
+  let [folder_level_1_txn_result,
+       folder_level_2_txn_result] = yield PT.batch(function* () {
     let folder_level_1_txn  = PT.NewFolder(folder_level_1_info);
     folder_level_1_info.guid = yield folder_level_1_txn.transact();
     folder_level_2_info.parentGuid = folder_level_1_info.guid;
     let folder_level_2_txn = PT.NewFolder(folder_level_2_info);
     folder_level_2_info.guid = yield folder_level_2_txn.transact();
     return [folder_level_1_txn, folder_level_2_txn];
   });
 
-  ensureUndoState([[folder_level_2_txn, folder_level_1_txn]]);
+  ensureUndoState([[folder_level_2_txn_result, folder_level_1_txn_result]]);
   yield ensureItemsAdded(folder_level_1_info, folder_level_2_info);
   observer.reset();
 
   let remove_folder_2_txn = PT.Remove(folder_level_2_info);
   yield remove_folder_2_txn.transact();
 
   ensureUndoState([ [remove_folder_2_txn]
-                  , [folder_level_2_txn, folder_level_1_txn] ]);
+                  , [folder_level_2_txn_result, folder_level_1_txn_result] ]);
   yield ensureItemsRemoved(folder_level_2_info);
 
   // Undo Remove "Folder Level 2"
   yield PT.undo();
   ensureUndoState([ [remove_folder_2_txn]
-                  , [folder_level_2_txn, folder_level_1_txn] ], 1);
+                  , [folder_level_2_txn_result, folder_level_1_txn_result] ], 1);
   yield ensureItemsAdded(folder_level_2_info);
   ensureTimestampsUpdated(folder_level_2_info.guid, true);
   observer.reset();
 
   // Redo Remove "Folder Level 2"
   yield PT.redo();
   ensureUndoState([ [remove_folder_2_txn]
-                  , [folder_level_2_txn, folder_level_1_txn] ]);
+                  , [folder_level_2_txn_result, folder_level_1_txn_result] ]);
   yield ensureItemsRemoved(folder_level_2_info);
   observer.reset();
 
   // Undo it again
   yield PT.undo();
   ensureUndoState([ [remove_folder_2_txn]
-                  , [folder_level_2_txn, folder_level_1_txn] ], 1);
+                  , [folder_level_2_txn_result, folder_level_1_txn_result] ], 1);
   yield ensureItemsAdded(folder_level_2_info);
   ensureTimestampsUpdated(folder_level_2_info.guid, true);
   observer.reset();
 
   // Undo the creation of both folders
   yield PT.undo();
   ensureUndoState([ [remove_folder_2_txn]
-                  , [folder_level_2_txn, folder_level_1_txn] ], 2);
+                  , [folder_level_2_txn_result, folder_level_1_txn_result] ], 2);
   yield ensureItemsRemoved(folder_level_2_info, folder_level_1_info);
   observer.reset();
 
   // Redo the creation of both folders
   yield PT.redo();
   ensureUndoState([ [remove_folder_2_txn]
-                  , [folder_level_2_txn, folder_level_1_txn] ], 1);
+                  , [folder_level_2_txn_result, folder_level_1_txn_result] ], 1);
   yield ensureItemsAdded(folder_level_1_info, folder_level_2_info);
   ensureTimestampsUpdated(folder_level_1_info.guid, true);
   ensureTimestampsUpdated(folder_level_2_info.guid, true);
   observer.reset();
 
   // Redo Remove "Folder Level 2"
   yield PT.redo();
   ensureUndoState([ [remove_folder_2_txn]
-                  , [folder_level_2_txn, folder_level_1_txn] ]);
+                  , [folder_level_2_txn_result, folder_level_1_txn_result] ]);
   yield ensureItemsRemoved(folder_level_2_info);
   observer.reset();
 
   // Undo everything one last time
   yield PT.undo();
   ensureUndoState([ [remove_folder_2_txn]
-                  , [folder_level_2_txn, folder_level_1_txn] ], 1);
+                  , [folder_level_2_txn_result, folder_level_1_txn_result] ], 1);
   yield ensureItemsAdded(folder_level_2_info);
   observer.reset();
 
   yield PT.undo();
   ensureUndoState([ [remove_folder_2_txn]
-                  , [folder_level_2_txn, folder_level_1_txn] ], 2);
+                  , [folder_level_2_txn_result, folder_level_1_txn_result] ], 2);
   yield ensureItemsRemoved(folder_level_2_info, folder_level_2_info);
   observer.reset();
 
   yield PT.clearTransactionsHistory();
   ensureUndoState();
 });
 
 add_task(function* test_add_and_remove_bookmarks_with_additional_info() {
--- a/toolkit/components/places/tests/unit/test_bookmarks_html.js
+++ b/toolkit/components/places/tests/unit/test_bookmarks_html.js
@@ -199,17 +199,17 @@ add_task(function* test_import_chromefav
     PlacesUtils.favicons.setAndFetchFaviconForPage(
       PAGE_URI, CHROME_FAVICON_URI, true,
       PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
       resolve, Services.scriptSecurityManager.getSystemPrincipal());
   });
 
   let data = yield new Promise(resolve => {
     PlacesUtils.favicons.getFaviconDataForPage(
-      PAGE_URI, (uri, dataLen, data, mimeType) => resolve(data));
+      PAGE_URI, (uri, dataLen, faviconData, mimeType) => resolve(faviconData));
   });
 
   let base64Icon = "data:image/png;base64," +
       base64EncodeString(String.fromCharCode.apply(String, data));
 
   test_bookmarks.unfiled.push(
     { title: "Test", url: PAGE_URI.spec, icon: base64Icon });
 
--- a/toolkit/components/places/tests/unit/test_bookmarks_html_corrupt.js
+++ b/toolkit/components/places/tests/unit/test_bookmarks_html_corrupt.js
@@ -26,17 +26,17 @@ add_task(function* test_corrupt_file() {
   yield database_check();
 });
 
 add_task(function* test_corrupt_database() {
   // Create corruption in the database, then export.
   let corruptBookmark = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.toolbarGuid,
                                                              url: "http://test.mozilla.org",
                                                              title: "We love belugas" });
-  let db = yield PlacesUtils.withConnectionWrapper("test", Task.async(function*(db) {
+  yield PlacesUtils.withConnectionWrapper("test", Task.async(function*(db) {
     yield db.execute("UPDATE moz_bookmarks SET fk = NULL WHERE guid = :guid",
                      { guid: corruptBookmark.guid });
   }));
 
   let bookmarksFile = OS.Path.join(OS.Constants.Path.profileDir, "bookmarks.exported.html");
   if ((yield OS.File.exists(bookmarksFile)))
     yield OS.File.remove(bookmarksFile);
   yield BookmarkHTMLUtils.exportToFile(bookmarksFile);
--- a/toolkit/components/places/tests/unit/test_download_history.js
+++ b/toolkit/components/places/tests/unit/test_download_history.js
@@ -80,18 +80,18 @@ add_test(function test_dh_is_from_places
 add_test(function test_dh_addRemoveDownload()
 {
   waitForOnVisit(function DHAD_onVisit(aURI) {
     do_check_true(aURI.equals(DOWNLOAD_URI));
 
     // Verify that the URI is already available in results at this time.
     do_check_true(!!page_in_database(DOWNLOAD_URI));
 
-    waitForOnDeleteURI(function DHRAD_onDeleteURI(aURI) {
-      do_check_true(aURI.equals(DOWNLOAD_URI));
+    waitForOnDeleteURI(function DHRAD_onDeleteURI(aDeletedURI) {
+      do_check_true(aDeletedURI.equals(DOWNLOAD_URI));
 
       // Verify that the URI is already available in results at this time.
       do_check_false(!!page_in_database(DOWNLOAD_URI));
 
       run_next_test();
     });
     gDownloadHistory.removeAllDownloads();
   });
@@ -104,18 +104,18 @@ add_test(function test_dh_addMultiRemove
   PlacesTestUtils.addVisits({
     uri: DOWNLOAD_URI,
     transition: TRANSITION_TYPED
   }).then(function () {
     waitForOnVisit(function DHAD_onVisit(aURI) {
       do_check_true(aURI.equals(DOWNLOAD_URI));
       do_check_true(!!page_in_database(DOWNLOAD_URI));
 
-      waitForOnDeleteVisits(function DHRAD_onDeleteVisits(aURI) {
-        do_check_true(aURI.equals(DOWNLOAD_URI));
+      waitForOnDeleteVisits(function DHRAD_onDeleteVisits(aDeletedURI) {
+        do_check_true(aDeletedURI.equals(DOWNLOAD_URI));
         do_check_true(!!page_in_database(DOWNLOAD_URI));
 
         PlacesTestUtils.clearHistory().then(run_next_test);
       });
       gDownloadHistory.removeAllDownloads();
     });
 
     gDownloadHistory.addDownload(DOWNLOAD_URI, null, Date.now() * 1000);
@@ -127,37 +127,37 @@ add_test(function test_dh_addBookmarkRem
   PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
                                        DOWNLOAD_URI,
                                        PlacesUtils.bookmarks.DEFAULT_INDEX,
                                        "A bookmark");
   waitForOnVisit(function DHAD_onVisit(aURI) {
     do_check_true(aURI.equals(DOWNLOAD_URI));
     do_check_true(!!page_in_database(DOWNLOAD_URI));
 
-    waitForOnDeleteVisits(function DHRAD_onDeleteVisits(aURI) {
-      do_check_true(aURI.equals(DOWNLOAD_URI));
+    waitForOnDeleteVisits(function DHRAD_onDeleteVisits(aDeletedURI) {
+      do_check_true(aDeletedURI.equals(DOWNLOAD_URI));
       do_check_true(!!page_in_database(DOWNLOAD_URI));
 
       PlacesTestUtils.clearHistory().then(run_next_test);
     });
     gDownloadHistory.removeAllDownloads();
   });
 
   gDownloadHistory.addDownload(DOWNLOAD_URI, null, Date.now() * 1000);
 });
 
 add_test(function test_dh_addDownload_referrer()
 {
   waitForOnVisit(function DHAD_prepareReferrer(aURI, aVisitID) {
     do_check_true(aURI.equals(REFERRER_URI));
     let referrerVisitId = aVisitID;
 
-    waitForOnVisit(function DHAD_onVisit(aURI, aVisitID, aTime, aSessionID,
-                                              aReferringID) {
-      do_check_true(aURI.equals(DOWNLOAD_URI));
+    waitForOnVisit(function DHAD_onVisit(aVisitedURI, unused, unused2, unused3,
+                                         aReferringID) {
+      do_check_true(aVisitedURI.equals(DOWNLOAD_URI));
       do_check_eq(aReferringID, referrerVisitId);
 
       // Verify that the URI is already available in results at this time.
       do_check_true(!!page_in_database(DOWNLOAD_URI));
 
       PlacesTestUtils.clearHistory().then(run_next_test);
     });
 
--- a/toolkit/components/places/tests/unit/test_getPlacesInfo.js
+++ b/toolkit/components/places/tests/unit/test_getPlacesInfo.js
@@ -57,17 +57,17 @@ add_task(test_getPlacesInfoNonExistentPl
 function* test_promisedHelper() {
   let uri = NetUtil.newURI("http://www.helper_existent_example.tld");
   yield PlacesTestUtils.addVisits(uri);
   let placeInfo = yield PlacesUtils.promisePlaceInfo(uri);
   do_check_true(placeInfo instanceof Ci.mozIPlaceInfo);
 
   uri = NetUtil.newURI("http://www.helper_non_existent_example.tld");
   try {
-    let placeInfo = yield PlacesUtils.promisePlaceInfo(uri);
+    yield PlacesUtils.promisePlaceInfo(uri);
     do_throw("PlacesUtils.promisePlaceInfo should have rejected the promise");
   }
   catch (ex) { }
 }
 add_task(test_promisedHelper);
 
 function* test_infoByGUID() {
   let testURI = NetUtil.newURI("http://www.guid_example.tld");
--- a/toolkit/components/places/tests/unit/test_history_autocomplete_tags.js
+++ b/toolkit/components/places/tests/unit/test_history_autocomplete_tags.js
@@ -90,17 +90,17 @@ function ensure_tag_results(uris, search
   input.onSearchComplete = function() {
     do_check_eq(numSearchesStarted, 1);
     do_check_eq(controller.searchStatus,
                 uris.length ?
                 Ci.nsIAutoCompleteController.STATUS_COMPLETE_MATCH :
                 Ci.nsIAutoCompleteController.STATUS_COMPLETE_NO_MATCH);
     do_check_eq(controller.matchCount, uris.length);
     let vals = [];
-    for (var i=0; i<controller.matchCount; i++) {
+    for (let i=0; i<controller.matchCount; i++) {
       // Keep the URL for later because order of tag results is undefined
       vals.push(controller.getValueAt(i));
       do_check_eq(controller.getStyleAt(i), "bookmark-tag");
     }
     // Sort the results then check if we have the right items
     vals.sort().forEach((val, i) => do_check_eq(val, uris[i].spec))
 
     if (current_test < (tests.length - 1)) {
--- a/toolkit/components/places/tests/unit/test_isURIVisited.js
+++ b/toolkit/components/places/tests/unit/test_isURIVisited.js
@@ -49,25 +49,25 @@ function* step()
         do_check_false(aIsVisited);
 
         let callback = {
           handleError:  function () {},
           handleResult: function () {},
           handleCompletion: function () {
             do_print("Added visit to " + uri.spec);
 
-            history.isURIVisited(uri, function (aURI, aIsVisited) {
-              do_check_true(uri.equals(aURI));
+            history.isURIVisited(uri, function (aURI2, aIsVisited2) {
+              do_check_true(uri.equals(aURI2));
               let checker = SCHEMES[scheme] ? do_check_true : do_check_false;
-              checker(aIsVisited);
+              checker(aIsVisited2);
 
               PlacesTestUtils.clearHistory().then(function () {
-                history.isURIVisited(uri, function(aURI, aIsVisited) {
-                  do_check_true(uri.equals(aURI));
-                  do_check_false(aIsVisited);
+                history.isURIVisited(uri, function(aURI3, aIsVisited3) {
+                  do_check_true(uri.equals(aURI3));
+                  do_check_false(aIsVisited3);
                   gRunner.next();
                 });
               });
             });
           },
         };
 
         history.updatePlaces({ uri:    uri
--- a/toolkit/components/satchel/test/test_form_autocomplete.html
+++ b/toolkit/components/satchel/test/test_form_autocomplete.html
@@ -1047,21 +1047,21 @@ function waitForScroll()
   }, false);
 }
 
 function waitForMenuChange(expectedCount, expectedFirstValue)
 {
     notifyMenuChanged(expectedCount, expectedFirstValue, runTest);
 }
 
-function checkMenuEntries(expectedValues, testNum) {
+function checkMenuEntries(expectedValues, testNumber) {
     var actualValues = getMenuEntries();
-    is(actualValues.length, expectedValues.length, testNum + " Checking length of expected menu");
+    is(actualValues.length, expectedValues.length, testNumber + " Checking length of expected menu");
     for (var i = 0; i < expectedValues.length; i++)
-        is(actualValues[i], expectedValues[i], testNum + " Checking menu entry #"+i);
+        is(actualValues[i], expectedValues[i], testNumber + " Checking menu entry #"+i);
 }
 
 function startTest() {
     setupFormHistory(function() {
         runTest();
     });
 }
 
--- a/toolkit/components/satchel/test/test_form_autocomplete_with_list.html
+++ b/toolkit/components/satchel/test/test_form_autocomplete_with_list.html
@@ -481,21 +481,21 @@ function runTest() {
       return;
     }
 }
 
 function waitForMenuChange(expectedCount) {
     notifyMenuChanged(expectedCount, null, runTest);
 }
 
-function checkMenuEntries(expectedValues, testNum) {
+function checkMenuEntries(expectedValues, testNumber) {
     var actualValues = getMenuEntries();
-    is(actualValues.length, expectedValues.length, testNum + " Checking length of expected menu");
+    is(actualValues.length, expectedValues.length, testNumber + " Checking length of expected menu");
     for (var i = 0; i < expectedValues.length; i++)
-        is(actualValues[i], expectedValues[i], testNum + " Checking menu entry #"+i);
+        is(actualValues[i], expectedValues[i], testNumber + " Checking menu entry #"+i);
 }
 
 function startTest() {
     setupFormHistory(runTest);
 }
 
 window.onload = startTest;
 
--- a/toolkit/components/satchel/test/test_form_submission.html
+++ b/toolkit/components/satchel/test/test_form_submission.html
@@ -95,34 +95,34 @@
     <input type="text" name="test1">
     <button type="submit">Submit</button>
   </form>
 
   <!-- input with sensitive data (16 digit credit card number) -->
   <form id="form15" onsubmit="return checkSubmit(15)">
     <script type="text/javascript">
       var form = document.getElementById('form15');
-      for (var i = 0; i != 10; i++)
+      for (let i = 0; i != 10; i++)
       {
-        var input = document.createElement('input');
+        let input = document.createElement('input');
         input.type = 'text';
         input.name = 'test' + (i + 1);
         form.appendChild(input);
       }
     </script>
     <button type="submit">Submit</button>
   </form>
 
   <!-- input with sensitive data (15 digit credit card number) -->
   <form id="form16" onsubmit="return checkSubmit(16)">
     <script type="text/javascript">
       form = document.getElementById('form16');
-      for (i = 0; i != 10; i++)
+      for (let i = 0; i != 10; i++)
       {
-        input = document.createElement('input');
+        let input = document.createElement('input');
         input.type = 'text';
         input.name = 'test' + (i + 1);
         form.appendChild(input);
       }
     </script>
     <button type="submit">Submit</button>
   </form>
 
@@ -212,35 +212,35 @@
     <button type="submit">Submit</button>
   </form>
 
   <!-- input that looks like sensitive data but doesn't
        satisfy the requirements (Luhn check fails for 16 chars) -->
   <form id="form107" onsubmit="return checkSubmit(107)">
     <script type="text/javascript">
       form = document.getElementById('form107');
-      for (i = 0; i != 10; i++)
+      for (let i = 0; i != 10; i++)
       {
-        input = document.createElement('input');
+        let input = document.createElement('input');
         input.type = 'text';
         input.name = 'test7_' + (i + 1);
         form.appendChild(input);
       }
     </script>
     <button type="submit">Submit</button>
   </form>
 
   <!-- input that looks like sensitive data but doesn't
        satisfy the requirements (Luhn check fails for 15 chars) -->
   <form id="form108" onsubmit="return checkSubmit(108)">
     <script type="text/javascript">
       form = document.getElementById('form108');
-      for (i = 0; i != 10; i++)
+      for (let i = 0; i != 10; i++)
       {
-        input = document.createElement('input');
+        let input = document.createElement('input');
         input.type = 'text';
         input.name = 'test8_' + (i + 1);
         form.appendChild(input);
       }
     </script>
     <button type="submit">Submit</button>
   </form>
 
@@ -308,34 +308,34 @@ function startTest() {
   $_(1, "test1").value = "dontSaveThis";
   $_(2, "test1").value = "dontSaveThis";
   $_(3, "test1").value = "dontSaveThis";
   $_(4, "test1").value = "dontSaveThis";
   $_(5, "test1").value = "";
   $_(6, "test1").value = "dontSaveThis";
   // Form 7 deliberately left untouched.
   // Form 8 has an input with no name or input attribute.
-  var input = document.getElementById("form8").elements[0];
+  let input = document.getElementById("form8").elements[0];
   is(input.type, "text", "checking we got unidentified input");
   input.value = "dontSaveThis";
   // Form 9 has nothing to modify.
   $_(10, "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890").value = "dontSaveThis";
   $_(11, "test1").value = "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";
   $_(12, "test1").value = " ";
   $_(13, "test1").value = "dontSaveThis";
   $_(14, "test1").type  = "password";
   $_(14, "test1").value = "dontSaveThis";
 
   var testData = ccNumbers.valid16;
-  for (var i = 0; i != testData.length; i++) {
+  for (let i = 0; i != testData.length; i++) {
     $_(15, "test" + (i + 1)).value = testData[i];
   }
 
   testData = ccNumbers.valid15;
-  for (i = 0; i != testData.length; i++) {
+  for (let i = 0; i != testData.length; i++) {
     $_(16, "test" + (i + 1)).value = testData[i];
   }
   $_(17, "test1").value = "001064088";
   $_(18, "test1").value = "0000-0000-0080-4609";
   $_(19, "test1").value = "0000 0000 0222 331";
   $_(20, "test1").value = "dontSaveThis";
   $_(22, "test1").value = "dontSaveThis";
   $_(23, "test1").value = "dontSaveThis";
@@ -344,22 +344,22 @@ function startTest() {
   $_(101, "test1").value = "savedValue";
   $_(102, "test2").value = "savedValue";
   $_(103, "test3").value = "savedValue";
   $_(104, "test4").value = " trimTrailingAndLeadingSpace ";
   $_(105, "test5").value = "\t trimTrailingAndLeadingWhitespace\t ";
   $_(106, "test6").value = "00000000109181";
 
   testData = ccNumbers.invalid16;
-  for (i = 0; i != testData.length; i++) {
+  for (let i = 0; i != testData.length; i++) {
     $_(107, "test7_" + (i + 1)).value = testData[i];
   }
 
   testData = ccNumbers.invalid15;
-  for (i = 0; i != testData.length; i++) {
+  for (let i = 0; i != testData.length; i++) {
     $_(108, "test8_" + (i + 1)).value = testData[i];
   }
 
   $_(109, "test9").value = "savedValue";
   $_(110, "test10").value = "savedValue";
 
   // submit the first form.
   var button = getFormSubmitButton(1);
@@ -424,22 +424,22 @@ function checkSubmit(formNum) {
         break;
     case 105:
         checkForSave("test5", "trimTrailingAndLeadingWhitespace", "checking saved value is trimmed on both sides");
         break;
     case 106:
         checkForSave("test6", "00000000109181", "checking saved value");
         break;
     case 107:
-        for (var i = 0; i != ccNumbers.invalid16.length; i++) {
+        for (let i = 0; i != ccNumbers.invalid16.length; i++) {
           checkForSave("test7_" + (i + 1), ccNumbers.invalid16[i], "checking saved value");
         }
         break;
     case 108:
-        for (i = 0; i != ccNumbers.invalid15.length; i++) {
+        for (let i = 0; i != ccNumbers.invalid15.length; i++) {
           checkForSave("test8_" + (i + 1), ccNumbers.invalid15[i], "checking saved value");
         }
         break;
     case 109:
         checkForSave("test9", "savedValue", "checking saved value");
         break;
     case 110:
         checkForSave("test10", "savedValue", "checking saved value");
--- a/toolkit/components/satchel/test/unit/test_autocomplete.js
+++ b/toolkit/components/satchel/test/unit/test_autocomplete.js
@@ -69,17 +69,17 @@ add_test(function test0() {
     }
 
     updateFormHistory(changes, run_next_test);
 });
 
 add_test(function test1() {
     do_log_info("Check initial state is as expected");
 
-    countEntries(null, null, function (count) {
+    countEntries(null, null, function () {
       countEntries("field1", null, function (count) {
         do_check_true(count > 0);
         run_next_test();
       });
     });
 });
 
 add_test(function test2() {
--- a/toolkit/components/telemetry/Histograms.json
+++ b/toolkit/components/telemetry/Histograms.json
@@ -3880,16 +3880,24 @@
   "URLCLASSIFIER_UPDATE_ERROR_TYPE": {
     "alert_emails": ["safebrowsing-telemetry@mozilla.org"],
     "expires_in_version": "58",
     "kind": "enumerated",
     "n_values": 10,
     "bug_numbers": [1305801],
     "description": "An error was encountered while parsing a partial update returned by a Safe Browsing V4 server (0 = addition of an already existing prefix, 1 = parser got into an infinite loop, 2 = removal index out of bounds, 3 = checksum mismatch, 4 = missing checksum)"
   },
+  "URLCLASSIFIER_PREFIX_MATCH": {
+    "alert_emails": ["safebrowsing-telemetry@mozilla.org"],
+    "expires_in_version": "58",
+    "kind": "enumerated",
+    "n_values": 4,
+    "bug_numbers": [1298257],
+    "description": "Classifier prefix matching result (0 = no match, 1 = match only V2, 2 = match only V4, 3 = match both V2 and V4)"
+  },
   "CSP_DOCUMENTS_COUNT": {
     "alert_emails": ["seceng@mozilla.com"],
     "bug_numbers": [1252829],
     "expires_in_version": "55",
     "kind": "count",
     "description": "Number of unique pages that contain a CSP"
   },
   "CSP_UNSAFE_INLINE_DOCUMENTS_COUNT": {
--- a/toolkit/components/url-classifier/Classifier.cpp
+++ b/toolkit/components/url-classifier/Classifier.cpp
@@ -15,16 +15,17 @@
 #include "nsNetCID.h"
 #include "nsPrintfCString.h"
 #include "nsThreadUtils.h"
 #include "mozilla/Telemetry.h"
 #include "mozilla/Logging.h"
 #include "mozilla/SyncRunnable.h"
 #include "mozilla/Base64.h"
 #include "mozilla/Unused.h"
+#include "mozilla/TypedEnumBits.h"
 
 // MOZ_LOG=UrlClassifierDbService:5
 extern mozilla::LazyLogModule gUrlClassifierDbServiceLog;
 #define LOG(args) MOZ_LOG(gUrlClassifierDbServiceLog, mozilla::LogLevel::Debug, args)
 #define LOG_ENABLED() MOZ_LOG_TEST(gUrlClassifierDbServiceLog, mozilla::LogLevel::Debug)
 
 #define STORE_DIRECTORY      NS_LITERAL_CSTRING("safebrowsing")
 #define TO_DELETE_DIR_SUFFIX NS_LITERAL_CSTRING("-to_delete")
@@ -471,16 +472,26 @@ Classifier::TableRequest(nsACString& aRe
   // Load meta data from *.metadata files in the root directory.
   // Specifically for v4 tables.
   nsCString metadata;
   nsresult rv = LoadMetadata(mRootStoreDirectory, metadata);
   NS_ENSURE_SUCCESS_VOID(rv);
   aResult.Append(metadata);
 }
 
+// This is used to record the matching statistics for v2 and v4.
+enum class PrefixMatch : uint8_t {
+  eNoMatch = 0x00,
+  eMatchV2Prefix = 0x01,
+  eMatchV4Prefix = 0x02,
+  eMatchBoth = eMatchV2Prefix | eMatchV4Prefix
+};
+
+MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS(PrefixMatch)
+
 nsresult
 Classifier::Check(const nsACString& aSpec,
                   const nsACString& aTables,
                   uint32_t aFreshnessGuarantee,
                   LookupResultArray& aResults)
 {
   Telemetry::AutoTimer<Telemetry::URLCLASSIFIER_CL_CHECK_TIME> timer;
 
@@ -500,31 +511,49 @@ Classifier::Check(const nsACString& aSpe
     LookupCache *cache = GetLookupCache(activeTables[i]);
     if (cache) {
       cacheArray.AppendElement(cache);
     } else {
       return NS_ERROR_FAILURE;
     }
   }
 
+  PrefixMatch matchingStatistics = PrefixMatch::eNoMatch;
+
   // Now check each lookup fragment against the entries in the DB.
   for (uint32_t i = 0; i < fragments.Length(); i++) {
     Completion lookupHash;
     lookupHash.FromPlaintext(fragments[i], mCryptoHash);
 
     if (LOG_ENABLED()) {
       nsAutoCString checking;
       lookupHash.ToHexString(checking);
       LOG(("Checking fragment %s, hash %s (%X)", fragments[i].get(),
            checking.get(), lookupHash.ToUint32()));
     }
 
     for (uint32_t i = 0; i < cacheArray.Length(); i++) {
       LookupCache *cache = cacheArray[i];
       bool has, complete;
+
+      if (LookupCache::Cast<LookupCacheV4>(cache)) {
+        // TODO Bug 1312339 Return length in LookupCache.Has and support
+        // VariableLengthPrefix in LookupResultArray
+        rv = cache->Has(lookupHash, &has, &complete);
+        if (NS_FAILED(rv)) {
+          LOG(("Failed to lookup fragment %s V4", fragments[i].get()));
+        }
+        if (has) {
+          matchingStatistics |= PrefixMatch::eMatchV4Prefix;
+          // TODO: Bug 1311935 - Implement Safe Browsing v4 caching
+          // Should check cache expired
+        }
+        continue;
+      }
+
       rv = cache->Has(lookupHash, &has, &complete);
       NS_ENSURE_SUCCESS(rv, rv);
       if (has) {
         LookupResult *result = aResults.AppendElement();
         if (!result)
           return NS_ERROR_OUT_OF_MEMORY;
 
         int64_t age;
@@ -540,19 +569,23 @@ Classifier::Check(const nsACString& aSpe
              cache->TableName().get(),
              complete ? "complete." : "Not complete.",
              age));
 
         result->hash.complete = lookupHash;
         result->mComplete = complete;
         result->mFresh = (age < aFreshnessGuarantee);
         result->mTableName.Assign(cache->TableName());
+
+        matchingStatistics |= PrefixMatch::eMatchV2Prefix;
       }
     }
 
+    Telemetry::Accumulate(Telemetry::URLCLASSIFIER_PREFIX_MATCH,
+                          static_cast<uint8_t>(matchingStatistics));
   }
 
   return NS_OK;
 }
 
 nsresult
 Classifier::ApplyUpdates(nsTArray<TableUpdate*>* aUpdates)
 {
--- a/toolkit/components/url-classifier/LookupCacheV4.cpp
+++ b/toolkit/components/url-classifier/LookupCacheV4.cpp
@@ -73,22 +73,38 @@ LookupCacheV4::Init()
 {
   mVLPrefixSet = new VariableLengthPrefixSet();
   nsresult rv = mVLPrefixSet->Init(mTableName);
   NS_ENSURE_SUCCESS(rv, rv);
 
   return NS_OK;
 }
 
-// TODO : Bug 1298257, Implement url matching for variable-length prefix set
 nsresult
 LookupCacheV4::Has(const Completion& aCompletion,
                    bool* aHas, bool* aComplete)
 {
   *aHas = false;
+
+  uint32_t length = 0;
+  nsDependentCSubstring fullhash;
+  fullhash.Rebind((const char *)aCompletion.buf, COMPLETE_SIZE);
+
+  nsresult rv = mVLPrefixSet->Matches(fullhash, &length);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  *aHas = length >= PREFIX_SIZE;
+  *aComplete = length == COMPLETE_SIZE;
+
+  if (LOG_ENABLED()) {
+    uint32_t prefix = aCompletion.ToUint32();
+    LOG(("Probe in V4 %s: %X, found %d, complete %d", mTableName.get(),
+          prefix, *aHas, *aComplete));
+  }
+
   return NS_OK;
 }
 
 nsresult
 LookupCacheV4::Build(PrefixStringMap& aPrefixMap)
 {
   return mVLPrefixSet->SetPrefixes(aPrefixMap);
 }
@@ -146,16 +162,27 @@ AppendPrefixToMap(PrefixStringMap& prefi
   if (!prefix.Length()) {
     return;
   }
 
   nsCString* prefixString = prefixes.LookupOrAdd(prefix.Length());
   prefixString->Append(prefix.BeginReading(), prefix.Length());
 }
 
+// Read prefix into a buffer and also update the hash which
+// keeps track of the checksum
+static void
+UpdateChecksum(nsICryptoHash* aCrypto, const nsACString& aPrefix)
+{
+  MOZ_ASSERT(aCrypto);
+  aCrypto->Update(reinterpret_cast<uint8_t*>(const_cast<char*>(
+                  aPrefix.BeginReading())),
+                  aPrefix.Length());
+}
+
 // Please see https://bug1287058.bmoattachments.org/attachment.cgi?id=8795366
 // for detail about partial update algorithm.
 nsresult
 LookupCacheV4::ApplyUpdate(TableUpdateV4* aTableUpdate,
                            PrefixStringMap& aInputMap,
                            PrefixStringMap& aOutputMap)
 {
   MOZ_ASSERT(aOutputMap.IsEmpty());
@@ -227,28 +254,22 @@ LookupCacheV4::ApplyUpdate(TableUpdateV4
 
       // If the number of picks from old map matches the removalIndex, then this prefix
       // will be removed by not merging it to new map.
       if (removalIndex < removalArray.Length() &&
           numOldPrefixPicked == removalArray[removalIndex]) {
         removalIndex++;
       } else {
         AppendPrefixToMap(aOutputMap, smallestOldPrefix);
-
-        crypto->Update(reinterpret_cast<uint8_t*>(const_cast<char*>(
-                       smallestOldPrefix.BeginReading())),
-                       smallestOldPrefix.Length());
+        UpdateChecksum(crypto, smallestOldPrefix);
       }
       smallestOldPrefix.SetLength(0);
     } else {
       AppendPrefixToMap(aOutputMap, smallestAddPrefix);
-
-      crypto->Update(reinterpret_cast<uint8_t*>(const_cast<char*>(
-                     smallestAddPrefix.BeginReading())),
-                     smallestAddPrefix.Length());
+      UpdateChecksum(crypto, smallestAddPrefix);
 
       smallestAddPrefix.SetLength(0);
     }
   }
 
   // We expect index will be greater to 0 because max number of runs will be
   // the number of original prefix plus add prefix.
   if (index <= 0) {
@@ -292,17 +313,17 @@ LookupCacheV4::InitCrypto(nsCOMPtr<nsICr
 {
   nsresult rv;
   aCrypto = do_CreateInstance(NS_CRYPTO_HASH_CONTRACTID, &rv);
   if (NS_WARN_IF(NS_FAILED(rv))) {
     return rv;
   }
 
   rv = aCrypto->Init(nsICryptoHash::SHA256);
-  Unused << NS_WARN_IF(NS_FAILED(rv));
+  NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "InitCrypto failed");
 
   return rv;
 }
 
 nsresult
 LookupCacheV4::VerifyChecksum(const nsACString& aChecksum)
 {
   nsCOMPtr<nsICryptoHash> crypto;
@@ -316,19 +337,17 @@ LookupCacheV4::VerifyChecksum(const nsAC
 
   VLPrefixSet loadPSet(map);
   uint32_t index = loadPSet.Count() + 1;
   for(;index > 0; index--) {
     nsDependentCSubstring prefix;
     if (!loadPSet.GetSmallestPrefix(prefix)) {
       break;
     }
-    crypto->Update(reinterpret_cast<uint8_t*>(const_cast<char*>(
-                   prefix.BeginReading())),
-                   prefix.Length());
+    UpdateChecksum(crypto, prefix);
   }
 
   nsAutoCString checksum;
   crypto->Finish(false, checksum);
 
   if (checksum != aChecksum) {
     LOG(("Checksum mismatch when loading prefixes from file."));
     return NS_ERROR_FILE_CORRUPTED;
--- a/toolkit/components/url-classifier/tests/gtest/Common.cpp
+++ b/toolkit/components/url-classifier/tests/gtest/Common.cpp
@@ -46,8 +46,22 @@ void ApplyUpdate(nsTArray<TableUpdate*>&
   });
 }
 
 void ApplyUpdate(TableUpdate* update)
 {
   nsTArray<TableUpdate*> updates = { update };
   ApplyUpdate(updates);
 }
+
+void
+PrefixArrayToPrefixStringMap(const nsTArray<nsCString>& prefixArray,
+                             PrefixStringMap& out)
+{
+  out.Clear();
+
+  for (uint32_t i = 0; i < prefixArray.Length(); i++) {
+    const nsCString& prefix = prefixArray[i];
+    nsCString* prefixString = out.LookupOrAdd(prefix.Length());
+    prefixString->Append(prefix.BeginReading(), prefix.Length());
+  }
+}
+
--- a/toolkit/components/url-classifier/tests/gtest/Common.h
+++ b/toolkit/components/url-classifier/tests/gtest/Common.h
@@ -14,8 +14,13 @@ void RunTestInNewThread(Function&& aFunc
 already_AddRefed<nsIFile>
 GetFile(const nsTArray<nsString>& path);
 
 // ApplyUpdate will call |ApplyUpdates| of Classifier within a new thread
 void ApplyUpdate(nsTArray<TableUpdate*>& updates);
 
 void ApplyUpdate(TableUpdate* update);
 
+// This function converts lexigraphic-sorted prefixes to a hashtable
+// which key is prefix size and value is concatenated prefix string.
+void PrefixArrayToPrefixStringMap(const nsTArray<nsCString>& prefixArray,
+                                  PrefixStringMap& out);
+
new file mode 100644
--- /dev/null
+++ b/toolkit/components/url-classifier/tests/gtest/TestLookupCacheV4.cpp
@@ -0,0 +1,88 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "LookupCacheV4.h"
+#include "Common.h"
+
+#define GTEST_SAFEBROWSING_DIR NS_LITERAL_CSTRING("safebrowsing")
+#define GTEST_TABLE NS_LITERAL_CSTRING("gtest-malware-proto")
+
+typedef nsCString _Fragment;
+typedef nsTArray<nsCString> _PrefixArray;
+
+// Generate a hash prefix from string
+static const nsCString
+GeneratePrefix(const _Fragment& aFragment, uint8_t aLength)
+{
+  Completion complete;
+  nsCOMPtr<nsICryptoHash> cryptoHash = do_CreateInstance(NS_CRYPTO_HASH_CONTRACTID);
+  complete.FromPlaintext(aFragment, cryptoHash);
+
+  nsCString hash;
+  hash.Assign((const char *)complete.buf, aLength);
+  return hash;
+}
+
+static UniquePtr<LookupCacheV4>
+SetupLookupCacheV4(const _PrefixArray& prefixArray)
+{
+  nsCOMPtr<nsIFile> file;
+  NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(file));
+
+  file->AppendNative(GTEST_SAFEBROWSING_DIR);
+
+  UniquePtr<LookupCacheV4> cache = MakeUnique<LookupCacheV4>(GTEST_TABLE, file);
+  nsresult rv = cache->Init();
+  EXPECT_EQ(rv, NS_OK);
+
+  PrefixStringMap map;
+  PrefixArrayToPrefixStringMap(prefixArray, map);
+  rv = cache->Build(map);
+  EXPECT_EQ(rv, NS_OK);
+
+  return Move(cache);
+}
+
+void
+TestHasPrefix(const _Fragment& aFragment, bool aExpectedHas, bool aExpectedComplete)
+{
+  _PrefixArray array = { GeneratePrefix(_Fragment("bravo.com/"), 32),
+                         GeneratePrefix(_Fragment("browsing.com/"), 8),
+                         GeneratePrefix(_Fragment("gound.com/"), 5),
+                         GeneratePrefix(_Fragment("small.com/"), 4)
+                       };
+
+  RunTestInNewThread([&] () -> void {
+    UniquePtr<LookupCache> cache = SetupLookupCacheV4(array);
+
+    Completion lookupHash;
+    nsCOMPtr<nsICryptoHash> cryptoHash = do_CreateInstance(NS_CRYPTO_HASH_CONTRACTID);
+    lookupHash.FromPlaintext(aFragment, cryptoHash);
+
+    bool has, complete;
+    nsresult rv = cache->Has(lookupHash, &has, &complete);
+
+    EXPECT_EQ(rv, NS_OK);
+    EXPECT_EQ(has, aExpectedHas);
+    EXPECT_EQ(complete, aExpectedComplete);
+
+    cache->ClearAll();
+  });
+
+}
+
+TEST(LookupCacheV4, HasComplete)
+{
+  TestHasPrefix(_Fragment("bravo.com/"), true, true);
+}
+
+TEST(LookupCacheV4, HasPrefix)
+{
+  TestHasPrefix(_Fragment("browsing.com/"), true, false);
+}
+
+TEST(LookupCacheV4, Nomatch)
+{
+  TestHasPrefix(_Fragment("nomatch.com/"), false, false);
+}
--- a/toolkit/components/url-classifier/tests/gtest/TestPerProviderDirectory.cpp
+++ b/toolkit/components/url-classifier/tests/gtest/TestPerProviderDirectory.cpp
@@ -1,15 +1,13 @@
 #include "LookupCache.h"
 #include "LookupCacheV4.h"
 #include "HashStore.h"
 #include "gtest/gtest.h"
-#include "nsIThread.h"
 #include "nsAppDirectoryServiceDefs.h"
-#include "nsThreadUtils.h"
 
 namespace mozilla {
 namespace safebrowsing {
 
 class PerProviderDirectoryTestUtils {
 public:
   template<typename T>
   static nsIFile* InspectStoreDirectory(const T& aT)
--- a/toolkit/components/url-classifier/tests/gtest/TestUrlClassifierTableUpdateV4.cpp
+++ b/toolkit/components/url-classifier/tests/gtest/TestUrlClassifierTableUpdateV4.cpp
@@ -1,11 +1,12 @@
 /* Any copyright is dedicated to the Public Domain.
  * http://creativecommons.org/publicdomain/zero/1.0/ */
 
+#include "Common.h"
 #include "Classifier.h"
 #include "HashStore.h"
 #include "nsAppDirectoryServiceDefs.h"
 #include "nsIFile.h"
 #include "nsIThread.h"
 #include "string.h"
 #include "gtest/gtest.h"
 #include "nsThreadUtils.h"
@@ -50,31 +51,16 @@ MergeAndSortArray(const _PrefixArray& ar
                   _PrefixArray& output)
 {
   output.Clear();
   output.AppendElements(array1);
   output.AppendElements(array2);
   output.Sort();
 }
 
-// This function converts lexigraphic-sorted prefixes to a hashtable
-// which key is prefix size and value is concatenated prefix string.
-static void
-PrefixArrayToPrefixStringMap(const _PrefixArray& prefixArray,
-                             PrefixStringMap& outMap)
-{
-  outMap.Clear();
-
-  for (uint32_t i = 0; i < prefixArray.Length(); i++) {
-    const _Prefix& prefix = prefixArray[i];
-    nsCString* prefixString = outMap.LookupOrAdd(prefix.Length());
-    prefixString->Append(prefix.BeginReading(), prefix.Length());
-  }
-}
-
 static void
 CalculateCheckSum(_PrefixArray& prefixArray, nsCString& checksum)
 {
   prefixArray.Sort();
 
   nsresult rv;
   nsCOMPtr<nsICryptoHash> cryptoHash =
     do_CreateInstance(NS_CRYPTO_HASH_CONTRACTID, &rv);
--- a/toolkit/components/url-classifier/tests/gtest/moz.build
+++ b/toolkit/components/url-classifier/tests/gtest/moz.build
@@ -7,16 +7,17 @@
 LOCAL_INCLUDES += [
     '../..',
 ]
 
 UNIFIED_SOURCES += [
     'Common.cpp',
     'TestChunkSet.cpp',
     'TestFailUpdate.cpp',
+    'TestLookupCacheV4.cpp',
     'TestPerProviderDirectory.cpp',
     'TestProtocolParser.cpp',
     'TestRiceDeltaDecoder.cpp',
     'TestSafebrowsingHash.cpp',
     'TestSafeBrowsingProtobuf.cpp',
     'TestTable.cpp',
     'TestUrlClassifierTableUpdateV4.cpp',
     'TestUrlClassifierUtils.cpp',
--- a/toolkit/content/tests/chrome/findbar_window.xul
+++ b/toolkit/content/tests/chrome/findbar_window.xul
@@ -16,16 +16,17 @@
         onload="onLoad();"
         title="findbar test">
 
   <script type="application/javascript"
           src="chrome://mochikit/content/tests/SimpleTest/EventUtils.js"/>
 
   <script type="application/javascript"><![CDATA[
     const {interfaces: Ci, classes: Cc, results: Cr, utils: Cu} = Components;
+    Cu.import("resource://gre/modules/AppConstants.jsm");
     Cu.import("resource://gre/modules/Task.jsm");
     Cu.import("resource://testing-common/ContentTask.jsm");
     ContentTask.setTestScope(window.opener.wrappedJSObject);
 
     var gPrefsvc = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch);
 
     const SAMPLE_URL = "http://www.mozilla.org/";
     const SAMPLE_TEXT = "Some text in a text field.";
@@ -132,22 +133,24 @@
       // TODO: I don't know how to drop a content element on a chrome input.
       if (!gBrowser.hasAttribute("remote"))
         testDrop();
       yield testQuickFindLink();
       if (gHasFindClipboard) {
         yield testStatusText();
       }
 
-      yield testFindCountUI();
-      gFindBar.close();
-      ok(gFindBar.hidden, "Failed to close findbar after testFindCountUI");
-      yield testFindCountUI(true);
-      gFindBar.close();
-      ok(gFindBar.hidden, "Failed to close findbar after testFindCountUI - linksOnly");
+      if (!AppConstants.DEBUG) {
+        yield testFindCountUI();
+        gFindBar.close();
+        ok(gFindBar.hidden, "Failed to close findbar after testFindCountUI");
+        yield testFindCountUI(true);
+        gFindBar.close();
+        ok(gFindBar.hidden, "Failed to close findbar after testFindCountUI - linksOnly");
+      }
 
       yield openFindbar();
       yield testFindAfterCaseChanged();
       gFindBar.close();
       yield openFindbar();
       yield testFailedStringReset();
       gFindBar.close();
       yield testQuickFindClose();
--- a/toolkit/content/tests/widgets/popup_shared.js
+++ b/toolkit/content/tests/widgets/popup_shared.js
@@ -360,18 +360,18 @@ function compareEdge(anchor, popup, edge
   else {
     is(Math.round(popuprect.width), gPopupWidth, testname + " width");
     is(Math.round(popuprect.height), gPopupHeight, testname + " height");
   }
 
   var spaceIdx = edge.indexOf(" ");
   if (spaceIdx > 0) {
     let cornerX, cornerY;
-    let [anchor, align] = edge.split(" ");
-    switch (anchor) {
+    let [position, align] = edge.split(" ");
+    switch (position) {
       case "topleft": cornerX = anchorrect.left; cornerY = anchorrect.top; break;
       case "topcenter": cornerX = anchorrect.left + anchorrect.width / 2; cornerY = anchorrect.top; break;
       case "topright": cornerX = anchorrect.right; cornerY = anchorrect.top; break;
       case "leftcenter": cornerX = anchorrect.left; cornerY = anchorrect.top + anchorrect.height / 2; break;
       case "rightcenter": cornerX = anchorrect.right; cornerY = anchorrect.top + anchorrect.height / 2; break;
       case "bottomleft": cornerX = anchorrect.left; cornerY = anchorrect.bottom; break;
       case "bottomcenter": cornerX = anchorrect.left + anchorrect.width / 2; cornerY = anchorrect.bottom; break;
       case "bottomright": cornerX = anchorrect.right; cornerY = anchorrect.bottom; break;
--- a/toolkit/content/tests/widgets/tree_shared.js
+++ b/toolkit/content/tests/widgets/tree_shared.js
@@ -1098,17 +1098,17 @@ function testtag_tree_column_reorder()
   if (testframe) {
     testframe.scrollIntoView();
   }
 
   var tree = document.getElementById("tree-column-reorder");
   var numColumns = tree.columns.count;
 
   var reference = [];
-  for (var i = 0; i < numColumns; i++) {
+  for (let i = 0; i < numColumns; i++) {
     reference.push("col_" + i);
   }
 
   // Drag the first column to each position
   for (let i = 0; i < numColumns - 1; i++) {
     synthesizeColumnDrag(tree, i, i + 1, true);
     arrayMove(reference, i, i + 1, true);
     checkColumns(tree, reference, "drag first column right");
@@ -1276,27 +1276,27 @@ function arrayMove(aArray, aFrom, aTo, a
   }
 
   aArray.splice(aTo, 0, o);
 }
 
 function getSortedColumnArray(aTree)
 {
   var columns = aTree.columns;
-  var a = [];
-  for (var i = 0; i < columns.length; i++) {
-    a.push(columns.getColumnAt(i));
+  var array = [];
+  for (let i = 0; i < columns.length; i++) {
+    array.push(columns.getColumnAt(i));
   }
 
-  a.sort(function(a, b) {
+  array.sort(function(a, b) {
     var o1 = parseInt(a.element.getAttribute("ordinal"));
     var o2 = parseInt(b.element.getAttribute("ordinal"));
     return o1 - o2;
   });
-  return a;
+  return array;
 }
 
 function checkColumns(aTree, aReference, aMessage)
 {
   var columns = getSortedColumnArray(aTree);
   var ids = [];
   columns.forEach(function(e) {
     ids.push(e.element.id);
@@ -1313,17 +1313,17 @@ function mouseOnCell(tree, row, column, 
 
 function mouseClickOnColumnHeader(aColumns, aColumnIndex, aButton, aClickCount)
 {
   var columnHeader = aColumns[aColumnIndex].element;
   var columnHeaderRect = columnHeader.getBoundingClientRect();
   var columnWidth = columnHeaderRect.right - columnHeaderRect.left;
   // For multiple click we send separate click events, with increasing
   // clickCount.  This simulates the common behavior of multiple clicks.
-  for (var i = 1; i <= aClickCount; i++) {
+  for (let i = 1; i <= aClickCount; i++) {
     // Target the middle of the column header.
     synthesizeMouse(columnHeader, columnWidth / 2, 3,
                     { button: aButton,
                       clickCount: i }, null);
   }
 }
 
 function mouseDblClickOnCell(tree, row, column, testname)
@@ -1339,29 +1339,29 @@ function mouseDblClickOnCell(tree, row, 
   synthesizeMouse(tree.body, rect.x, rect.y, { clickCount: 2 }, null);
 }
 
 function compareArrays(arr1, arr2)
 {
   if (arr1.length != arr2.length)
     return false;
 
-  for (var i = 0; i < arr1.length; i++) {
+  for (let i = 0; i < arr1.length; i++) {
     if (arr1[i] != arr2[i])
       return false;
   }
 
   return true;
 }
 
 function convertProperties(arr)
 {
   var results = [];
   var count = arr.Count();
-  for (var i = 0; i < count; i++)
+  for (let i = 0; i < count; i++)
     results.push(arr.GetElementAt(i).QueryInterface(Components.interfaces.nsIAtom).toString());
 
   results.sort();
   return results.join(" ");
 }
 
 function convertDOMtoTreeRowInfo(treechildren, level, rowidx)
 {
--- a/xpcom/threads/MainThreadIdlePeriod.cpp
+++ b/xpcom/threads/MainThreadIdlePeriod.cpp
@@ -6,44 +6,71 @@
 
 #include "MainThreadIdlePeriod.h"
 
 #include "mozilla/Maybe.h"
 #include "mozilla/Preferences.h"
 #include "nsRefreshDriver.h"
 
 #define DEFAULT_LONG_IDLE_PERIOD 50.0f
+#define DEFAULT_MIN_IDLE_PERIOD 3.0f
 
 namespace mozilla {
 
 NS_IMETHODIMP
 MainThreadIdlePeriod::GetIdlePeriodHint(TimeStamp* aIdleDeadline)
 {
+  MOZ_ASSERT(NS_IsMainThread());
   MOZ_ASSERT(aIdleDeadline);
 
   Maybe<TimeStamp> deadline = nsRefreshDriver::GetIdleDeadlineHint();
 
   if (deadline.isSome()) {
-    *aIdleDeadline = deadline.value();
+    // If the idle period is too small, then just return a null time
+    // to indicate we are busy. Otherwise return the actual deadline.
+    TimeDuration minIdlePeriod =
+      TimeDuration::FromMilliseconds(GetMinIdlePeriod());
+    bool busySoon = deadline.value().IsNull() ||
+                    (TimeStamp::Now() >= (deadline.value() - minIdlePeriod));
+    *aIdleDeadline = busySoon ? TimeStamp() : deadline.value();
   } else {
     *aIdleDeadline =
       TimeStamp::Now() + TimeDuration::FromMilliseconds(GetLongIdlePeriod());
   }
 
   return NS_OK;
 }
 
 /* static */ float
 MainThreadIdlePeriod::GetLongIdlePeriod()
 {
+  MOZ_ASSERT(NS_IsMainThread());
+
   static float sLongIdlePeriod = DEFAULT_LONG_IDLE_PERIOD;
   static bool sInitialized = false;
 
   if (!sInitialized && Preferences::IsServiceAvailable()) {
     sInitialized = true;
     Preferences::AddFloatVarCache(&sLongIdlePeriod, "idle_queue.long_period",
                                   DEFAULT_LONG_IDLE_PERIOD);
   }
 
   return sLongIdlePeriod;
 }
 
+/* static */ float
+MainThreadIdlePeriod::GetMinIdlePeriod()
+{
+  MOZ_ASSERT(NS_IsMainThread());
+
+  static float sMinIdlePeriod = DEFAULT_MIN_IDLE_PERIOD;
+  static bool sInitialized = false;
+
+  if (!sInitialized && Preferences::IsServiceAvailable()) {
+    sInitialized = true;
+    Preferences::AddFloatVarCache(&sMinIdlePeriod, "idle_queue.min_period",
+                                  DEFAULT_MIN_IDLE_PERIOD);
+  }
+
+  return sMinIdlePeriod;
+}
+
 } // namespace mozilla
--- a/xpcom/threads/MainThreadIdlePeriod.h
+++ b/xpcom/threads/MainThreadIdlePeriod.h
@@ -13,15 +13,16 @@
 namespace mozilla {
 
 class MainThreadIdlePeriod final : public IdlePeriod
 {
 public:
   NS_DECL_NSIIDLEPERIOD
 
   static float GetLongIdlePeriod();
+  static float GetMinIdlePeriod();
 private:
   virtual ~MainThreadIdlePeriod() {}
 };
 
 } // namespace mozilla
 
 #endif // mozilla_dom_mainthreadidleperiod_h
--- a/xpcom/threads/nsThread.cpp
+++ b/xpcom/threads/nsThread.cpp
@@ -977,16 +977,22 @@ nsThread::RegisterIdlePeriod(already_Add
   MutexAutoLock lock(mLock);
   mIdlePeriod = aIdlePeriod;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsThread::IdleDispatch(already_AddRefed<nsIRunnable> aEvent)
 {
+  // Currently the only supported idle dispatch is from the same
+  // thread. To support idle dispatch from another thread we need to
+  // support waking threads that are waiting for an event queue that
+  // isn't mIdleEvents.
+  MOZ_ASSERT(PR_GetCurrentThread() == mThread);
+
   MutexAutoLock lock(mLock);
   LeakRefPtr<nsIRunnable> event(Move(aEvent));
 
   if (NS_WARN_IF(!event)) {
     return NS_ERROR_INVALID_ARG;
   }
 
   if (mEventsAreDoomed) {