Merge m-c to b2g-inbound.
authorRyan VanderMeulen <ryanvm@gmail.com>
Fri, 30 Aug 2013 13:42:41 -0400
changeset 145128 9b6f43676952ede0ccd1ced0751d4e88de72c18c
parent 145127 87eedd56640e35598fd3fc9501368b332d6996fd (current diff)
parent 145112 cfe8b0ab6d59359abe8074332d394ab667635089 (diff)
child 145129 830aa8fab7537c437bb2e132ad0dc9ece05b14c8
push id33167
push userryanvm@gmail.com
push dateSat, 31 Aug 2013 01:16:35 +0000
treeherdermozilla-inbound@7973c4b7cfd0 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone26.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Merge m-c to b2g-inbound.
docshell/shistory/public/nsIHistoryEntry.idl
dom/system/unix/MaemoLocationProvider.cpp
dom/system/unix/MaemoLocationProvider.h
js/src/devtools/rootAnalysis/suppressedPoints.js
media/webrtc/trunk/webrtc/common_audio/resampler/resampler.gypi
media/webrtc/trunk/webrtc/common_audio/signal_processing/signal_processing.gypi
media/webrtc/trunk/webrtc/common_audio/vad/vad.gypi
media/webrtc/trunk/webrtc/modules/audio_coding/codecs/cng/test/CNG.cc
media/webrtc/trunk/webrtc/modules/audio_coding/codecs/cng/test/StdAfx.cc
media/webrtc/trunk/webrtc/modules/audio_coding/codecs/cng/test/StdAfx.h
media/webrtc/trunk/webrtc/modules/audio_device/audio_device_opensles.cc
media/webrtc/trunk/webrtc/modules/audio_device/audio_device_opensles.h
media/webrtc/trunk/webrtc/modules/remote_bitrate_estimator/remote_bitrate_estimator_multi_stream.h
media/webrtc/trunk/webrtc/modules/remote_bitrate_estimator/remote_bitrate_estimator_single_stream.h
media/webrtc/trunk/webrtc/modules/remote_bitrate_estimator/remote_bitrate_estimator_unittest.cc
media/webrtc/trunk/webrtc/modules/rtp_rtcp/source/rtp_rtcp_tests.gypi
media/webrtc/trunk/webrtc/modules/rtp_rtcp/test/bitstreamTest/bitstreamTest.cc
media/webrtc/trunk/webrtc/modules/rtp_rtcp/test/testAPI/test_api_nack.cc
media/webrtc/trunk/webrtc/modules/rtp_rtcp/test/testH263Parser/testH263Parser.cc
media/webrtc/trunk/webrtc/modules/rtp_rtcp/test/testRateControl/testRateControl.cc
media/webrtc/trunk/webrtc/modules/video_capture/mac/qtkit/video_capture_recursive_lock.h
media/webrtc/trunk/webrtc/modules/video_capture/mac/qtkit/video_capture_recursive_lock.mm
media/webrtc/trunk/webrtc/modules/video_coding/main/test/jitter_buffer_test.cc
media/webrtc/trunk/webrtc/modules/video_coding/main/test/receiver_timing_tests.cc
media/webrtc/trunk/webrtc/modules/video_processing/main/test/vpm_tests.gypi
media/webrtc/trunk/webrtc/test/channel_transport.gyp
media/webrtc/trunk/webrtc/video_engine/new_include/common.h
media/webrtc/trunk/webrtc/video_engine/test/auto_test/media/captureDeviceImage.bmp
media/webrtc/trunk/webrtc/video_engine/test/auto_test/media/captureDeviceImage.jpg
media/webrtc/trunk/webrtc/video_engine/test/auto_test/media/renderStartImage.bmp
media/webrtc/trunk/webrtc/video_engine/test/auto_test/media/renderStartImage.jpg
media/webrtc/trunk/webrtc/video_engine/test/auto_test/media/renderTimeoutImage.bmp
media/webrtc/trunk/webrtc/video_engine/test/auto_test/media/renderTimeoutImage.jpg
media/webrtc/trunk/webrtc/voice_engine/test/voice_engine_tests.gypi
media/webrtc/trunk/webrtc/voice_engine/voice_engine_core.gypi
mfbt/Util.h
netwerk/base/src/nsAutodialMaemo.cpp
netwerk/base/src/nsAutodialMaemo.h
netwerk/system/maemo/Makefile.in
netwerk/system/maemo/moz.build
netwerk/system/maemo/nsMaemoNetworkLinkService.cpp
netwerk/system/maemo/nsMaemoNetworkLinkService.h
netwerk/system/maemo/nsMaemoNetworkManager.cpp
netwerk/system/maemo/nsMaemoNetworkManager.h
toolkit/components/social/FrameWorker.jsm
toolkit/crashreporter/client/certdata2pem.py
toolkit/crashreporter/client/crashreporter_maemo_gtk.cpp
toolkit/crashreporter/client/maemo-unit/crashreports.crt
toolkit/crashreporter/client/maemo-unit/opensslverify.sh
toolkit/crashreporter/client/maemo-unit/test_maemo_certs.js
toolkit/crashreporter/client/maemo-unit/xpcshell.ini
webapprt/content/mochitest.js
--- a/addon-sdk/source/lib/sdk/ui/sidebar.js
+++ b/addon-sdk/source/lib/sdk/ui/sidebar.js
@@ -1,47 +1,38 @@
 /* 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';
 
 module.metadata = {
   'stability': 'experimental',
   'engines': {
-    'Firefox': '> 24'
+    'Firefox': '*'
   }
 };
 
-try {
-  require('chrome').Cu.import('resource:///modules/CustomizableUI.jsm', {});
-}
-catch (e) {
-  throw Error('Unsupported Application: The module ' + module.id + ' does not support this application.');
-}
-
 const { Class } = require('../core/heritage');
 const { merge } = require('../util/object');
 const { Disposable } = require('../core/disposable');
 const { off, emit, setListeners } = require('../event/core');
 const { EventTarget } = require('../event/target');
 const { URL } = require('../url');
 const { add, remove, has, clear, iterator } = require('../lang/weak-set');
 const { WindowTracker } = require('../deprecated/window-utils');
 const { isShowing } = require('./sidebar/utils');
 const { isBrowser, getMostRecentBrowserWindow, windows, isWindowPrivate } = require('../window/utils');
 const { ns } = require('../core/namespace');
 const { remove: removeFromArray } = require('../util/array');
 const { show, hide, toggle } = require('./sidebar/actions');
 const { Worker: WorkerTrait } = require('../content/worker');
 const { contract: sidebarContract } = require('./sidebar/contract');
-const { Button } = require('./button');
-const { setStateFor, getStateFor } = require('./state');
 const { create, dispose, updateTitle, updateURL, isSidebarShowing, showSidebar, hideSidebar } = require('./sidebar/view');
 const { defer } = require('../core/promise');
-const { models, buttons, views, viewsFor, modelFor } = require('./sidebar/namespace');
+const { models, views, viewsFor, modelFor } = require('./sidebar/namespace');
 const { isLocalURL } = require('../url');
 const { ensure } = require('../system/unload');
 
 const Worker = WorkerTrait.resolve({
   _injectInDocument: '__injectInDocument'
 }).compose({
   get _injectInDocument() true
 });
@@ -56,60 +47,25 @@ const Sidebar = Class({
   implements: [ Disposable ],
   extends: EventTarget,
   setup: function(options) {
     let model = sidebarContract(options);
     models.set(this, model);
 
     validateTitleAndURLCombo({}, this.title, this.url);
 
-    // NOTE: delegating icon validation to the Button.
-    // IMPORTANT: Make the button first since it has it's own
-    // validation which we make use of.. (even if the sidebar
-    // id is not a duplicate the button id could be..)
-    let button = Button({
-      id: model.id,
-      icon: model.icon,
-      label: model.title,
-      type: 'checkbox',
-      onChange: update.bind(null, 'button')
-    });
-    buttons.set(this, button);
-
     const self = this;
     const internals = sidebarNS(self);
     const windowNS = internals.windowNS = ns();
 
     // see bug https://bugzilla.mozilla.org/show_bug.cgi?id=886148
     ensure(this, 'destroy');
 
     setListeners(this, options);
 
-    function update(source, state) {
-      let wins = windows('navigator:browser', { includePrivate: true });
-
-      for (let window of wins) {
-        let isShowing = isSidebarShowing(window, self);
-        let isChecked = (source == 'button') ? getStateFor(button, window).checked : isShowing;
-
-        // update sidebar?
-        if (isShowing != isChecked) {
-          if (isChecked) {
-            showSidebar(window, self);
-          }
-          else {
-            hideSidebar(window, self);
-          }
-        }
-
-        // update the button
-        setStateFor(button, window, { checked: isChecked });
-      }
-    }
-
     let bars = [];
     internals.tracker = WindowTracker({
       onTrack: function(window) {
         if (!isBrowser(window))
           return;
 
         let sidebar = window.document.getElementById('sidebar');
         let sidebarBox = window.document.getElementById('sidebar-box');
@@ -155,33 +111,30 @@ const Sidebar = Class({
               window: panelBrowser.contentWindow
             });
 
             function onWebPanelSidebarUnload() {
               windowNS(window).onWebPanelSidebarUnload = null;
 
               // uncheck the associated menuitem
               bar.setAttribute('checked', 'false');
-              setStateFor(button, window, { checked: false });
 
               emit(self, 'hide', {});
               emit(self, 'detach', worker);
             }
             windowNS(window).onWebPanelSidebarUnload = onWebPanelSidebarUnload;
             panelBrowser.contentWindow.addEventListener('unload', onWebPanelSidebarUnload, true);
 
             // check the associated menuitem
             bar.setAttribute('checked', 'true');
 
             function onWebPanelSidebarLoad() {
               panelBrowser.contentWindow.removeEventListener('load', onWebPanelSidebarLoad, true);
               windowNS(window).onWebPanelSidebarLoad = null;
 
-              update();
-
               // TODO: decide if returning worker is acceptable..
               //emit(self, 'show', { worker: worker });
               emit(self, 'show', {});
             }
             windowNS(window).onWebPanelSidebarLoad = onWebPanelSidebarLoad;
             panelBrowser.contentWindow.addEventListener('load', onWebPanelSidebarLoad, true);
 
             emit(self, 'attach', worker);
@@ -258,23 +211,16 @@ const Sidebar = Class({
     // validation
     if (!isLocalURL(v))
       throw Error('the url must be a valid local url');
     validateTitleAndURLCombo(this, this.title, v);
     // do update
     updateURL(this, v);
     modelFor(this).url = v;
   },
-  get icon() (buttons.get(this) || {}).icon,
-  set icon(v) {
-    let button = buttons.get(this);
-    if (!button)
-      return;
-    button.icon = v;
-  },
   show: function() {
     return showSidebar(null, this);
   },
   hide: function() {
     return hideSidebar(null, this);
   },
   dispose: function() {
     const internals = sidebarNS(this);
@@ -286,21 +232,16 @@ const Sidebar = Class({
     // stop tracking windows
     internals.tracker.unload();
     internals.tracker = null;
 
     internals.windowNS = null;
 
     views.delete(this);
     models.delete(this);
-
-    // kill the button
-    let button = buttons.get(this);
-    if (button)
-      button.destroy();
   }
 });
 exports.Sidebar = Sidebar;
 
 function validateTitleAndURLCombo(sidebar, title, url) {
   if (sidebar.title == title && sidebar.url == url) {
     return false;
   }
--- a/addon-sdk/source/lib/sdk/ui/sidebar/contract.js
+++ b/addon-sdk/source/lib/sdk/ui/sidebar/contract.js
@@ -2,37 +2,26 @@
 * 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 { contract } = require('../../util/contract');
 const { isValidURI, URL, isLocalURL } = require('../../url');
 const { isNil, isObject, isString } = require('../../lang/type');
 
-function isIconSet(icons) {
-  return Object.keys(icons).
-    every(size => String(size >>> 0) === size && isLocalURL(icons[size]))
-}
-
 exports.contract = contract({
   id: {
   	is: [ 'string' ],
   	ok: v => /^[a-z0-9-_]+$/i.test(v),
     msg: 'The option "id" must be a valid alphanumeric id (hyphens and ' +
          'underscores are allowed).'
   },
   title: {
   	is: [ 'string' ],
   	ok: v => v.length
   },
-  icon: {
-    is: ['string', 'object'],
-    ok: v => (isString(v) && isLocalURL(v)) || (isObject(v) && isIconSet(v)),
-    msg: 'The option "icon" must be a local URL or an object with ' +
-      'numeric keys / local URL values pair.'
-  },
   url: {
     is: [ 'string' ],
     ok: v => isLocalURL(v),
     map: function(v) v.toString(),
     msg: 'The option "url" must be a valid URI.'
   }
 });
--- a/addon-sdk/source/lib/sdk/ui/sidebar/view.js
+++ b/addon-sdk/source/lib/sdk/ui/sidebar/view.js
@@ -1,34 +1,38 @@
 /* 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';
 
 module.metadata = {
   'stability': 'unstable',
   'engines': {
-    'Firefox': '> 24'
+    'Firefox': '*'
   }
 };
 
 const { models, buttons, views, viewsFor, modelFor } = require('./namespace');
 const { isBrowser, getMostRecentBrowserWindow, windows, isWindowPrivate } = require('../../window/utils');
 const { setStateFor } = require('../state');
 const { defer } = require('../../core/promise');
 const { isPrivateBrowsingSupported } = require('../../self');
 
 const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
 const WEB_PANEL_BROWSER_ID = 'web-panels-browser';
 
 function create(window, details) {
+  let id = makeID(details.id);
   let { document } = window;
 
+  if (document.getElementById(id))
+    throw new Error('The ID "' + details.id + '" seems already used.');
+
   let menuitem = document.createElementNS(XUL_NS, 'menuitem');
-  menuitem.setAttribute('id', makeID(details.id));
+  menuitem.setAttribute('id', id);
   menuitem.setAttribute('label', details.title);
   menuitem.setAttribute('sidebarurl', details.sidebarurl);
   menuitem.setAttribute('checked', 'false');
   menuitem.setAttribute('type', 'checkbox');
   menuitem.setAttribute('group', 'sidebar');
   menuitem.setAttribute('autoCheck', 'false');
 
   document.getElementById('viewSidebarMenu').appendChild(menuitem);
--- a/addon-sdk/source/test/addons/private-browsing-supported/sidebar/utils.js
+++ b/addon-sdk/source/test/addons/private-browsing-supported/sidebar/utils.js
@@ -2,18 +2,16 @@
  * 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 { Cu } = require('chrome');
 const { getMostRecentBrowserWindow } = require('sdk/window/utils');
 const { fromIterator } = require('sdk/util/array');
 
-const BLANK_IMG = exports.BLANK_IMG = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
-
 const BUILTIN_SIDEBAR_MENUITEMS = exports.BUILTIN_SIDEBAR_MENUITEMS = [
   'menu_socialSidebar',
   'menu_historySidebar',
   'menu_bookmarksSidebar'
 ];
 
 function isSidebarShowing(window) {
   window = window || getMostRecentBrowserWindow();
@@ -56,31 +54,14 @@ function simulateClick(ele) {
   let { document } = window;
   let evt = document.createEvent('MouseEvents');
   evt.initMouseEvent('click', true, true, window,
     0, 0, 0, 0, 0, false, false, false, false, 0, null);
   ele.dispatchEvent(evt);
 }
 exports.simulateClick = simulateClick;
 
-function getWidget(buttonId, window = getMostRecentBrowserWindow()) {
-  const { CustomizableUI } = Cu.import('resource:///modules/CustomizableUI.jsm', {});
-  const { AREA_NAVBAR } = CustomizableUI;
-
-  let widgets = CustomizableUI.getWidgetsInArea(AREA_NAVBAR).
-    filter(({id}) => id.startsWith('button--') && id.endsWith(buttonId));
-
-  if (widgets.length === 0)
-    throw new Error('Widget with id `' + buttonId +'` not found.');
-
-  if (widgets.length > 1)
-    throw new Error('Unexpected number of widgets: ' + widgets.length)
-
-  return widgets[0].forWindow(window);
-};
-exports.getWidget = getWidget;
-
 // OSX and Windows exhibit different behaviors when 'checked' is false,
 // so compare against the consistent 'true'. See bug 894809.
 function isChecked(node) {
   return node.getAttribute('checked') === 'true';
 };
 exports.isChecked = isChecked;
--- a/addon-sdk/source/test/addons/private-browsing-supported/test-sidebar.js
+++ b/addon-sdk/source/test/addons/private-browsing-supported/test-sidebar.js
@@ -8,27 +8,26 @@ const { show, hide } = require('sdk/ui/s
 const { isShowing } = require('sdk/ui/sidebar/utils');
 const { getMostRecentBrowserWindow, isWindowPrivate } = require('sdk/window/utils');
 const { open, close, focus, promise: windowPromise } = require('sdk/window/helpers');
 const { setTimeout } = require('sdk/timers');
 const { isPrivate } = require('sdk/private-browsing');
 const { data } = require('sdk/self');
 const { URL } = require('sdk/url');
 
-const { BLANK_IMG, BUILTIN_SIDEBAR_MENUITEMS, isSidebarShowing,
+const { BUILTIN_SIDEBAR_MENUITEMS, isSidebarShowing,
         getSidebarMenuitems, getExtraSidebarMenuitems, makeID, simulateCommand,
-        simulateClick, getWidget, isChecked } = require('./sidebar/utils');
+        simulateClick, isChecked } = require('./sidebar/utils');
 
 exports.testSideBarIsInNewPrivateWindows = function(assert, done) {
   const { Sidebar } = require('sdk/ui/sidebar');
   let testName = 'testSideBarIsInNewPrivateWindows';
   let sidebar = Sidebar({
     id: testName,
     title: testName,
-    icon: BLANK_IMG,
     url: 'data:text/html;charset=utf-8,'+testName
   });
 
   let startWindow = getMostRecentBrowserWindow();
   let ele = startWindow.document.getElementById(makeID(testName));
   assert.ok(ele, 'sidebar element was added');
 
   open(null, { features: { private: true } }).then(function(window) {
@@ -39,25 +38,26 @@ exports.testSideBarIsInNewPrivateWindows
       sidebar.destroy();
       assert.ok(!window.document.getElementById(makeID(testName)), 'sidebar id DNE');
       assert.ok(!startWindow.document.getElementById(makeID(testName)), 'sidebar id DNE');
 
       close(window).then(done, assert.fail);
   })
 }
 
+// Disabled in order to land other fixes, see bug 910647 for further details.
+/*
 exports.testSidebarIsOpenInNewPrivateWindow = function(assert, done) {
   const { Sidebar } = require('sdk/ui/sidebar');
   let testName = 'testSidebarIsOpenInNewPrivateWindow';
   let window = getMostRecentBrowserWindow();
 
   let sidebar = Sidebar({
     id: testName,
     title: testName,
-    icon: BLANK_IMG,
     url: 'data:text/html;charset=utf-8,'+testName
   });
 
   assert.equal(isPrivate(window), false, 'the window is not private');
 
   sidebar.on('show', function() {
     assert.equal(isSidebarShowing(window), true, 'the sidebar is showing');
     assert.equal(isShowing(sidebar), true, 'the sidebar is showing');
@@ -82,26 +82,25 @@ exports.testSidebarIsOpenInNewPrivateWin
       sidebarEle.addEventListener('load', onSBLoad, true);
 
       assert.pass('waiting for the sidebar to open...');
     }, assert.fail).then(null, assert.fail);
   });
 
   sidebar.show();
 }
-
+*/
 // TEST: edge case where web panel is destroyed while loading
 exports.testDestroyEdgeCaseBugWithPrivateWindow = function(assert, done) {
   const { Sidebar } = require('sdk/ui/sidebar');
   let testName = 'testDestroyEdgeCaseBug';
   let window = getMostRecentBrowserWindow();
   let sidebar = Sidebar({
     id: testName,
     title: testName,
-    icon: BLANK_IMG,
     url: 'data:text/html;charset=utf-8,'+testName
   });
 
   // NOTE: purposely not listening to show event b/c the event happens
   //       between now and then.
   sidebar.show();
 
   assert.equal(isPrivate(window), false, 'the new window is not private');
@@ -120,24 +119,23 @@ exports.testDestroyEdgeCaseBugWithPrivat
     close(window2).then(function() {
       let loader = Loader(module);
 
       assert.equal(isPrivate(window), false, 'the current window is not private');
 
       let sidebar = loader.require('sdk/ui/sidebar').Sidebar({
         id: testName,
         title: testName,
-        icon: BLANK_IMG,
         url:  'data:text/html;charset=utf-8,'+ testName,
         onShow: function() {
           assert.pass('onShow works for Sidebar');
           loader.unload();
 
           let sidebarMI = getSidebarMenuitems();
-          for each (let mi in sidebarMI) {
+          for (let mi of sidebarMI) {
             assert.ok(BUILTIN_SIDEBAR_MENUITEMS.indexOf(mi.getAttribute('id')) >= 0, 'the menuitem is for a built-in sidebar')
             assert.ok(!isChecked(mi), 'no sidebar menuitem is checked');
           }
           assert.ok(!window.document.getElementById(makeID(testName)), 'sidebar id DNE');
           assert.equal(isSidebarShowing(window), false, 'the sidebar is not showing');
 
           done();
         }
@@ -154,17 +152,16 @@ exports.testShowInPrivateWindow = functi
   const { Sidebar } = require('sdk/ui/sidebar');
   let testName = 'testShowInPrivateWindow';
   let window1 = getMostRecentBrowserWindow();
   let url = 'data:text/html;charset=utf-8,'+testName;
 
   let sidebar1 = Sidebar({
     id: testName,
     title: testName,
-    icon: BLANK_IMG,
     url: url
   });
   let menuitemID = makeID(sidebar1.id);
 
   assert.equal(sidebar1.url, url, 'url getter works');
   assert.equal(isShowing(sidebar1), false, 'the sidebar is not showing');
   assert.ok(!isChecked(window1.document.getElementById(menuitemID)),
                'the menuitem is not checked');
--- a/addon-sdk/source/test/sidebar/utils.js
+++ b/addon-sdk/source/test/sidebar/utils.js
@@ -1,25 +1,23 @@
 /* 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';
 
 module.metadata = {
   'engines': {
-    'Firefox': '> 24'
+    'Firefox': '*'
   }
 };
 
 const { Cu } = require('chrome');
 const { getMostRecentBrowserWindow } = require('sdk/window/utils');
 const { fromIterator } = require('sdk/util/array');
 
-const BLANK_IMG = exports.BLANK_IMG = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
-
 const BUILTIN_SIDEBAR_MENUITEMS = exports.BUILTIN_SIDEBAR_MENUITEMS = [
   'menu_socialSidebar',
   'menu_historySidebar',
   'menu_bookmarksSidebar'
 ];
 
 function isSidebarShowing(window) {
   window = window || getMostRecentBrowserWindow();
@@ -62,31 +60,14 @@ function simulateClick(ele) {
   let { document } = window;
   let evt = document.createEvent('MouseEvents');
   evt.initMouseEvent('click', true, true, window,
     0, 0, 0, 0, 0, false, false, false, false, 0, null);
   ele.dispatchEvent(evt);
 }
 exports.simulateClick = simulateClick;
 
-function getWidget(buttonId, window = getMostRecentBrowserWindow()) {
-  const { CustomizableUI } = Cu.import('resource:///modules/CustomizableUI.jsm', {});
-  const { AREA_NAVBAR } = CustomizableUI;
-
-  let widgets = CustomizableUI.getWidgetsInArea(AREA_NAVBAR).
-    filter(({id}) => id.startsWith('button--') && id.endsWith(buttonId));
-
-  if (widgets.length === 0)
-    throw new Error('Widget with id `' + buttonId +'` not found.');
-
-  if (widgets.length > 1)
-    throw new Error('Unexpected number of widgets: ' + widgets.length)
-
-  return widgets[0].forWindow(window);
-};
-exports.getWidget = getWidget;
-
 // OSX and Windows exhibit different behaviors when 'checked' is false,
 // so compare against the consistent 'true'. See bug 894809.
 function isChecked(node) {
   return node.getAttribute('checked') === 'true';
 };
 exports.isChecked = isChecked;
--- a/addon-sdk/source/test/test-ui-sidebar-private-browsing.js
+++ b/addon-sdk/source/test/test-ui-sidebar-private-browsing.js
@@ -1,40 +1,39 @@
 /* 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';
 
 module.metadata = {
   'engines': {
-    'Firefox': '> 24'
+    'Firefox': '*'
   }
 };
 
 const { Loader } = require('sdk/test/loader');
 const { show, hide } = require('sdk/ui/sidebar/actions');
 const { isShowing } = require('sdk/ui/sidebar/utils');
 const { getMostRecentBrowserWindow, isWindowPrivate } = require('sdk/window/utils');
 const { open, close, focus, promise: windowPromise } = require('sdk/window/helpers');
 const { setTimeout } = require('sdk/timers');
 const { isPrivate } = require('sdk/private-browsing');
 const { data } = require('sdk/self');
 const { URL } = require('sdk/url');
 
-const { BLANK_IMG, BUILTIN_SIDEBAR_MENUITEMS, isSidebarShowing,
+const { BUILTIN_SIDEBAR_MENUITEMS, isSidebarShowing,
         getSidebarMenuitems, getExtraSidebarMenuitems, makeID, simulateCommand,
-        simulateClick, getWidget, isChecked } = require('./sidebar/utils');
+        simulateClick, isChecked } = require('./sidebar/utils');
 
 exports.testSideBarIsNotInNewPrivateWindows = function(assert, done) {
   const { Sidebar } = require('sdk/ui/sidebar');
   let testName = 'testSideBarIsNotInNewPrivateWindows';
   let sidebar = Sidebar({
     id: testName,
     title: testName,
-    icon: BLANK_IMG,
     url: 'data:text/html;charset=utf-8,'+testName
   });
 
   let startWindow = getMostRecentBrowserWindow();
   let ele = startWindow.document.getElementById(makeID(testName));
   assert.ok(ele, 'sidebar element was added');
 
   open(null, { features: { private: true } }).then(function(window) {
@@ -53,17 +52,16 @@ exports.testSideBarIsNotInNewPrivateWind
 /*
 exports.testSidebarIsNotOpenInNewPrivateWindow = function(assert, done) {
   let testName = 'testSidebarIsNotOpenInNewPrivateWindow';
   let window = getMostRecentBrowserWindow();
 
     let sidebar = Sidebar({
       id: testName,
       title: testName,
-      icon: BLANK_IMG,
       url: 'data:text/html;charset=utf-8,'+testName
     });
 
     sidebar.on('show', function() {
       assert.equal(isPrivate(window), false, 'the new window is not private');
       assert.equal(isSidebarShowing(window), true, 'the sidebar is showing');
       assert.equal(isShowing(sidebar), true, 'the sidebar is showing');
 
@@ -89,17 +87,16 @@ exports.testSidebarIsNotOpenInNewPrivate
 exports.testDestroyEdgeCaseBugWithPrivateWindow = function(assert, done) {
   const { Sidebar } = require('sdk/ui/sidebar');
   let testName = 'testDestroyEdgeCaseBug';
   let window = getMostRecentBrowserWindow();
 
   let sidebar = Sidebar({
     id: testName,
     title: testName,
-    icon: BLANK_IMG,
     url: 'data:text/html;charset=utf-8,'+testName
   });
 
   // NOTE: purposely not listening to show event b/c the event happens
   //       between now and then.
   sidebar.show();
 
   assert.equal(isPrivate(window), false, 'the new window is not private');
@@ -118,24 +115,23 @@ exports.testDestroyEdgeCaseBugWithPrivat
     close(window2).then(function() {
       let loader = Loader(module);
 
       assert.equal(isPrivate(window), false, 'the current window is not private');
 
       let sidebar = loader.require('sdk/ui/sidebar').Sidebar({
         id: testName,
         title: testName,
-        icon: BLANK_IMG,
         url:  'data:text/html;charset=utf-8,'+ testName,
         onShow: function() {
           assert.pass('onShow works for Sidebar');
           loader.unload();
 
           let sidebarMI = getSidebarMenuitems();
-          for each (let mi in sidebarMI) {
+          for (let mi of sidebarMI) {
             assert.ok(BUILTIN_SIDEBAR_MENUITEMS.indexOf(mi.getAttribute('id')) >= 0, 'the menuitem is for a built-in sidebar')
             assert.ok(!isChecked(mi), 'no sidebar menuitem is checked');
           }
           assert.ok(!window.document.getElementById(makeID(testName)), 'sidebar id DNE');
           assert.equal(isSidebarShowing(window), false, 'the sidebar is not showing');
 
           done();
         }
@@ -153,17 +149,16 @@ exports.testShowInPrivateWindow = functi
   let testName = 'testShowInPrivateWindow';
   let window = getMostRecentBrowserWindow();
   let { document } = window;
   let url = 'data:text/html;charset=utf-8,'+testName;
 
   let sidebar1 = Sidebar({
     id: testName,
     title: testName,
-    icon: BLANK_IMG,
     url: url
   });
 
   assert.equal(sidebar1.url, url, 'url getter works');
   assert.equal(isShowing(sidebar1), false, 'the sidebar is not showing');
   assert.ok(!isChecked(document.getElementById(makeID(sidebar1.id))),
                'the menuitem is not checked');
   assert.equal(isSidebarShowing(window), false, 'the new window sidebar is not showing');
--- a/addon-sdk/source/test/test-ui-sidebar.js
+++ b/addon-sdk/source/test/test-ui-sidebar.js
@@ -1,58 +1,55 @@
 /* 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';
 
 module.metadata = {
   'engines': {
-    'Firefox': '> 24'
+    'Firefox': '*'
   }
 };
 
 const { Cu } = require('chrome');
 const { Loader } = require('sdk/test/loader');
 const { show, hide } = require('sdk/ui/sidebar/actions');
 const { isShowing } = require('sdk/ui/sidebar/utils');
 const { getMostRecentBrowserWindow } = require('sdk/window/utils');
 const { open, close, focus, promise: windowPromise } = require('sdk/window/helpers');
 const { setTimeout } = require('sdk/timers');
 const { isPrivate } = require('sdk/private-browsing');
 const { data } = require('sdk/self');
 const { URL } = require('sdk/url');
 const { once, off, emit } = require('sdk/event/core');
 const { defer, all } = require('sdk/core/promise');
 
-const { BLANK_IMG, BUILTIN_SIDEBAR_MENUITEMS, isSidebarShowing,
+const { BUILTIN_SIDEBAR_MENUITEMS, isSidebarShowing,
         getSidebarMenuitems, getExtraSidebarMenuitems, makeID, simulateCommand,
-        simulateClick, getWidget, isChecked } = require('./sidebar/utils');
+        simulateClick, isChecked } = require('./sidebar/utils');
 
 exports.testSidebarBasicLifeCycle = function(assert, done) {
   const { Sidebar } = require('sdk/ui/sidebar');
   let testName = 'testSidebarBasicLifeCycle';
   let window = getMostRecentBrowserWindow();
   assert.ok(!window.document.getElementById(makeID(testName)), 'sidebar id DNE');
   let sidebarXUL = window.document.getElementById('sidebar');
   assert.ok(sidebarXUL, 'sidebar xul element does exist');
   assert.ok(!getExtraSidebarMenuitems().length, 'there are no extra sidebar menuitems');
 
   assert.equal(isSidebarShowing(window), false, 'sidebar is not showing 1');
   let sidebarDetails = {
     id: testName,
     title: 'test',
-    icon: BLANK_IMG,
     url: 'data:text/html;charset=utf-8,'+testName
   };
   let sidebar = Sidebar(sidebarDetails);
 
   // test the sidebar attributes
-  for each(let key in Object.keys(sidebarDetails)) {
-    if (key == 'icon')
-      continue;
+  for (let key of Object.keys(sidebarDetails)) {
     assert.equal(sidebarDetails[key], sidebar[key], 'the attributes match the input');
   }
 
   assert.pass('The Sidebar constructor worked');
 
   let extraMenuitems = getExtraSidebarMenuitems();
   assert.equal(extraMenuitems.length, 1, 'there is one extra sidebar menuitems');
 
@@ -76,17 +73,17 @@ exports.testSidebarBasicLifeCycle = func
       assert.equal(isSidebarShowing(window), false, 'the sidebar elemnt is hidden');
 
       sidebar.once('detach', function() {
         // calling destroy twice should not matter
         sidebar.destroy();
         sidebar.destroy();
 
         let sidebarMI = getSidebarMenuitems();
-        for each (let mi in sidebarMI) {
+        for (let mi of sidebarMI) {
           assert.ok(BUILTIN_SIDEBAR_MENUITEMS.indexOf(mi.getAttribute('id')) >= 0, 'the menuitem is for a built-in sidebar')
           assert.ok(!isChecked(mi), 'no sidebar menuitem is checked');
         }
 
         assert.ok(!window.document.getElementById(makeID(testName)), 'sidebar id DNE');
         assert.pass('calling destroy worked without error');
 
         done();
@@ -102,17 +99,16 @@ exports.testSidebarBasicLifeCycle = func
 }
 
 exports.testSideBarIsInNewWindows = function(assert, done) {
   const { Sidebar } = require('sdk/ui/sidebar');
   let testName = 'testSideBarIsInNewWindows';
   let sidebar = Sidebar({
     id: testName,
     title: testName,
-    icon: BLANK_IMG,
     url: 'data:text/html;charset=utf-8,'+testName
   });
 
   let startWindow = getMostRecentBrowserWindow();
   let ele = startWindow.document.getElementById(makeID(testName));
   assert.ok(ele, 'sidebar element was added');
 
   open().then(function(window) {
@@ -131,17 +127,16 @@ exports.testSideBarIsInNewWindows = func
 }
 
 exports.testSideBarIsShowingInNewWindows = function(assert, done) {
   const { Sidebar } = require('sdk/ui/sidebar');
   let testName = 'testSideBarIsShowingInNewWindows';
   let sidebar = Sidebar({
     id: testName,
     title: testName,
-    icon: BLANK_IMG,
     url: URL('data:text/html;charset=utf-8,'+testName)
   });
 
   let startWindow = getMostRecentBrowserWindow();
   let ele = startWindow.document.getElementById(makeID(testName));
   assert.ok(ele, 'sidebar element was added');
 
   let oldEle = ele;
@@ -201,17 +196,16 @@ exports.testSideBarIsShowingInNewWindows
 // TODO: determine if this is acceptable..
 /*
 exports.testAddonGlobalSimple = function(assert, done) {
   const { Sidebar } = require('sdk/ui/sidebar');
   let testName = 'testAddonGlobalSimple';
   let sidebar = Sidebar({
     id: testName,
     title: testName,
-    icon: BLANK_IMG,
     url: data.url('test-sidebar-addon-global.html')
   });
 
   sidebar.on('show', function({worker}) {
     assert.pass('sidebar was attached');
     assert.ok(!!worker, 'attach event has worker');
 
     worker.port.on('X', function(msg) {
@@ -228,17 +222,16 @@ exports.testAddonGlobalSimple = function
 */
 
 exports.testAddonGlobalComplex = function(assert, done) {
   const { Sidebar } = require('sdk/ui/sidebar');
   let testName = 'testAddonGlobalComplex';
   let sidebar = Sidebar({
     id: testName,
     title: testName,
-    icon: BLANK_IMG,
     url: data.url('test-sidebar-addon-global.html')
   });
 
   sidebar.on('attach', function(worker) {
     assert.pass('sidebar was attached');
     assert.ok(!!worker, 'attach event has worker');
 
     worker.port.once('Y', function(msg) {
@@ -260,23 +253,21 @@ exports.testAddonGlobalComplex = functio
 
 exports.testShowingOneSidebarAfterAnother = function(assert, done) {
   const { Sidebar } = require('sdk/ui/sidebar');
   let testName = 'testShowingOneSidebarAfterAnother';
 
   let sidebar1 = Sidebar({
     id: testName + '1',
     title: testName + '1',
-    icon: BLANK_IMG,
     url:  'data:text/html;charset=utf-8,'+ testName + 1
   });
   let sidebar2 = Sidebar({
     id: testName + '2',
     title: testName + '2',
-    icon: BLANK_IMG,
     url:  'data:text/html;charset=utf-8,'+ testName + 2
   });
 
   let window = getMostRecentBrowserWindow();
   let IDs = [ sidebar1.id, sidebar2.id ];
 
   let extraMenuitems = getExtraSidebarMenuitems(window);
   assert.equal(extraMenuitems.length, 2, 'there are two extra sidebar menuitems');
@@ -285,25 +276,25 @@ exports.testShowingOneSidebarAfterAnothe
     assert.equal(isShowing(sidebar1), sb1);
     assert.equal(isShowing(sidebar2), sb2);
     assert.equal(isSidebarShowing(window), sbEle);
   }
   testShowing(false, false, false);
 
   sidebar1.once('show', function() {
     testShowing(true, false, true);
-    for each (let mi in getExtraSidebarMenuitems(window)) {
+    for (let mi of getExtraSidebarMenuitems(window)) {
       let menuitemID = mi.getAttribute('id').replace(/^jetpack-sidebar-/, '');
       assert.ok(IDs.indexOf(menuitemID) >= 0, 'the extra menuitem is for one of our test sidebars');
       assert.equal(isChecked(mi), menuitemID == sidebar1.id, 'the test sidebar menuitem has the correct checked value');
     }
 
     sidebar2.once('show', function() {
       testShowing(false, true, true);
-      for each (let mi in getExtraSidebarMenuitems(window)) {
+      for (let mi of getExtraSidebarMenuitems(window)) {
         let menuitemID = mi.getAttribute('id').replace(/^jetpack-sidebar-/, '');
         assert.ok(IDs.indexOf(menuitemID) >= 0, 'the extra menuitem is for one of our test sidebars');
         assert.equal(isChecked(mi), menuitemID == sidebar2.id, 'the test sidebar menuitem has the correct checked value');
       }
 
       sidebar1.destroy();
       sidebar2.destroy();
 
@@ -323,28 +314,26 @@ exports.testSidebarUnload = function(ass
   const { Sidebar } = require('sdk/ui/sidebar');
   let testName = 'testSidebarUnload';
   let loader = Loader(module);
 
   let window = getMostRecentBrowserWindow();
 
   assert.equal(isPrivate(window), false, 'the current window is not private');
 
-  // EXPLICIT: testing require('sdk/ui')
-  let sidebar = loader.require('sdk/ui').Sidebar({
+  let sidebar = loader.require('sdk/ui/sidebar').Sidebar({
     id: testName,
     title: testName,
-    icon: BLANK_IMG,
     url:  'data:text/html;charset=utf-8,'+ testName,
     onShow: function() {
       assert.pass('onShow works for Sidebar');
       loader.unload();
 
       let sidebarMI = getSidebarMenuitems();
-      for each (let mi in sidebarMI) {
+      for (let mi of sidebarMI) {
         assert.ok(BUILTIN_SIDEBAR_MENUITEMS.indexOf(mi.getAttribute('id')) >= 0, 'the menuitem is for a built-in sidebar')
         assert.ok(!isChecked(mi), 'no sidebar menuitem is checked');
       }
       assert.ok(!window.document.getElementById(makeID(testName)), 'sidebar id DNE');
       assert.equal(isSidebarShowing(window), false, 'the sidebar is not showing');
 
       done();
     }
@@ -356,17 +345,16 @@ exports.testSidebarUnload = function(ass
 
 exports.testRemoteContent = function(assert) {
   const { Sidebar } = require('sdk/ui/sidebar');
   let testName = 'testRemoteContent';
   try {
     let sidebar = Sidebar({
       id: testName,
       title: testName,
-      icon: BLANK_IMG,
       url: 'http://dne.xyz.mozilla.org'
     });
     assert.fail('a bad sidebar was created..');
     sidebar.destroy();
   }
   catch(e) {
     assert.ok(/The option "url" must be a valid URI./.test(e), 'remote content is not acceptable');
   }
@@ -374,87 +362,66 @@ exports.testRemoteContent = function(ass
 
 exports.testInvalidURL = function(assert) {
   const { Sidebar } = require('sdk/ui/sidebar');
   let testName = 'testInvalidURL';
   try {
     let sidebar = Sidebar({
       id: testName,
       title: testName,
-      icon: BLANK_IMG,
       url: 'http:mozilla.org'
     });
     assert.fail('a bad sidebar was created..');
     sidebar.destroy();
   }
   catch(e) {
     assert.ok(/The option "url" must be a valid URI./.test(e), 'invalid URIs are not acceptable');
   }
 }
 
 exports.testInvalidURLType = function(assert) {
   const { Sidebar } = require('sdk/ui/sidebar');
   let testName = 'testInvalidURLType';
   try {
     let sidebar = Sidebar({
       id: testName,
-      title: testName,
-      icon: BLANK_IMG
+      title: testName
     });
     assert.fail('a bad sidebar was created..');
     sidebar.destroy();
   }
   catch(e) {
     assert.ok(/The option "url" must be a valid URI./.test(e), 'invalid URIs are not acceptable');
   }
 }
 
 exports.testInvalidTitle = function(assert) {
   const { Sidebar } = require('sdk/ui/sidebar');
   let testName = 'testInvalidTitle';
   try {
     let sidebar = Sidebar({
       id: testName,
       title: '',
-      icon: BLANK_IMG,
       url: 'data:text/html;charset=utf-8,'+testName
     });
     assert.fail('a bad sidebar was created..');
     sidebar.destroy();
   }
   catch(e) {
     assert.equal('The option "title" must be one of the following types: string', e.message, 'invalid titles are not acceptable');
   }
 }
 
-exports.testInvalidIcon = function(assert) {
-  const { Sidebar } = require('sdk/ui/sidebar');
-  let testName = 'testInvalidIcon';
-  try {
-    let sidebar = Sidebar({
-      id: testName,
-      title: testName,
-      url: 'data:text/html;charset=utf-8,'+testName
-    });
-    assert.fail('a bad sidebar was created..');
-    sidebar.destroy();
-  }
-  catch(e) {
-    assert.ok(/The option "icon" must be a local URL or an object with/.test(e), 'invalid icons are not acceptable');
-  }
-}
-
 exports.testInvalidID = function(assert) {
   const { Sidebar } = require('sdk/ui/sidebar');
   let testName = 'testInvalidID';
   try {
     let sidebar = Sidebar({
       id: '!',
       title: testName,
-      icon: BLANK_IMG,
       url: 'data:text/html;charset=utf-8,'+testName
     });
     assert.fail('a bad sidebar was created..');
     sidebar.destroy();
   }
   catch(e) {
     assert.ok(/The option "id" must be a valid alphanumeric id/.test(e), 'invalid ids are not acceptable');
   }
@@ -462,17 +429,16 @@ exports.testInvalidID = function(assert)
 
 exports.testInvalidBlankID = function(assert) {
   const { Sidebar } = require('sdk/ui/sidebar');
   let testName = 'testInvalidBlankID';
   try {
     let sidebar = Sidebar({
       id: '',
       title: testName,
-      icon: BLANK_IMG,
       url: 'data:text/html;charset=utf-8,'+testName
     });
     assert.fail('a bad sidebar was created..');
     sidebar.destroy();
   }
   catch(e) {
     assert.ok(/The option "id" must be a valid alphanumeric id/.test(e), 'invalid ids are not acceptable');
   }
@@ -480,34 +446,32 @@ exports.testInvalidBlankID = function(as
 
 exports.testInvalidNullID = function(assert) {
   const { Sidebar } = require('sdk/ui/sidebar');
   let testName = 'testInvalidNullID';
   try {
     let sidebar = Sidebar({
       id: null,
       title: testName,
-      icon: BLANK_IMG,
       url: 'data:text/html;charset=utf-8,'+testName
     });
     assert.fail('a bad sidebar was created..');
     sidebar.destroy();
   }
   catch(e) {
     assert.ok(/The option "id" must be a valid alphanumeric id/.test(e), 'invalid ids are not acceptable');
   }
 }
 
 exports.testInvalidUndefinedID = function(assert) {
   const { Sidebar } = require('sdk/ui/sidebar');
   let testName = 'testInvalidBlankID';
   try {
     let sidebar = Sidebar({
       title: testName,
-      icon: BLANK_IMG,
       url: 'data:text/html;charset=utf-8,'+testName
     });
     assert.fail('a bad sidebar was created..');
     sidebar.destroy();
   }
   catch(e) {
     assert.ok(/The option "id" must be a valid alphanumeric id/.test(e), 'invalid ids are not acceptable');
   }
@@ -516,17 +480,16 @@ exports.testInvalidUndefinedID = functio
 // TEST: edge case where web panel is destroyed while loading
 exports.testDestroyEdgeCaseBug = function(assert, done) {
   const { Sidebar } = require('sdk/ui/sidebar');
   let testName = 'testDestroyEdgeCaseBug';
   let window = getMostRecentBrowserWindow();
   let sidebar = Sidebar({
     id: testName,
     title: testName,
-    icon: BLANK_IMG,
     url: 'data:text/html;charset=utf-8,'+testName
   });
 
   // NOTE: purposely not listening to show event b/c the event happens
   //       between now and then.
   sidebar.show();
 
   assert.equal(isPrivate(window), false, 'the new window is not private');
@@ -545,24 +508,23 @@ exports.testDestroyEdgeCaseBug = functio
     close(window2).then(function() {
       let loader = Loader(module);
 
       assert.equal(isPrivate(window), false, 'the current window is not private');
 
       let sidebar = loader.require('sdk/ui/sidebar').Sidebar({
         id: testName,
         title: testName,
-        icon: BLANK_IMG,
         url:  'data:text/html;charset=utf-8,'+ testName,
         onShow: function() {
           assert.pass('onShow works for Sidebar');
           loader.unload();
 
           let sidebarMI = getSidebarMenuitems();
-          for each (let mi in sidebarMI) {
+          for (let mi of sidebarMI) {
             assert.ok(BUILTIN_SIDEBAR_MENUITEMS.indexOf(mi.getAttribute('id')) >= 0, 'the menuitem is for a built-in sidebar')
             assert.ok(!isChecked(mi), 'no sidebar menuitem is checked');
           }
           assert.ok(!window.document.getElementById(makeID(testName)), 'sidebar id DNE');
           assert.equal(isSidebarShowing(window), false, 'the sidebar is not showing');
 
           done();
         }
@@ -577,17 +539,16 @@ exports.testDestroyEdgeCaseBug = functio
 
 exports.testClickingACheckedMenuitem = function(assert, done) {
   const { Sidebar } = require('sdk/ui/sidebar');
   let testName = 'testClickingACheckedMenuitem';
   let window = getMostRecentBrowserWindow();
   let sidebar = Sidebar({
     id: testName,
     title: testName,
-    icon: BLANK_IMG,
     url: 'data:text/html;charset=utf-8,'+testName,
   });
 
   sidebar.show().then(function() {
     assert.pass('the show callback works');
 
     sidebar.once('hide', function() {
       assert.pass('clicking the menuitem after the sidebar has shown hides it.');
@@ -595,123 +556,61 @@ exports.testClickingACheckedMenuitem = f
       done();
     });
 
     let menuitem = window.document.getElementById(makeID(sidebar.id));
     simulateCommand(menuitem);
   });
 };
 
-exports.testClickingACheckedButton = function(assert, done) {
-  const { Sidebar } = require('sdk/ui/sidebar');
-  let testName = 'testClickingACheckedButton';
-  let window = getMostRecentBrowserWindow();
-
-  let sidebar = Sidebar({
-    id: testName,
-    title: testName,
-    icon: BLANK_IMG,
-    url: 'data:text/html;charset=utf-8,'+testName,
-    onShow: function onShow() {
-      sidebar.off('show', onShow);
-
-      assert.pass('the sidebar was shown');
-      //assert.equal(button.checked, true, 'the button is now checked');
-
-      sidebar.once('hide', function() {
-        assert.pass('clicking the button after the sidebar has shown hides it.');
-
-        sidebar.once('show', function() {
-          assert.pass('clicking the button again shows it.');
-
-          sidebar.hide().then(function() {
-            assert.pass('hide callback works');
-            assert.equal(isShowing(sidebar), false, 'the sidebar is not showing, final.');
-
-            assert.pass('the sidebar was destroying');
-            sidebar.destroy();
-            assert.pass('the sidebar was destroyed');
-
-            assert.equal(button.parentNode, null, 'the button\'s parents were shot')
-
-            done();
-          }, assert.fail);
-        });
-
-        assert.equal(isShowing(sidebar), false, 'the sidebar is not showing');
-
-        // TODO: figure out why this is necessary..
-        setTimeout(function() simulateCommand(button));
-      });
-
-      assert.equal(isShowing(sidebar), true, 'the sidebar is showing');
-
-      simulateCommand(button);
-    }
-  });
-
-  let { node: button } = getWidget(sidebar.id, window);
-  //assert.equal(button.checked, false, 'the button exists and is not checked');
-
-  assert.equal(isShowing(sidebar), false, 'the sidebar is not showing');
-  simulateCommand(button);
-}
-
 exports.testTitleSetter = function(assert, done) {
   const { Sidebar } = require('sdk/ui/sidebar');
   let testName = 'testTitleSetter';
   let { document } = getMostRecentBrowserWindow();
 
   let sidebar1 = Sidebar({
     id: testName,
     title: testName,
-    icon: BLANK_IMG,
     url: 'data:text/html;charset=utf-8,'+testName,
   });
 
   assert.equal(sidebar1.title, testName, 'title getter works');
 
   sidebar1.show().then(function() {
-    let button = document.querySelector('toolbarbutton[label=' + testName + ']');
-    assert.ok(button, 'button was found');
-
     assert.equal(document.getElementById(makeID(sidebar1.id)).getAttribute('label'),
                  testName,
                  'the menuitem label is correct');
 
     assert.equal(document.getElementById('sidebar-title').value, testName, 'the menuitem label is correct');
 
     sidebar1.title = 'foo';
 
     assert.equal(sidebar1.title, 'foo', 'title getter works');
 
     assert.equal(document.getElementById(makeID(sidebar1.id)).getAttribute('label'),
                  'foo',
                  'the menuitem label was updated');
 
     assert.equal(document.getElementById('sidebar-title').value, 'foo', 'the sidebar title was updated');
 
-    assert.equal(button.getAttribute('label'), 'foo', 'the button label was updated');
-
     sidebar1.destroy();
     done();
   }, assert.fail);
 }
 
 exports.testURLSetter = function(assert, done) {
   const { Sidebar } = require('sdk/ui/sidebar');
   let testName = 'testURLSetter';
   let window = getMostRecentBrowserWindow();
   let { document } = window;
   let url = 'data:text/html;charset=utf-8,'+testName;
 
   let sidebar1 = Sidebar({
     id: testName,
     title: testName,
-    icon: BLANK_IMG,
     url: url
   });
 
   assert.equal(sidebar1.url, url, 'url getter works');
   assert.equal(isShowing(sidebar1), false, 'the sidebar is not showing');
   assert.ok(!isChecked(document.getElementById(makeID(sidebar1.id))),
                'the menuitem is not checked');
   assert.equal(isSidebarShowing(window), false, 'the new window sidebar is not showing');
@@ -754,25 +653,23 @@ exports.testDuplicateID = function(asser
   let testName = 'testDuplicateID';
   let window = getMostRecentBrowserWindow();
   let { document } = window;
   let url = 'data:text/html;charset=utf-8,'+testName;
 
   let sidebar1 = Sidebar({
     id: testName,
     title: testName,
-    icon: BLANK_IMG,
     url: url
   });
 
   assert.throws(function() {
     Sidebar({
       id: testName,
       title: testName + 1,
-      icon: BLANK_IMG,
       url: url + 2
     }).destroy();
   }, /The ID .+ seems already used\./i, 'duplicate IDs will throw errors');
 
   sidebar1.destroy();
 }
 
 exports.testURLSetterToSameValueReloadsSidebar = function(assert, done) {
@@ -780,17 +677,16 @@ exports.testURLSetterToSameValueReloadsS
   let testName = 'testURLSetterToSameValueReloadsSidebar';
   let window = getMostRecentBrowserWindow();
   let { document } = window;
   let url = 'data:text/html;charset=utf-8,'+testName;
 
   let sidebar1 = Sidebar({
     id: testName,
     title: testName,
-    icon: BLANK_IMG,
     url: url
   });
 
   assert.equal(sidebar1.url, url, 'url getter works');
   assert.equal(isShowing(sidebar1), false, 'the sidebar is not showing');
   assert.ok(!isChecked(document.getElementById(makeID(sidebar1.id))),
                'the menuitem is not checked');
   assert.equal(isSidebarShowing(window), false, 'the new window sidebar is not showing');
@@ -823,26 +719,25 @@ exports.testURLSetterToSameValueReloadsS
 
       assert.equal(sidebar1.url, url, 'url getter works');
       assert.equal(isShowing(sidebar1), true, 'the sidebar is showing');
       assert.ok(isSidebarShowing(window), 'the new window sidebar is showing');
     }, assert.fail);
   }, assert.fail);
 }
 
-exports.testButtonShowingInOneWindowDoesNotAffectOtherWindows = function(assert, done) {
+exports.testShowingInOneWindowDoesNotAffectOtherWindows = function(assert, done) {
   const { Sidebar } = require('sdk/ui/sidebar');
-  let testName = 'testButtonShowingInOneWindowDoesNotAffectOtherWindows';
+  let testName = 'testShowingInOneWindowDoesNotAffectOtherWindows';
   let window1 = getMostRecentBrowserWindow();
   let url = 'data:text/html;charset=utf-8,'+testName;
 
   let sidebar1 = Sidebar({
     id: testName,
     title: testName,
-    icon: BLANK_IMG,
     url: url
   });
 
   assert.equal(sidebar1.url, url, 'url getter works');
   assert.equal(isShowing(sidebar1), false, 'the sidebar is not showing');
   let checkCount = 1;
   function checkSidebarShowing(window, expected) {
     assert.pass('check count ' + checkCount++);
@@ -855,17 +750,17 @@ exports.testButtonShowingInOneWindowDoes
     assert.equal(isSidebarShowing(window), expected || false, 'the new window sidebar is not showing');
   }
   checkSidebarShowing(window1, false);
 
   windowPromise(window1.OpenBrowserWindow(), 'load').then(function(window) {
     let { document } = window;
     assert.pass('new window was opened!');
 
-    // waiting for show using button
+    // waiting for show
     sidebar1.once('show', function() {
       // check state of the new window
       assert.equal(isShowing(sidebar1), true, 'the sidebar is showing');
       checkSidebarShowing(window, true);
 
       // check state of old window
       checkSidebarShowing(window1, false);
 
@@ -894,32 +789,27 @@ exports.testButtonShowingInOneWindowDoes
         close(window).then(done);
       });
 
       assert.pass('setting sidebar1.url');
       sidebar1.url += '1';
       assert.pass('set sidebar1.url');
     });
 
-    // clicking the sidebar button on the second window
-    let { node: button } = getWidget(sidebar1.id, window);
-    assert.ok(!!button, 'the button was found!');
-    simulateCommand(button);
-
+    sidebar1.show();
   }, assert.fail);
 }
 
 exports.testHidingAHiddenSidebarRejects = function(assert) {
   const { Sidebar } = require('sdk/ui/sidebar');
   let testName = 'testHidingAHiddenSidebarRejects';
   let url = 'data:text/html;charset=utf-8,'+testName;
   let sidebar = Sidebar({
     id: testName,
     title: testName,
-    icon: BLANK_IMG,
     url: url
   });
 
   sidebar.hide().then(assert.fail, assert.pass).then(function() {
     sidebar.destroy();
     done();
   }, assert.fail);
 }
@@ -933,36 +823,32 @@ exports.testGCdSidebarsOnUnload = functi
   let url = 'data:text/html;charset=utf-8,'+testName;
 
   assert.equal(isSidebarShowing(window), false, 'the sidebar is not showing');
 
   // IMPORTANT: make no reference to the sidebar instance, so it is GC'd
   let sidebar = Sidebar({
     id: testName,
     title: testName,
-    icon: BLANK_IMG,
     url: url
   });
 
   sidebar.show().then(function() {
     sidebar = null;
 
     assert.equal(isSidebarShowing(window), true, 'the sidebar is showing');
 
-    let buttonID = getWidget(testName, window).node.getAttribute('id');
     let menuitemID = makeID(testName);
 
-    assert.ok(!!window.document.getElementById(buttonID), 'the button was found');
     assert.ok(!!window.document.getElementById(menuitemID), 'the menuitem was found');
 
     Cu.schedulePreciseGC(function() {
       loader.unload();
 
       assert.equal(isSidebarShowing(window), false, 'the sidebar is not showing after unload');
-      assert.ok(!window.document.getElementById(buttonID), 'the button was removed');
       assert.ok(!window.document.getElementById(menuitemID), 'the menuitem was removed');
 
       done();
     })
   }, assert.fail).then(null, assert.fail);
 }
 
 exports.testGCdShowingSidebarsOnUnload = function(assert, done) {
@@ -973,40 +859,35 @@ exports.testGCdShowingSidebarsOnUnload =
   let testName = 'testGCdShowingSidebarsOnUnload';
   let url = 'data:text/html;charset=utf-8,'+testName;
 
   assert.equal(isSidebarShowing(window), false, 'the sidebar is not showing');
 
   let sidebar = Sidebar({
     id: testName,
     title: testName,
-    icon: BLANK_IMG,
     url: url
   });
 
   sidebar.on('show', function() {
     sidebar = null;
 
     assert.equal(isSidebarShowing(window), true, 'the sidebar is showing');
 
-    let buttonID = getWidget(testName, window).node.getAttribute('id');
     let menuitemID = makeID(testName);
 
-    assert.ok(!!window.document.getElementById(buttonID), 'the button was found');
     assert.ok(!!window.document.getElementById(menuitemID), 'the menuitem was found');
 
     Cu.schedulePreciseGC(function() {
       assert.equal(isSidebarShowing(window), true, 'the sidebar is still showing after gc');
-      assert.ok(!!window.document.getElementById(buttonID), 'the button was found after gc');
       assert.ok(!!window.document.getElementById(menuitemID), 'the menuitem was found after gc');
 
       loader.unload();
 
       assert.equal(isSidebarShowing(window), false, 'the sidebar is not showing after unload');
-      assert.ok(!window.document.getElementById(buttonID), 'the button was removed');
       assert.ok(!window.document.getElementById(menuitemID), 'the menuitem was removed');
 
       done();
     })
   });
 
   sidebar.show();
 }
@@ -1020,48 +901,42 @@ exports.testGCdHiddenSidebarsOnUnload = 
   let url = 'data:text/html;charset=utf-8,'+testName;
 
   assert.equal(isSidebarShowing(window), false, 'the sidebar is not showing');
 
   // IMPORTANT: make no reference to the sidebar instance, so it is GC'd
   Sidebar({
     id: testName,
     title: testName,
-    icon: BLANK_IMG,
     url: url
   });
 
-  let buttonID = getWidget(testName, window).node.getAttribute('id');
   let menuitemID = makeID(testName);
 
-  assert.ok(!!window.document.getElementById(buttonID), 'the button was found');
   assert.ok(!!window.document.getElementById(menuitemID), 'the menuitem was found');
 
   Cu.schedulePreciseGC(function() {
-    assert.ok(!!window.document.getElementById(buttonID), 'the button was found after gc');
     assert.ok(!!window.document.getElementById(menuitemID), 'the menuitem was found after gc');
 
     loader.unload();
 
-    assert.ok(!window.document.getElementById(buttonID), 'the button was removed');
     assert.ok(!window.document.getElementById(menuitemID), 'the menuitem was removed');
 
     done();
   });
 }
 
 exports.testSidebarGettersAndSettersAfterDestroy = function(assert) {
   const { Sidebar } = require('sdk/ui/sidebar');
   let testName = 'testSidebarGettersAndSettersAfterDestroy';
   let url = 'data:text/html;charset=utf-8,'+testName;
 
   let sidebar = Sidebar({
     id: testName,
     title: testName,
-    icon: BLANK_IMG,
     url: url
   });
 
   sidebar.destroy();
 
   assert.equal(sidebar.id, undefined, 'sidebar after destroy has no id');
 
   assert.throws(() => sidebar.id = 'foo-tang',
@@ -1074,80 +949,24 @@ exports.testSidebarGettersAndSettersAfte
   sidebar.title = 'boo-tang';
   assert.equal(sidebar.title, undefined, 'sidebar after destroy has no title');
 
   assert.equal(sidebar.url, undefined, 'sidebar after destroy has no url');
   sidebar.url = url + 'barz';
   assert.equal(sidebar.url, undefined, 'sidebar after destroy has no url');
 }
 
-exports.testButtonIconSet = function(assert) {
-  const { CustomizableUI } = Cu.import('resource:///modules/CustomizableUI.jsm', {});
-  let loader = Loader(module);
-  let { Sidebar } = loader.require('sdk/ui');
-  let testName = 'testButtonIconSet';
-  let url = 'data:text/html;charset=utf-8,'+testName;
-
-  // Test remote icon set
-  assert.throws(
-    () => Sidebar({
-      id: 'my-button-10',
-      title: 'my button',
-      url: url,
-      icon: {
-        '16': 'http://www.mozilla.org/favicon.ico'
-      }
-    }),
-    /^The option "icon"/,
-    'throws on no valid icon given');
-
-  let sidebar = Sidebar({
-    id: 'my-button-11',
-    title: 'my button',
-    url: url,
-    icon: {
-      '16': './icon16.png',
-      '32': './icon32.png',
-      '64': './icon64.png'
-    }
-  });
-
-  let { node, id: widgetId } = getWidget(sidebar.id);
-  let { devicePixelRatio } = node.ownerDocument.defaultView;
-
-  let size = 16 * devicePixelRatio;
-
-  assert.equal(node.getAttribute('image'), data.url(sidebar.icon[size].substr(2)),
-    'the icon is set properly in navbar');
-
-  let size = 32 * devicePixelRatio;
-
-  CustomizableUI.addWidgetToArea(widgetId, CustomizableUI.AREA_PANEL);
-
-  assert.equal(node.getAttribute('image'), data.url(sidebar.icon[size].substr(2)),
-    'the icon is set properly in panel');
-
-  // Using `loader.unload` without move back the button to the original area
-  // raises an error in the CustomizableUI. This is doesn't happen if the
-  // button is moved manually from navbar to panel. I believe it has to do
-  // with `addWidgetToArea` method, because even with a `timeout` the issue
-  // persist.
-  CustomizableUI.addWidgetToArea(widgetId, CustomizableUI.AREA_NAVBAR);
-
-  loader.unload();
-}
 
 exports.testSidebarLeakCheckDestroyAfterAttach = function(assert, done) {
   const { Sidebar } = require('sdk/ui/sidebar');
   let testName = 'testSidebarLeakCheckDestroyAfterAttach';
   let window = getMostRecentBrowserWindow();
   let sidebar = Sidebar({
     id: testName,
     title: testName,
-    icon: BLANK_IMG,
     url: 'data:text/html;charset=utf-8,'+testName
   });
 
   sidebar.on('attach', function() {
     assert.pass('the sidebar was shown');
 
     sidebar.on('show', function() {
       assert.fail('the sidebar show listener should have been removed');
@@ -1179,17 +998,16 @@ exports.testSidebarLeakCheckDestroyAfter
 exports.testSidebarLeakCheckUnloadAfterAttach = function(assert, done) {
   const loader = Loader(module);
   const { Sidebar } = loader.require('sdk/ui/sidebar');
   let testName = 'testSidebarLeakCheckUnloadAfterAttach';
   let window = getMostRecentBrowserWindow();
   let sidebar = Sidebar({
     id: testName,
     title: testName,
-    icon: BLANK_IMG,
     url: 'data:text/html;charset=utf-8,'+testName
   });
 
   sidebar.on('attach', function() {
     assert.pass('the sidebar was shown');
 
     sidebar.on('show', function() {
       assert.fail('the sidebar show listener should have been removed');
@@ -1223,33 +1041,30 @@ exports.testTwoSidebarsWithSameTitleAndU
   let testName = 'testTwoSidebarsWithSameTitleAndURL';
 
   let title = testName;
   let url = 'data:text/html;charset=utf-8,' + testName;
 
   let sidebar1 = Sidebar({
     id: testName + 1,
     title: title,
-    icon: BLANK_IMG,
     url: url
   });
 
   assert.throws(function() {
     Sidebar({
       id: testName + 2,
       title: title,
-      icon: BLANK_IMG,
       url: url
     }).destroy();
   }, /title.+url.+invalid/i, 'Creating two sidebars with the same title + url is not allowed');
 
   let sidebar2 = Sidebar({
     id: testName + 2,
     title: title,
-    icon: BLANK_IMG,
     url: 'data:text/html;charset=utf-8,X'
   });
 
   assert.throws(function() {
     sidebar2.url = url;
   }, /title.+url.+invalid/i, 'Creating two sidebars with the same title + url is not allowed');
 
   sidebar2.title = 'foo';
@@ -1258,100 +1073,89 @@ exports.testTwoSidebarsWithSameTitleAndU
   assert.throws(function() {
     sidebar2.title = title;
   }, /title.+url.+invalid/i, 'Creating two sidebars with the same title + url is not allowed');
 
   sidebar1.destroy();
   sidebar2.destroy();
 }
 
-exports.testButtonToOpenXToClose = function(assert, done) {
+exports.testShowToOpenXToClose = function(assert, done) {
   const { Sidebar } = require('sdk/ui/sidebar');
-  let testName = 'testButtonToOpenXToClose';
+  let testName = 'testShowToOpenXToClose';
 
   let title = testName;
   let url = 'data:text/html;charset=utf-8,' + testName;
   let window = getMostRecentBrowserWindow();
 
   let sidebar = Sidebar({
     id: testName,
     title: testName,
-    icon: BLANK_IMG,
     url: url,
     onShow: function() {
-      assert.ok(isChecked(button), 'button is checked');
       assert.ok(isChecked(menuitem), 'menuitem is checked');
 
       let closeButton = window.document.querySelector('#sidebar-header > toolbarbutton.tabs-closebutton');
       simulateCommand(closeButton);
     },
     onHide: function() {
-      assert.ok(!isChecked(button), 'button is not checked');
       assert.ok(!isChecked(menuitem), 'menuitem is not checked');
 
       sidebar.destroy();
       done();
     }
   });
 
-  let { node: button } = getWidget(sidebar.id, window);
   let menuitem = window.document.getElementById(makeID(sidebar.id));
 
-  assert.ok(!isChecked(button), 'button is not checked');
   assert.ok(!isChecked(menuitem), 'menuitem is not checked');
 
-  simulateCommand(button);
+  sidebar.show();
 }
 
-exports.testButtonToOpenMenuitemToClose = function(assert, done) {
+exports.testShowToOpenMenuitemToClose = function(assert, done) {
   const { Sidebar } = require('sdk/ui/sidebar');
-  let testName = 'testButtonToOpenMenuitemToClose';
+  let testName = 'testShowToOpenMenuitemToClose';
 
   let title = testName;
   let url = 'data:text/html;charset=utf-8,' + testName;
   let window = getMostRecentBrowserWindow();
 
   let sidebar = Sidebar({
     id: testName,
     title: testName,
-    icon: BLANK_IMG,
     url: url,
     onShow: function() {
-      assert.ok(isChecked(button), 'button is checked');
       assert.ok(isChecked(menuitem), 'menuitem is checked');
 
       simulateCommand(menuitem);
     },
     onHide: function() {
-      assert.ok(!isChecked(button), 'button is not checked');
       assert.ok(!isChecked(menuitem), 'menuitem is not checked');
 
       sidebar.destroy();
       done();
     }
   });
 
-  let { node: button } = getWidget(sidebar.id, window);
   let menuitem = window.document.getElementById(makeID(sidebar.id));
 
-  assert.ok(!isChecked(button), 'button is not checked');
   assert.ok(!isChecked(menuitem), 'menuitem is not checked');
 
-  simulateCommand(button);
+  sidebar.show();
 }
 
 exports.testDestroyWhileNonBrowserWindowIsOpen = function(assert, done) {
   const { Sidebar } = require('sdk/ui/sidebar');
   let testName = 'testDestroyWhileNonBrowserWindowIsOpen';
   let url = 'data:text/html;charset=utf-8,' + testName;
 
   let sidebar = Sidebar({
     id: testName,
     title: testName,
-    icon: BLANK_IMG,
     url: url
   });
 
   open('chrome://browser/content/preferences/preferences.xul').then(function(window) {
     try {
       sidebar.show();
       assert.equal(isSidebarShowing(getMostRecentBrowserWindow()), true, 'the sidebar is showing');
 
@@ -1388,17 +1192,16 @@ exports.testEventListeners = function(as
 
   function testThis() {
     assert(this, sidebar, '`this` is correct');
   }
 
   let sidebar = Sidebar({
     id: testName,
     title: testName,
-    icon: BLANK_IMG,
     url: 'data:text/html;charset=utf-8,' + testName,
     onShow: function() {
       assert.equal(this, sidebar, '`this` is correct in onShow');
       eventListenerOrder.push('onShow');
       constructorOnShow.resolve();
     },
     onAttach: function() {
       assert.equal(this, sidebar, '`this` is correct in onAttach');
--- a/browser/base/content/test/Makefile.in
+++ b/browser/base/content/test/Makefile.in
@@ -187,16 +187,17 @@ MOCHITEST_BROWSER_FILES = \
                  browser_bug822367.js \
                  browser_bug902156.js \
                  browser_bug832435.js \
                  browser_bug839103.js \
                  browser_bug880101.js \
                  browser_bug882977.js \
                  browser_bug887515.js \
                  browser_canonizeURL.js \
+                 browser_mixedcontent_securityflags.js \
                  browser_clearplugindata_noage.html \
                  browser_clearplugindata.html \
                  browser_clearplugindata.js \
                  browser_contentAreaClick.js \
                  browser_contextSearchTabPosition.js \
                  browser_CTP_drag_drop.js \
                  browser_CTP_data_urls.js \
                  browser_ctrlTab.js \
@@ -332,16 +333,17 @@ MOCHITEST_BROWSER_FILES = \
                  POSTSearchEngine.xml \
                  print_postdata.sjs \
                  redirect_bug623155.sjs \
                  test_bug435035.html \
                  test_bug462673.html \
                  test_bug628179.html \
                  test_bug839103.html \
                  test_wyciwyg_copying.html \
+                 test-mixedcontent-securityerrors.html \
                  title_test.svg \
                  video.ogg \
                  zoom_test.html \
                  $(NULL)
 
 # Disable tests on Windows due to frequent failures (bugs 825739, 841341)
 ifneq (windows,$(MOZ_WIDGET_TOOLKIT))
 MOCHITEST_BROWSER_FILES += \
new file mode 100644
--- /dev/null
+++ b/browser/base/content/test/browser_mixedcontent_securityflags.js
@@ -0,0 +1,57 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+// The test loads a web page with mixed active and display content
+// on it while the "block mixed content" settings are _on_.
+// It then checks that the mixed content flags have been set correctly.
+// The test then overrides the MCB settings and checks that the flags
+// have been set correctly again.
+// Bug 838396 - Not setting hasMixedDisplayContentLoaded and
+// hasMixedDisplayContentBlocked flag in nsMixedContentBlocker.cpp
+
+const TEST_URI = "https://example.com/browser/browser/base/content/test/test-mixedcontent-securityerrors.html";
+let gTestBrowser = null;
+
+function test()
+{
+  waitForExplicitFinish();
+  SpecialPowers.pushPrefEnv({"set": [["security.mixed_content.block_active_content", true],
+                            ["security.mixed_content.block_display_content", true]]}, blockMixedContentTest);
+}
+
+function blockMixedContentTest()
+{
+  gBrowser.selectedTab = gBrowser.addTab(TEST_URI);
+  let tab = gBrowser.selectedTab;
+  gTestBrowser = gBrowser.getBrowserForTab(tab);
+
+  gTestBrowser.addEventListener("load", function onLoad(aEvent) {
+    gTestBrowser.removeEventListener(aEvent.type, onLoad, true);
+    is(gTestBrowser.docShell.hasMixedDisplayContentBlocked, true, "hasMixedDisplayContentBlocked flag has been set");
+    is(gTestBrowser.docShell.hasMixedActiveContentBlocked, true, "hasMixedActiveContentBlocked flag has been set");
+    is(gTestBrowser.docShell.hasMixedDisplayContentLoaded, false, "hasMixedDisplayContentLoaded flag has been set");
+    is(gTestBrowser.docShell.hasMixedActiveContentLoaded, false, "hasMixedActiveContentLoaded flag has been set");
+    overrideMCB();
+  }, true);
+}
+
+function overrideMCB()
+{
+  gTestBrowser.addEventListener("load", mixedContentOverrideTest, true);
+  var notification = PopupNotifications.getNotification("mixed-content-blocked", gTestBrowser);
+  ok(notification, "Mixed Content Doorhanger didn't appear");
+  // Click on the doorhanger to allow mixed content.
+  notification.secondaryActions[0].callback(mixedContentOverrideTest);
+}
+
+function mixedContentOverrideTest()
+{
+  gTestBrowser.removeEventListener("load", mixedContentOverrideTest, true);
+
+  is(gTestBrowser.docShell.hasMixedDisplayContentLoaded, true, "hasMixedDisplayContentLoaded flag has not been set");
+  is(gTestBrowser.docShell.hasMixedActiveContentLoaded, true, "hasMixedActiveContentLoaded flag has not been set");
+  is(gTestBrowser.docShell.hasMixedDisplayContentBlocked, false, "second hasMixedDisplayContentBlocked flag has been set");
+  is(gTestBrowser.docShell.hasMixedActiveContentBlocked, false, "second hasMixedActiveContentBlocked flag has been set");
+  gBrowser.removeCurrentTab();
+  finish();
+}
new file mode 100644
--- /dev/null
+++ b/browser/base/content/test/test-mixedcontent-securityerrors.html
@@ -0,0 +1,21 @@
+<!--
+  Bug 875456 - Log mixed content messages from the Mixed Content Blocker to the
+  Security Pane in the Web Console
+-->
+
+<!DOCTYPE HTML>
+<html dir="ltr" xml:lang="en-US" lang="en-US">
+  <head>
+    <meta charset="utf8">
+    <title>Mixed Content test - http on https</title>
+    <script src="testscript.js"></script>
+    <!--
+      Any copyright is dedicated to the Public Domain.
+      http://creativecommons.org/publicdomain/zero/1.0/
+    -->
+  </head>
+  <body>
+    <iframe src="http://example.com"></iframe>
+    <img src="http://example.com/tests/image/test/mochitest/blue.png"></img>
+  </body>
+</html>
--- a/browser/installer/Makefile.in
+++ b/browser/installer/Makefile.in
@@ -96,18 +96,16 @@ MOZ_PKG_MAC_BACKGROUND=branding/backgrou
 MOZ_PKG_MAC_ICON=branding/disk.icns
 MOZ_PKG_MAC_EXTRA=--symlink "/Applications:/ "
 endif
 
 ifndef LIBXUL_SDK
 INSTALL_SDK = 1
 endif
 
-GENERATE_CACHE = 1
-
 include $(topsrcdir)/toolkit/mozapps/installer/signing.mk
 include $(topsrcdir)/toolkit/mozapps/installer/packager.mk
 
 ifeq (bundle, $(MOZ_FS_LAYOUT))
 BINPATH = $(_BINPATH)
 DEFINES += -DAPPNAME=$(_APPNAME)
 else
 # Every other platform just winds up in dist/bin
--- a/build/Makefile.in
+++ b/build/Makefile.in
@@ -52,18 +52,18 @@ DEFINES += \
   -DMAR_CHANNEL_ID="$(MAR_CHANNEL_ID)" \
   -DACCEPTED_MAR_CHANNEL_IDS="$(ACCEPTED_MAR_CHANNEL_IDS)" \
   $(NULL)
 
 ifdef MOZ_APP_PROFILE
 DEFINES += -DMOZ_APP_PROFILE="$(MOZ_APP_PROFILE)"
 endif
 
-ifdef MOZILLA_OFFICIAL
-DEFINES += -DMOZILLA_OFFICIAL
+ifdef MOZ_CRASHREPORTER
+DEFINES += -DMOZ_CRASHREPORTER
 endif
 
 ifdef MOZ_PROFILE_MIGRATOR
 DEFINES += -DMOZ_PROFILE_MIGRATOR
 endif
 
 ifdef MOZ_EXTENSION_MANAGER
 DEFINES += -DMOZ_EXTENSION_MANAGER
--- a/build/application.ini
+++ b/build/application.ini
@@ -32,13 +32,13 @@ MaxVersion=@GRE_MILESTONE@
 [XRE]
 #ifdef MOZ_PROFILE_MIGRATOR
 EnableProfileMigrator=1
 #endif
 #ifdef MOZ_EXTENSION_MANAGER
 EnableExtensionManager=1
 #endif
 
+#if MOZ_CRASHREPORTER
 [Crash Reporter]
-#if MOZILLA_OFFICIAL
 Enabled=1
+ServerURL=https://crash-reports.mozilla.com/submit?id=@MOZ_APP_ID@&version=@MOZ_APP_VERSION@&buildid=@APP_BUILDID@
 #endif
-ServerURL=https://crash-reports.mozilla.com/submit?id=@MOZ_APP_ID@&version=@MOZ_APP_VERSION@&buildid=@APP_BUILDID@
--- a/build/autoconf/arch.m4
+++ b/build/autoconf/arch.m4
@@ -32,26 +32,16 @@ if test -z "$MOZ_ARCH"; then
         MOZ_ARCH=armv7-a
         MOZ_FPU=vfp
         MOZ_FLOAT_ABI=softfp
         ;;
     arm-Darwin)
         MOZ_ARCH=toolchain-default
         MOZ_THUMB=yes
         ;;
-    arm-*)
-        if test -n "$MOZ_PLATFORM_MAEMO"; then
-            MOZ_THUMB=no
-            MOZ_ARCH=armv7-a
-            MOZ_FLOAT_ABI=softfp
-        fi
-        if test "$MOZ_PLATFORM_MAEMO" = 6; then
-            MOZ_THUMB=yes
-        fi
-        ;;
     esac
 fi
 
 if test "$MOZ_ARCH" = "armv6" -a "$OS_TARGET" = "Android"; then
    MOZ_FPU=vfp
 fi
 
 MOZ_ARG_WITH_STRING(thumb,
--- a/build/autoconf/compiler-opts.m4
+++ b/build/autoconf/compiler-opts.m4
@@ -73,16 +73,95 @@ if test -z "$_MOZ_USE_RTTI"; then
         case "$target" in
         *-mingw*)
             CXXFLAGS="$CXXFLAGS -GR-"
         esac
     fi
 fi
 ])
 
+dnl ========================================================
+dnl =
+dnl = Debugging Options
+dnl =
+dnl ========================================================
+AC_DEFUN([MOZ_DEBUGGING_OPTS],
+[
+dnl Debug info is ON by default.
+if test -z "$MOZ_DEBUG_FLAGS"; then
+  MOZ_DEBUG_FLAGS="-g"
+fi
+
+MOZ_ARG_ENABLE_STRING(debug,
+[  --enable-debug[=DBG]    Enable building with developer debug info
+                           (using compiler flags DBG)],
+[ if test "$enableval" != "no"; then
+    MOZ_DEBUG=1
+    if test -n "$enableval" -a "$enableval" != "yes"; then
+        MOZ_DEBUG_FLAGS=`echo $enableval | sed -e 's|\\\ | |g'`
+        _MOZ_DEBUG_FLAGS_SET=1
+    fi
+  else
+    MOZ_DEBUG=
+  fi ],
+  MOZ_DEBUG=)
+
+MOZ_DEBUG_ENABLE_DEFS="-DDEBUG -D_DEBUG -DTRACING"
+MOZ_ARG_WITH_STRING(debug-label,
+[  --with-debug-label=LABELS
+                          Define DEBUG_<value> for each comma-separated
+                          value given.],
+[ for option in `echo $withval | sed 's/,/ /g'`; do
+    MOZ_DEBUG_ENABLE_DEFS="$MOZ_DEBUG_ENABLE_DEFS -DDEBUG_${option}"
+done])
+
+MOZ_DEBUG_DISABLE_DEFS="-DNDEBUG -DTRIMMED"
+
+if test -n "$MOZ_DEBUG"; then
+    AC_MSG_CHECKING([for valid debug flags])
+    _SAVE_CFLAGS=$CFLAGS
+    CFLAGS="$CFLAGS $MOZ_DEBUG_FLAGS"
+    AC_TRY_COMPILE([#include <stdio.h>],
+        [printf("Hello World\n");],
+        _results=yes,
+        _results=no)
+    AC_MSG_RESULT([$_results])
+    if test "$_results" = "no"; then
+        AC_MSG_ERROR([These compiler flags are invalid: $MOZ_DEBUG_FLAGS])
+    fi
+    CFLAGS=$_SAVE_CFLAGS
+fi
+
+dnl ========================================================
+dnl = Enable generation of debug symbols
+dnl ========================================================
+MOZ_ARG_ENABLE_STRING(debug-symbols,
+[  --enable-debug-symbols[=DBG]
+                          Enable debugging symbols (using compiler flags DBG)],
+[ if test "$enableval" != "no"; then
+      MOZ_DEBUG_SYMBOLS=1
+      if test -n "$enableval" -a "$enableval" != "yes"; then
+          if test -z "$_MOZ_DEBUG_FLAGS_SET"; then
+              MOZ_DEBUG_FLAGS=`echo $enableval | sed -e 's|\\\ | |g'`
+          else
+              AC_MSG_ERROR([--enable-debug-symbols flags cannot be used with --enable-debug flags])
+          fi
+      fi
+  else
+      MOZ_DEBUG_SYMBOLS=
+  fi ],
+  MOZ_DEBUG_SYMBOLS=1)
+
+if test -n "$MOZ_DEBUG" -o -n "$MOZ_DEBUG_SYMBOLS"; then
+    AC_DEFINE(MOZ_DEBUG_SYMBOLS)
+    export MOZ_DEBUG_SYMBOLS
+fi
+
+])
+
 dnl A high level macro for selecting compiler options.
 AC_DEFUN([MOZ_COMPILER_OPTS],
 [
   if test -z "$MOZILLA_OFFICIAL"; then
     DEVELOPER_OPTIONS=1
   fi
   MOZ_ARG_ENABLE_BOOL(release,
   [  --enable-release        Build with more conservative, release engineering-oriented options.
--- a/chrome/src/nsChromeRegistryChrome.h
+++ b/chrome/src/nsChromeRegistryChrome.h
@@ -3,16 +3,17 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef nsChromeRegistryChrome_h
 #define nsChromeRegistryChrome_h
 
 #include "nsChromeRegistry.h"
 #include "nsVoidArray.h"
+#include "mozilla/Move.h"
 
 namespace mozilla {
 namespace dom {
 class PContentParent;
 }
 }
 
 class nsIPrefBranch;
@@ -121,18 +122,18 @@ class nsChromeRegistryChrome : public ns
 
   class OverlayListEntry : public nsURIHashKey
   {
    public:
     typedef nsURIHashKey::KeyType        KeyType;
     typedef nsURIHashKey::KeyTypePointer KeyTypePointer;
 
     OverlayListEntry(KeyTypePointer aKey) : nsURIHashKey(aKey) { }
-    OverlayListEntry(OverlayListEntry& toCopy) : nsURIHashKey(toCopy),
-                                                 mArray(toCopy.mArray) { }
+    OverlayListEntry(OverlayListEntry&& toMove) : nsURIHashKey(mozilla::Move(toMove)),
+                                                  mArray(mozilla::Move(toMove.mArray)) { }
     ~OverlayListEntry() { }
 
     void AddURI(nsIURI* aURI);
 
     nsCOMArray<nsIURI> mArray;
   };
 
   class OverlayListHash
--- a/config/config.mk
+++ b/config/config.mk
@@ -489,18 +489,18 @@ HOST_CMMFLAGS += -fobjc-exceptions
 OS_COMPILE_CMFLAGS += -fobjc-exceptions
 OS_COMPILE_CMMFLAGS += -fobjc-exceptions
 ifeq ($(MOZ_WIDGET_TOOLKIT),uikit)
 OS_COMPILE_CMFLAGS += -fobjc-abi-version=2 -fobjc-legacy-dispatch
 OS_COMPILE_CMMFLAGS += -fobjc-abi-version=2 -fobjc-legacy-dispatch
 endif
 endif
 
-COMPILE_CFLAGS	= $(VISIBILITY_FLAGS) $(DEFINES) $(INCLUDES) $(DSO_CFLAGS) $(DSO_PIC_CFLAGS) $(CFLAGS) $(RTL_FLAGS) $(OS_CPPFLAGS) $(OS_COMPILE_CFLAGS)
-COMPILE_CXXFLAGS = $(STL_FLAGS) $(VISIBILITY_FLAGS) $(DEFINES) $(INCLUDES) $(DSO_CFLAGS) $(DSO_PIC_CFLAGS) $(CXXFLAGS) $(RTL_FLAGS) $(OS_CPPFLAGS) $(OS_COMPILE_CXXFLAGS)
+COMPILE_CFLAGS	= $(VISIBILITY_FLAGS) $(DEFINES) $(INCLUDES) $(DSO_CFLAGS) $(DSO_PIC_CFLAGS) $(RTL_FLAGS) $(OS_CPPFLAGS) $(OS_COMPILE_CFLAGS) $(CFLAGS)
+COMPILE_CXXFLAGS = $(STL_FLAGS) $(VISIBILITY_FLAGS) $(DEFINES) $(INCLUDES) $(DSO_CFLAGS) $(DSO_PIC_CFLAGS) $(RTL_FLAGS) $(OS_CPPFLAGS) $(OS_COMPILE_CXXFLAGS) $(CXXFLAGS)
 COMPILE_CMFLAGS = $(OS_COMPILE_CMFLAGS)
 COMPILE_CMMFLAGS = $(OS_COMPILE_CMMFLAGS)
 
 ifndef CROSS_COMPILE
 HOST_CFLAGS += $(RTL_FLAGS)
 endif
 
 #
--- a/config/js/js.mozbuild
+++ b/config/js/js.mozbuild
@@ -1,7 +1,7 @@
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
-add_tier_dir('js', 'js/src', static=True)
+add_tier_dir('js', 'js/src', external=True)
 
--- a/config/rules.mk
+++ b/config/rules.mk
@@ -678,19 +678,16 @@ SUBMAKEFILES += $(addsuffix /Makefile, $
 
 # The root makefile doesn't want to do a plain export/libs, because
 # of the tiers and because of libxul. Suppress the default rules in favor
 # of something else. Makefiles which use this var *must* provide a sensible
 # default rule before including rules.mk
 ifndef SUPPRESS_DEFAULT_RULES
 ifndef TIERS
 default all::
-ifneq (,$(strip $(STATIC_DIRS)))
-	$(foreach dir,$(STATIC_DIRS),$(call SUBMAKE,,$(dir),1))
-endif
 	$(MAKE) export
 	$(MAKE) libs
 	$(MAKE) tools
 
 # Do depend as well
 alldep::
 	$(MAKE) export
 	$(MAKE) depend
@@ -825,20 +822,31 @@ endif # NO_PROFILE_GUIDED_OPTIMIZE
 ##############################################
 
 checkout:
 	$(MAKE) -C $(topsrcdir) -f client.mk checkout
 
 clean clobber realclean clobber_all:: $(SUBMAKEFILES)
 	-$(RM) $(ALL_TRASH)
 	-$(RM) -r $(ALL_TRASH_DIRS)
-	$(foreach dir,$(PARALLEL_DIRS) $(DIRS) $(STATIC_DIRS) $(TOOL_DIRS),-$(call SUBMAKE,$@,$(dir)))
+
+ifdef TIERS
+clean clobber realclean clobber_all distclean::
+	$(foreach dir, \
+		$(foreach tier, $(TIERS), $(tier_$(tier)_staticdirs) $(tier_$(tier)_dirs)), \
+		-$(call SUBMAKE,$@,$(dir)))
+else
+clean clobber realclean clobber_all distclean::
+	$(foreach dir,$(PARALLEL_DIRS) $(DIRS) $(TOOL_DIRS),-$(call SUBMAKE,$@,$(dir)))
 
 distclean:: $(SUBMAKEFILES)
-	$(foreach dir,$(PARALLEL_DIRS) $(DIRS) $(STATIC_DIRS) $(TOOL_DIRS),-$(call SUBMAKE,$@,$(dir)))
+	$(foreach dir,$(PARALLEL_DIRS) $(DIRS) $(TOOL_DIRS),-$(call SUBMAKE,$@,$(dir)))
+endif
+
+distclean::
 	-$(RM) -r $(ALL_TRASH_DIRS)
 	-$(RM) $(ALL_TRASH)  \
 	Makefile .HSancillary \
 	$(wildcard *.$(OBJ_SUFFIX)) $(wildcard *.ho) $(wildcard host_*.o*) \
 	$(wildcard *.$(LIB_SUFFIX)) $(wildcard *$(DLL_SUFFIX)) \
 	$(wildcard *.$(IMPORT_LIB_SUFFIX))
 ifeq ($(OS_ARCH),OS2)
 	-$(RM) $(PROGRAM:.exe=.map)
--- a/config/system-headers
+++ b/config/system-headers
@@ -1054,42 +1054,27 @@ libsn/sn-monitor.h
 libsn/sn-util.h
 #endif
 #if MOZ_NATIVE_HUNSPELL==1
 hunspell.hxx
 #endif
 #if MOZ_NATIVE_BZ2==1
 bzlib.h
 #endif
-#if MOZ_PLATFORM_MAEMO==5
-hildon-uri.h
-hildon-mime.h
-hildon-file-chooser-dialog.h
-libosso.h
-osso-mem.h
-#endif
 #ifdef MOZ_ENABLE_GIO
 gio/gio.h
 #endif
-#ifdef MOZ_ENABLE_LIBCONIC
-conic/conicconnection.h
-conic/conicconnectionevent.h
-conic/conicstatisticsevent.h
-#endif
 #if MOZ_NATIVE_LIBEVENT==1
 event.h
 #else
 sys/event.h
 #endif
 #ifdef MOZ_ENABLE_LIBPROXY
 proxy.h
 #endif
-#if MOZ_PLATFORM_MAEMO==6
-contentaction/contentaction.h
-#endif
 #ifdef MOZ_ENABLE_CONTENTMANAGER
 SelectSingleContentItemPage.h
 SelectMultipleContentItemsPage.h
 QtSparql/qsparqlconnection.h
 QtSparql/qsparqlquery.h
 QtSparql/qsparqlresult.h
 #endif
 
--- a/configure.in
+++ b/configure.in
@@ -2459,98 +2459,16 @@ case "$target" in
         ;;
 esac
 
 if test -z "$COMPILE_ENVIRONMENT"; then
     SKIP_COMPILER_CHECKS=1
     SKIP_LIBRARY_CHECKS=1
 fi
 
-dnl ========================================================
-dnl =
-dnl = Debugging Options
-dnl =
-dnl = These must come before MOZ_COMPILER_OPTS so that MOZ_COMPILER_OPTS
-dnl = sees any debug flags set by the user.
-dnl =
-dnl ========================================================
-MOZ_ARG_HEADER(Debugging)
-
-dnl ========================================================
-dnl = Debug info is ON by default.
-dnl ========================================================
-if test -z "$MOZ_DEBUG_FLAGS"; then
-  MOZ_DEBUG_FLAGS="-g"
-fi
-
-MOZ_ARG_ENABLE_STRING(debug,
-[  --enable-debug[=DBG]    Enable building with developer debug info
-                           (using compiler flags DBG)],
-[ if test "$enableval" != "no"; then
-    MOZ_DEBUG=1
-    if test -n "$enableval" -a "$enableval" != "yes"; then
-        MOZ_DEBUG_FLAGS=`echo $enableval | sed -e 's|\\\ | |g'`
-        _MOZ_DEBUG_FLAGS_SET=1
-    fi
-  else
-    MOZ_DEBUG=
-  fi ],
-  MOZ_DEBUG=)
-
-MOZ_DEBUG_ENABLE_DEFS="-DDEBUG -D_DEBUG -DTRACING"
-MOZ_ARG_WITH_STRING(debug-label,
-[  --with-debug-label=LABELS
-                          Define DEBUG_<value> for each comma-separated
-                          value given.],
-[ for option in `echo $withval | sed 's/,/ /g'`; do
-    MOZ_DEBUG_ENABLE_DEFS="$MOZ_DEBUG_ENABLE_DEFS -DDEBUG_${option}"
-done])
-
-MOZ_DEBUG_DISABLE_DEFS="-DNDEBUG -DTRIMMED"
-
-if test -n "$MOZ_DEBUG"; then
-    AC_MSG_CHECKING([for valid debug flags])
-    _SAVE_CFLAGS=$CFLAGS
-    CFLAGS="$CFLAGS $MOZ_DEBUG_FLAGS"
-    AC_TRY_COMPILE([#include <stdio.h>],
-        [printf("Hello World\n");],
-        _results=yes,
-        _results=no)
-    AC_MSG_RESULT([$_results])
-    if test "$_results" = "no"; then
-        AC_MSG_ERROR([These compiler flags are invalid: $MOZ_DEBUG_FLAGS])
-    fi
-    CFLAGS=$_SAVE_CFLAGS
-fi
-
-dnl ========================================================
-dnl = Enable generation of debug symbols
-dnl ========================================================
-MOZ_ARG_ENABLE_STRING(debug-symbols,
-[  --enable-debug-symbols[=DBG]
-                          Enable debugging symbols (using compiler flags DBG)],
-[ if test "$enableval" != "no"; then
-      MOZ_DEBUG_SYMBOLS=1
-      if test -n "$enableval" -a "$enableval" != "yes"; then
-          if test -z "$_MOZ_DEBUG_FLAGS_SET"; then
-              MOZ_DEBUG_FLAGS=`echo $enableval | sed -e 's|\\\ | |g'`
-          else
-              AC_MSG_ERROR([--enable-debug-symbols flags cannot be used with --enable-debug flags])
-          fi
-      fi
-  else
-      MOZ_DEBUG_SYMBOLS=
-  fi ],
-  MOZ_DEBUG_SYMBOLS=1)
-
-if test -n "$MOZ_DEBUG" -o -n "$MOZ_DEBUG_SYMBOLS"; then
-    AC_DEFINE(MOZ_DEBUG_SYMBOLS)
-    export MOZ_DEBUG_SYMBOLS
-fi
-
 MOZ_COMPILER_OPTS
 if test -z "$SKIP_COMPILER_CHECKS"; then
 dnl Checks for typedefs, structures, and compiler characteristics.
 dnl ========================================================
 AC_HEADER_STDC
 AC_C_CONST
 AC_TYPE_MODE_T
 AC_TYPE_OFF_T
@@ -4813,28 +4731,42 @@ incorrect])
     MOZ_ENABLE_QTMOBILITY=
     PKG_CHECK_MODULES(_QTMOBILITY, QtSensors QtFeedback QtLocation,
                       MOZ_ENABLE_QTMOBILITY=1,
                       MOZ_ENABLE_QTMOBILITY=)
     if test "$MOZ_ENABLE_QTMOBILITY"; then
        MOZ_ENABLE_QTMOBILITY=1
        MOZ_QT_CFLAGS="$MOZ_QT_CFLAGS $_QTMOBILITY_CFLAGS"
        MOZ_QT_LIBS="$MOZ_QT_LIBS $_QTMOBILITY_LIBS"
+       AC_DEFINE(MOZ_ENABLE_QTMOBILITY)
+       AC_SUBST(MOZ_ENABLE_QTMOBILITY)
     else
        AC_CHECK_LIB(QtSensors, main, [
           MOZ_ENABLE_QTMOBILITY=1
           MOZ_QT_CFLAGS="$MOZ_QT_CFLAGS -I$QTDIR/include/QtMobility"
           MOZ_QT_CFLAGS="$MOZ_QT_CFLAGS -I$QTDIR/include/QtSensors"
           MOZ_QT_CFLAGS="$MOZ_QT_CFLAGS -I$QTDIR/include/QtFeedback"
           MOZ_QT_CFLAGS="$MOZ_QT_CFLAGS -I$QTDIR/include/QtLocation"
           MOZ_QT_LIBS="$MOZ_QT_LIBS -lQtSensors -lQtFeedback -lQtLocation"
        ])
     fi
-    if test "$MOZ_ENABLE_QTMOBILITY"; then
-       AC_DEFINE(MOZ_ENABLE_QTMOBILITY)
+
+    if test "$MOZ_ENABLE_CONTENTACTION"; then
+      MOZ_ENABLE_CONTENTACTION=1
+      AC_DEFINE(MOZ_ENABLE_CONTENTACTION)
+    fi
+
+    MOZ_ENABLE_CONTENTACTION=
+    PKG_CHECK_MODULES(LIBCONTENTACTION, contentaction-0.1, _LIB_FOUND=1, _LIB_FOUND=)
+    if test "$MOZ_ENABLE_CONTENTACTION"; then
+       MOZ_ENABLE_CONTENTACTION=1
+       MOZ_QT_CFLAGS="$MOZ_QT_CFLAGS $_CONTENTACTION_CFLAGS"
+       MOZ_QT_LIBS="$MOZ_QT_LIBS $_CONTENTACTION_LIBS"
+       AC_DEFINE(MOZ_ENABLE_CONTENTACTION)
+       AC_SUBST(MOZ_ENABLE_CONTENTACTION)
     fi
 fi
 
 AC_SUBST(GTK_CONFIG)
 AC_SUBST(TK_CFLAGS)
 AC_SUBST(TK_LIBS)
 
 AC_SUBST(MOZ_ENABLE_GTK2)
@@ -6761,195 +6693,16 @@ dnl = Disable zipwriter
 dnl ========================================================
 MOZ_ARG_DISABLE_BOOL(zipwriter,
 [  --disable-zipwriter     Disable zipwriter component],
     MOZ_ZIPWRITER=,
     MOZ_ZIPWRITER=1 )
 AC_SUBST(MOZ_ZIPWRITER)
 
 dnl ========================================================
-dnl = libconic
-dnl ========================================================
-dnl superseded by QtNetwork starting from 4.7
-MOZ_ENABLE_LIBCONIC=1
-
-if test -n "$MOZ_ENABLE_QT"; then
-  if test "$MOZ_ENABLE_QTNETWORK"; then
-    MOZ_ENABLE_LIBCONIC=
-  fi
-fi
-
-MOZ_ARG_DISABLE_BOOL(libconic,
-[  --disable-libconic      Disable libconic],
-    MOZ_ENABLE_LIBCONIC=,
-    MOZ_ENABLE_LIBCONIC=1 )
-
-if test -n "$MOZ_ENABLE_LIBCONIC"; then
-    PKG_CHECK_MODULES(LIBCONIC, conic,
-                      MOZ_ENABLE_LIBCONIC=1,
-                      MOZ_ENABLE_LIBCONIC=)
-fi
-if test "$MOZ_ENABLE_LIBCONIC"; then
-    AC_DEFINE(MOZ_ENABLE_LIBCONIC)
-fi
-
-AC_SUBST(MOZ_ENABLE_LIBCONIC)
-AC_SUBST(LIBCONIC_CFLAGS)
-AC_SUBST(LIBCONIC_LIBS)
-
-dnl ========================================================
-dnl = Maemo checks
-dnl ========================================================
-
-MAEMO_SDK_TARGET_VER=-1
-
-MOZ_ARG_WITH_STRING(maemo-version,
-[  --with-maemo-version=MAEMO_SDK_TARGET_VER
-                          Maemo SDK Version],
-  MAEMO_SDK_TARGET_VER=$withval)
-
-case "$MAEMO_SDK_TARGET_VER" in
-5)
-    MOZ_PLATFORM_MAEMO=5
-    ;;
-
-6)
-    MOZ_PLATFORM_MAEMO=6
-    ;;
-
--1)
-    dnl We aren't compiling for Maemo, move on.
-    ;;
-*)
-    AC_MSG_ERROR([Unknown Maemo Version.  Try setting --with-maemo-version to 5 or 6.])
-    ;;
-esac
-
-if test $MOZ_PLATFORM_MAEMO; then
-   AC_DEFINE_UNQUOTED([MOZ_PLATFORM_MAEMO], $MOZ_PLATFORM_MAEMO)
-
-   if test -z "$MOZ_ENABLE_DBUS"; then
-       AC_MSG_ERROR([DBus is required when building for Maemo])
-   fi
-
-   MOZ_GFX_OPTIMIZE_MOBILE=1
-   MOZ_GL_DEFAULT_PROVIDER=EGL
-   MOZ_MAEMO_LIBLOCATION=
-
-   if test $MOZ_PLATFORM_MAEMO = 5; then
-      dnl if we have Xcomposite we should also have Xdamage and Xfixes
-      MOZ_CHECK_HEADERS([X11/extensions/Xdamage.h], [],
-          [AC_MSG_ERROR([Couldn't find X11/extensions/Xdamage.h which is required for composited plugins.])])
-      AC_CHECK_LIB(Xcomposite, XCompositeRedirectWindow, [XCOMPOSITE_LIBS="-lXcomposite -lXdamage -lXfixes"],
-                   [MISSING_X="$MISSING_X -lXcomposite"], $XLIBS)
-
-      AC_SUBST(XCOMPOSITE_LIBS)
-
-      PKG_CHECK_MODULES(LIBHILDONMIME,libhildonmime, _LIB_FOUND=1, _LIB_FOUND=)
-      MOZ_PLATFORM_MAEMO_LIBS="$MOZ_PLATFORM_MAEMO_LIBS $LIBHILDONMIME_LIBS"
-      MOZ_PLATFORM_MAEMO_CFLAGS="$MOZ_PLATFORM_MAEMO_CFLAGS $LIBHILDONMIME_CFLAGS"
-      if test -z "$_LIB_FOUND"; then
-         AC_MSG_ERROR([Hildon Mime is required when building for Maemo])
-      fi
-
-
-      PKG_CHECK_MODULES(LIBOSSO,libosso, _LIB_FOUND=1, _LIB_FOUND=)
-      MOZ_PLATFORM_MAEMO_LIBS="$MOZ_PLATFORM_MAEMO_LIBS $LIBOSSO_LIBS"
-      MOZ_PLATFORM_MAEMO_CFLAGS="$MOZ_PLATFORM_MAEMO_CFLAGS $LIBOSSO_CFLAGS"
-      if test -z "$_LIB_FOUND"; then
-         AC_MSG_ERROR([LibOSSO is required when building for Maemo])
-      fi
-
-      PKG_CHECK_MODULES(LIBHILDONFM,hildon-fm-2, _LIB_FOUND=1, _LIB_FOUND=)
-      MOZ_PLATFORM_MAEMO_LIBS="$MOZ_PLATFORM_MAEMO_LIBS $LIBHILDONFM_LIBS"
-      MOZ_PLATFORM_MAEMO_CFLAGS="$MOZ_PLATFORM_MAEMO_CFLAGS $LIBHILDONFM_CFLAGS"
-      if test -z "$_LIB_FOUND"; then
-         AC_MSG_ERROR([Hildon FM-2 is required when building for Maemo])
-      fi
-
-   fi
-   if test $MOZ_PLATFORM_MAEMO = 6; then
-
-      PKG_CHECK_MODULES(LIBCONTENTMANAGER, ContentManager QtSparql,
-                        _LIB_FOUND=1,
-                        _LIB_FOUND=)
-      if test "$_LIB_FOUND"; then
-         MOZ_PLATFORM_MAEMO_LIBS="$MOZ_PLATFORM_MAEMO_LIBS $LIBCONTENTMANAGER_LIBS"
-         MOZ_PLATFORM_MAEMO_CFLAGS="$MOZ_PLATFORM_MAEMO_CFLAGS $LIBCONTENTMANAGER_CFLAGS"
-         MOZ_ENABLE_CONTENTMANAGER=1
-         AC_DEFINE(MOZ_ENABLE_CONTENTMANAGER)
-      else
-         AC_MSG_WARN([Cannot find libcontentmanager and or QtSparql building for Maemo 6])
-      fi
-      AC_SUBST(MOZ_ENABLE_CONTENTMANAGER)
-
-      dnl ========================================================
-      dnl = Enable meego libcontentaction
-      dnl ========================================================
-      MOZ_ARG_ENABLE_BOOL(meegocontentaction,
-      [  --enable-meegocontentaction           Enable meegocontentaction support],
-         MOZ_MEEGOCONTENTACTION=1,
-         MOZ_MEEGOCONTENTACTION=)
-
-      if test -n "$MOZ_MEEGOCONTENTACTION"; then
-
-         PKG_CHECK_MODULES(LIBCONTENTACTION, contentaction-0.1, _LIB_FOUND=1, _LIB_FOUND=)
-         if test "$_LIB_FOUND"; then
-            MOZ_PLATFORM_MAEMO_LIBS="$MOZ_PLATFORM_MAEMO_LIBS $LIBCONTENTACTION_LIBS"
-            MOZ_PLATFORM_MAEMO_CFLAGS="$MOZ_PLATFORM_MAEMO_CFLAGS $LIBCONTENTACTION_CFLAGS"
-            MOZ_ENABLE_CONTENTACTION=1
-            AC_DEFINE(MOZ_ENABLE_CONTENTACTION)
-            AC_SUBST(MOZ_ENABLE_CONTENTACTION)
-         fi
-      fi
-
-      MOZ_ARG_ENABLE_BOOL(meegotouch,
-      [  --enable-meegotouch  Enable meegotouch support],
-         MOZ_MEEGOTOUCHENABLED=1,
-         MOZ_MEEGOTOUCHENABLED=)
-
-      if test -n "$MOZ_MEEGOTOUCHENABLED"; then
-          PKG_CHECK_MODULES(MOZ_MEEGOTOUCH, meegotouchcore, _LIB_FOUND=1, _LIB_FOUND=)
-          if test "$_LIB_FOUND"; then
-              MOZ_QT_CFLAGS="$MOZ_MEEGOTOUCH_CFLAGS $MOZ_QT_CFLAGS"
-              MOZ_QT_LIBS="$MOZ_MEEGOTOUCH_LIBS $MOZ_QT_LIBS"
-              AC_DEFINE(MOZ_ENABLE_MEEGOTOUCH)
-          else
-              AC_MSG_WARN([Cannot meegotouchcore-dev. Disabling Meegotouch support.])
-          fi
-      fi
-   fi
-
-   PKG_CHECK_MODULES(LIBLOCATION,liblocation, _LIB_FOUND=1, _LIB_FOUND=)
-   MOZ_PLATFORM_MAEMO_LIBS="$MOZ_PLATFORM_MAEMO_LIBS $LIBLOCATION_LIBS"
-   MOZ_PLATFORM_MAEMO_CFLAGS="$MOZ_PLATFORM_MAEMO_CFLAGS $LIBLOCATION_CFLAGS"
-   if test "$_LIB_FOUND"; then
-      MOZ_MAEMO_LIBLOCATION=1
-      AC_DEFINE(MOZ_MAEMO_LIBLOCATION)
-   else
-      AC_MSG_WARN([Cannot liblocation-dev. Disabling Maemo geolocation.])
-   fi
-   AC_SUBST(MOZ_MAEMO_LIBLOCATION)
-
-   PKG_CHECK_MODULES(LIBMEEGOTOUCHSHARE, ShareUiInterface-maemo-meegotouch >= 0.3.31 mdatauri, _LIB_FOUND=1, _LIB_FOUND=)
-   MOZ_PLATFORM_MAEMO_LIBS="$MOZ_PLATFORM_MAEMO_LIBS $LIBMEEGOTOUCHSHARE_LIBS"
-   MOZ_PLATFORM_MAEMO_CFLAGS="$MOZ_PLATFORM_MAEMO_CFLAGS $LIBMEEGOTOUCHSHARE_CFLAGS"
-   if test "$_LIB_FOUND"; then
-      MOZ_ENABLE_MEEGOTOUCHSHARE=1
-      AC_DEFINE(MOZ_ENABLE_MEEGOTOUCHSHARE)
-   else
-      AC_MSG_WARN([Cannot find maemo-meegotouch-interfaces-dev or libmdatauri-dev. Disabling meegotouch share ui.])
-   fi
-   AC_SUBST(MOZ_ENABLE_MEEGOTOUCHSHARE)
-
-   AC_SUBST(MOZ_PLATFORM_MAEMO_LIBS)
-   AC_SUBST(MOZ_PLATFORM_MAEMO_CFLAGS)
-fi
-
-dnl ========================================================
 dnl GL provider
 dnl ========================================================
 MOZ_GL_PROVIDER=
 MOZ_ARG_WITH_STRING(gl-provider,
 [  --with-gl-provider=ID
                           Set GL provider backend type],
 [ val=`echo $withval`
     MOZ_GL_PROVIDER="$val"])
@@ -8609,17 +8362,16 @@ AC_SUBST(RC)
 AC_SUBST(RCFLAGS)
 AC_SUBST(MC)
 AC_SUBST(WINDRES)
 AC_SUBST(IMPLIB)
 AC_SUBST(FILTER)
 AC_SUBST(BIN_FLAGS)
 AC_SUBST(MOZ_WIDGET_TOOLKIT)
 AC_SUBST(MOZ_UPDATE_XTERM)
-AC_SUBST(MOZ_PLATFORM_MAEMO)
 AC_SUBST(MOZ_AUTH_EXTENSION)
 AC_SUBST(MOZ_PERMISSIONS)
 AC_SUBST(MOZ_PREF_EXTENSIONS)
 AC_SUBST(MOZ_JS_LIBS)
 AC_SUBST(MOZ_DEBUG)
 AC_SUBST(MOZ_DEBUG_SYMBOLS)
 AC_SUBST(MOZ_DEBUG_ENABLE_DEFS)
 AC_SUBST(MOZ_DEBUG_DISABLE_DEFS)
--- a/content/base/public/nsContentUtils.h
+++ b/content/base/public/nsContentUtils.h
@@ -184,16 +184,17 @@ public:
   static nsresult Init();
 
   /**
    * Get a JSContext from the document's scope object.
    */
   static JSContext* GetContextFromDocument(nsIDocument *aDocument);
 
   static bool     IsCallerChrome();
+  static bool     ThreadsafeIsCallerChrome();
   static bool     IsCallerXBL();
 
   static bool     IsImageSrcSetDisabled();
 
   static bool LookupBindingMember(JSContext* aCx, nsIContent *aContent,
                                   JS::HandleId aId, JS::MutableHandle<JSPropertyDescriptor> aDesc);
 
   /**
--- a/content/base/public/nsINode.h
+++ b/content/base/public/nsINode.h
@@ -11,16 +11,17 @@
 #include "nsGkAtoms.h"              // for nsGkAtoms::baseURIProperty
 #include "nsIDOMNode.h"
 #include "nsINodeInfo.h"            // member (in nsCOMPtr)
 #include "nsIVariant.h"             // for use in GetUserData()
 #include "nsNodeInfoManager.h"      // for use in NodePrincipal()
 #include "nsPropertyTable.h"        // for typedefs
 #include "nsTObserverArray.h"       // for member
 #include "nsWindowMemoryReporter.h" // for NS_DECL_SIZEOF_EXCLUDING_THIS
+#include "mozilla/ErrorResult.h"
 #include "mozilla/MemoryReporting.h"
 #include "mozilla/dom/EventTarget.h" // for base class
 
 // Including 'windows.h' will #define GetClassInfo to something else.
 #ifdef XP_WIN
 #ifdef GetClassInfo
 #undef GetClassInfo
 #endif
--- a/content/base/src/nsCCUncollectableMarker.cpp
+++ b/content/base/src/nsCCUncollectableMarker.cpp
@@ -258,19 +258,18 @@ MarkDocShell(nsIDocShellTreeNode* aNode,
 
   nsCOMPtr<nsIWebNavigation> webNav = do_QueryInterface(shell);
   nsCOMPtr<nsISHistory> history;
   webNav->GetSessionHistory(getter_AddRefs(history));
   if (history) {
     int32_t i, historyCount;
     history->GetCount(&historyCount);
     for (i = 0; i < historyCount; ++i) {
-      nsCOMPtr<nsIHistoryEntry> historyEntry;
-      history->GetEntryAtIndex(i, false, getter_AddRefs(historyEntry));
-      nsCOMPtr<nsISHEntry> shEntry = do_QueryInterface(historyEntry);
+      nsCOMPtr<nsISHEntry> shEntry;
+      history->GetEntryAtIndex(i, false, getter_AddRefs(shEntry));
 
       MarkSHEntry(shEntry, aCleanupJS, aPrepareForCC);
     }
   }
 
   int32_t i, childCount;
   aNode->GetChildCount(&childCount);
   for (i = 0; i < childCount; ++i) {
--- a/content/base/src/nsContentUtils.cpp
+++ b/content/base/src/nsContentUtils.cpp
@@ -1741,29 +1741,46 @@ nsContentUtils::GetDocumentFromContext()
   }
 
   return nullptr;
 }
 
 bool
 nsContentUtils::IsCallerChrome()
 {
+  MOZ_ASSERT(NS_IsMainThread());
   bool is_caller_chrome = false;
   nsresult rv = sSecurityManager->SubjectPrincipalIsSystem(&is_caller_chrome);
   if (NS_FAILED(rv)) {
     return false;
   }
   if (is_caller_chrome) {
     return true;
   }
 
   // If the check failed, look for UniversalXPConnect on the cx compartment.
   return xpc::IsUniversalXPConnectEnabled(GetCurrentJSContext());
 }
 
+namespace mozilla {
+namespace dom {
+namespace workers {
+extern bool IsCurrentThreadRunningChromeWorker();
+}
+}
+}
+
+bool
+nsContentUtils::ThreadsafeIsCallerChrome()
+{
+  return NS_IsMainThread() ?
+    IsCallerChrome() :
+    mozilla::dom::workers::IsCurrentThreadRunningChromeWorker();
+}
+
 bool
 nsContentUtils::IsCallerXBL()
 {
     JSContext *cx = GetCurrentJSContext();
     if (!cx)
         return false;
 
     JSCompartment *c = js::GetContextCompartment(cx);
--- a/content/base/src/nsCrossSiteListenerProxy.cpp
+++ b/content/base/src/nsCrossSiteListenerProxy.cpp
@@ -17,17 +17,16 @@
 #include "nsIStreamConverterService.h"
 #include "nsStringStream.h"
 #include "nsGkAtoms.h"
 #include "nsWhitespaceTokenizer.h"
 #include "nsIChannelEventSink.h"
 #include "nsIAsyncVerifyRedirectCallback.h"
 #include "nsCharSeparatedTokenizer.h"
 #include "nsAsyncRedirectVerifyHelper.h"
-#include "prtime.h"
 #include "nsClassHashtable.h"
 #include "nsHashKeys.h"
 #include "nsStreamUtils.h"
 #include "mozilla/Preferences.h"
 #include <algorithm>
 
 using namespace mozilla;
 
@@ -40,33 +39,33 @@ static bool gDisableCORSPrivateData = fa
 // Preflight cache
 
 class nsPreflightCache
 {
 public:
   struct TokenTime
   {
     nsCString token;
-    PRTime expirationTime;
+    TimeStamp expirationTime;
   };
 
   struct CacheEntry : public LinkedListElement<CacheEntry>
   {
     CacheEntry(nsCString& aKey)
       : mKey(aKey)
     {
       MOZ_COUNT_CTOR(nsPreflightCache::CacheEntry);
     }
     
     ~CacheEntry()
     {
       MOZ_COUNT_DTOR(nsPreflightCache::CacheEntry);
     }
 
-    void PurgeExpired(PRTime now);
+    void PurgeExpired(TimeStamp now);
     bool CheckRequest(const nsCString& aMethod,
                         const nsTArray<nsCString>& aCustomHeaders);
 
     nsCString mKey;
     nsTArray<TokenTime> mMethods;
     nsTArray<TokenTime> mHeaders;
   };
 
@@ -119,17 +118,17 @@ static bool EnsurePreflightCache()
     sPreflightCache = newCache.forget();
     return true;
   }
 
   return false;
 }
 
 void
-nsPreflightCache::CacheEntry::PurgeExpired(PRTime now)
+nsPreflightCache::CacheEntry::PurgeExpired(TimeStamp now)
 {
   uint32_t i;
   for (i = 0; i < mMethods.Length(); ++i) {
     if (now >= mMethods[i].expirationTime) {
       mMethods.RemoveElementAt(i--);
     }
   }
   for (i = 0; i < mHeaders.Length(); ++i) {
@@ -138,17 +137,17 @@ nsPreflightCache::CacheEntry::PurgeExpir
     }
   }
 }
 
 bool
 nsPreflightCache::CacheEntry::CheckRequest(const nsCString& aMethod,
                                            const nsTArray<nsCString>& aHeaders)
 {
-  PurgeExpired(PR_Now());
+  PurgeExpired(TimeStamp::NowLoRes());
 
   if (!aMethod.EqualsLiteral("GET") && !aMethod.EqualsLiteral("POST")) {
     uint32_t i;
     for (i = 0; i < mMethods.Length(); ++i) {
       if (aMethod.Equals(mMethods[i].token))
         break;
     }
     if (i == mMethods.Length()) {
@@ -209,17 +208,17 @@ nsPreflightCache::GetEntry(nsIURI* aURI,
   }
 
   NS_ASSERTION(mTable.Count() <= PREFLIGHT_CACHE_SIZE,
                "Something is borked, too many entries in the cache!");
 
   // Now enforce the max count.
   if (mTable.Count() == PREFLIGHT_CACHE_SIZE) {
     // Try to kick out all the expired entries.
-    PRTime now = PR_Now();
+    TimeStamp now = TimeStamp::NowLoRes();
     mTable.Enumerate(RemoveExpiredEntries, &now);
 
     // If that didn't remove anything then kick out the least recently used
     // entry.
     if (mTable.Count() == PREFLIGHT_CACHE_SIZE) {
       CacheEntry* lruEntry = static_cast<CacheEntry*>(mList.popLast());
       MOZ_ASSERT(lruEntry);
 
@@ -262,17 +261,17 @@ nsPreflightCache::Clear()
   mTable.Clear();
 }
 
 /* static */ PLDHashOperator
 nsPreflightCache::RemoveExpiredEntries(const nsACString& aKey,
                                            nsAutoPtr<CacheEntry>& aValue,
                                            void* aUserData)
 {
-  PRTime* now = static_cast<PRTime*>(aUserData);
+  TimeStamp* now = static_cast<TimeStamp*>(aUserData);
   
   aValue->PurgeExpired(*now);
   
   if (aValue->mHeaders.IsEmpty() &&
       aValue->mMethods.IsEmpty()) {
     // Expired, remove from the list as well as the hash table.
     aValue->removeFrom(sPreflightCache->mList);
     return PL_DHASH_REMOVE;
@@ -894,18 +893,17 @@ nsCORSPreflightListener::AddResultToCach
 
   // String seems fine, go ahead and cache.
   // Note that we have already checked that these headers follow the correct
   // syntax.
 
   nsCOMPtr<nsIURI> uri;
   NS_GetFinalChannelURI(http, getter_AddRefs(uri));
 
-  // PR_Now gives microseconds
-  PRTime expirationTime = PR_Now() + (uint64_t)age * PR_USEC_PER_SEC;
+  TimeStamp expirationTime = TimeStamp::NowLoRes() + TimeDuration::FromSeconds(age);
 
   nsPreflightCache::CacheEntry* entry =
     sPreflightCache->GetEntry(uri, mReferrerPrincipal, mWithCredentials,
                               true);
   if (!entry) {
     return;
   }
 
--- a/content/base/src/nsGkAtomList.h
+++ b/content/base/src/nsGkAtomList.h
@@ -2007,17 +2007,16 @@ GK_ATOM(images_in_menus, "images-in-menu
 GK_ATOM(images_in_buttons, "images-in-buttons")
 GK_ATOM(overlay_scrollbars, "overlay-scrollbars")
 GK_ATOM(windows_default_theme, "windows-default-theme")
 GK_ATOM(mac_graphite_theme, "mac-graphite-theme")
 GK_ATOM(mac_lion_theme, "mac-lion-theme")
 GK_ATOM(windows_compositor, "windows-compositor")
 GK_ATOM(windows_glass, "windows-glass")
 GK_ATOM(touch_enabled, "touch-enabled")
-GK_ATOM(maemo_classic, "maemo-classic")
 GK_ATOM(menubar_drag, "menubar-drag")
 GK_ATOM(swipe_animation_enabled, "swipe-animation-enabled")
 GK_ATOM(physical_home_button, "physical-home-button")
 
 // windows theme selector metrics
 GK_ATOM(windows_classic, "windows-classic")
 GK_ATOM(windows_theme_aero, "windows-theme-aero")
 GK_ATOM(windows_theme_aero_lite, "windows-theme-aero-lite")
@@ -2048,17 +2047,16 @@ GK_ATOM(_moz_windows_default_theme, "-mo
 GK_ATOM(_moz_mac_graphite_theme, "-moz-mac-graphite-theme")
 GK_ATOM(_moz_mac_lion_theme, "-moz-mac-lion-theme")
 GK_ATOM(_moz_windows_compositor, "-moz-windows-compositor")
 GK_ATOM(_moz_windows_classic, "-moz-windows-classic")
 GK_ATOM(_moz_windows_glass, "-moz-windows-glass")
 GK_ATOM(_moz_windows_theme, "-moz-windows-theme")
 GK_ATOM(_moz_os_version, "-moz-os-version")
 GK_ATOM(_moz_touch_enabled, "-moz-touch-enabled")
-GK_ATOM(_moz_maemo_classic, "-moz-maemo-classic")
 GK_ATOM(_moz_menubar_drag, "-moz-menubar-drag")
 GK_ATOM(_moz_device_pixel_ratio, "-moz-device-pixel-ratio")
 GK_ATOM(_moz_device_orientation, "-moz-device-orientation")
 GK_ATOM(_moz_is_resource_document, "-moz-is-resource-document")
 GK_ATOM(_moz_swipe_animation_enabled, "-moz-swipe-animation-enabled")
 GK_ATOM(_moz_physical_home_button, "-moz-physical-home-button")
 
 // application commands
--- a/content/base/src/nsMixedContentBlocker.cpp
+++ b/content/base/src/nsMixedContentBlocker.cpp
@@ -477,22 +477,24 @@ nsMixedContentBlocker::ShouldLoad(uint32
 
   // If the content is display content, and the pref says display content should be blocked, block it.
   if (sBlockMixedDisplay && classification == eMixedDisplay) {
     if (allowMixedContent) {
       LogMixedContentMessage(classification, aContentLocation, rootDoc, eUserOverride);
       *aDecision = nsIContentPolicy::ACCEPT;
       rootDoc->SetHasMixedActiveContentLoaded(true);
       if (!rootDoc->GetHasMixedDisplayContentLoaded() && NS_SUCCEEDED(stateRV)) {
+        rootDoc->SetHasMixedDisplayContentLoaded(true);
         eventSink->OnSecurityChange(aRequestingContext, (State | nsIWebProgressListener::STATE_LOADED_MIXED_DISPLAY_CONTENT));
       }
     } else {
       *aDecision = nsIContentPolicy::REJECT_REQUEST;
       LogMixedContentMessage(classification, aContentLocation, rootDoc, eBlocked);
       if (!rootDoc->GetHasMixedDisplayContentBlocked() && NS_SUCCEEDED(stateRV)) {
+        rootDoc->SetHasMixedDisplayContentBlocked(true);
         eventSink->OnSecurityChange(aRequestingContext, (State | nsIWebProgressListener::STATE_BLOCKED_MIXED_DISPLAY_CONTENT));
       }
     }
     return NS_OK;
 
   } else if (sBlockMixedScript && classification == eMixedScript) {
     // If the content is active content, and the pref says active content should be blocked, block it
     // unless the user has choosen to override the pref
--- a/content/base/src/nsObjectLoadingContent.cpp
+++ b/content/base/src/nsObjectLoadingContent.cpp
@@ -2671,22 +2671,16 @@ nsObjectLoadingContent::GetSrcURI(nsIURI
   return NS_OK;
 }
 
 static bool
 DoDelayedStop(nsPluginInstanceOwner* aInstanceOwner,
               nsObjectLoadingContent* aContent,
               bool aDelayedStop)
 {
-#if (MOZ_PLATFORM_MAEMO==5)
-  // Don't delay stop on Maemo/Hildon (bug 530739).
-  if (aDelayedStop && aInstanceOwner->MatchPluginName("Shockwave Flash"))
-    return false;
-#endif
-
   // Don't delay stopping QuickTime (bug 425157), Flip4Mac (bug 426524),
   // XStandard (bug 430219), CMISS Zinc (bug 429604).
   if (aDelayedStop
 #if !(defined XP_WIN || defined MOZ_X11)
       && !aInstanceOwner->MatchPluginName("QuickTime")
       && !aInstanceOwner->MatchPluginName("Flip4Mac")
       && !aInstanceOwner->MatchPluginName("XStandard plugin")
       && !aInstanceOwner->MatchPluginName("CMISS Zinc Plugin")
--- a/content/base/test/test_CrossSiteXHR_cache.html
+++ b/content/base/test/test_CrossSiteXHR_cache.html
@@ -449,18 +449,20 @@ function runTest() {
       headers: test.headers,
     };
 
     sec = { allowOrigin: test.noOrigin ? "" : origin,
             allowHeaders: test.allowHeaders,
             allowMethods: test.allowMethods,
             cacheTime: test.cacheTime };
     xhr = new XMLHttpRequest();
-    xhr.open("POST", setStateURL + escape(sec.toSource()), false);
+    xhr.open("POST", setStateURL + escape(sec.toSource()), true);
+    xhr.onloadend = function() { gen.next(); }
     xhr.send();
+    yield undefined;
 
     loaderWindow.postMessage(req.toSource(), origin);
 
     res = eval(yield);
 
     testName = test.toSource() + " (index " + tests.indexOf(test) + ")";
 
     if (test.pass) {
--- a/content/events/public/EventTarget.h
+++ b/content/events/public/EventTarget.h
@@ -3,29 +3,31 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef mozilla_dom_EventTarget_h_
 #define mozilla_dom_EventTarget_h_
 
 #include "nsIDOMEventTarget.h"
 #include "nsWrapperCache.h"
-#include "nsIDOMEventListener.h"
-#include "mozilla/ErrorResult.h"
-#include "mozilla/dom/Nullable.h"
 #include "nsIAtom.h"
 
 class nsDOMEvent;
 class nsIDOMWindow;
+class nsIDOMEventListener;
 
 namespace mozilla {
+
+class ErrorResult;
+
 namespace dom {
 
 class EventListener;
 class EventHandlerNonNull;
+template <class T> class Nullable;
 
 // IID for the dom::EventTarget interface
 #define NS_EVENTTARGET_IID \
 { 0x0a5aed21, 0x0bab, 0x48b3, \
  { 0xbe, 0x4b, 0xd4, 0xf9, 0xd4, 0xea, 0xc7, 0xdb } }
 
 class EventTarget : public nsIDOMEventTarget,
                     public nsWrapperCache
--- a/content/events/src/DOMWheelEvent.cpp
+++ b/content/events/src/DOMWheelEvent.cpp
@@ -1,17 +1,16 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set ts=2 et sw=2 tw=80: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "DOMWheelEvent.h"
 #include "nsGUIEvent.h"
-#include "nsIContent.h"
 #include "prtime.h"
 
 namespace mozilla {
 namespace dom {
 
 DOMWheelEvent::DOMWheelEvent(EventTarget* aOwner,
                              nsPresContext* aPresContext,
                              widget::WheelEvent* aWheelEvent)
--- a/content/events/src/SpeechRecognitionError.cpp
+++ b/content/events/src/SpeechRecognitionError.cpp
@@ -1,14 +1,13 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-#include "nsDOMClassInfoID.h"
 #include "SpeechRecognitionError.h"
 
 namespace mozilla {
 namespace dom {
 
 SpeechRecognitionError::SpeechRecognitionError(mozilla::dom::EventTarget* aOwner, nsPresContext* aPresContext, nsEvent* aEvent)
 : nsDOMEvent(aOwner, aPresContext, aEvent),
   mError()
--- a/content/events/src/TextComposition.h
+++ b/content/events/src/TextComposition.h
@@ -5,26 +5,23 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef mozilla_TextComposition_h
 #define mozilla_TextComposition_h
 
 #include "nsCOMPtr.h"
 #include "nsEvent.h"
 #include "nsINode.h"
-#include "nsString.h"
 #include "nsTArray.h"
 #include "nsThreadUtils.h"
 #include "mozilla/Attributes.h"
 
-class nsCompositionEvent;
 class nsDispatchingCallback;
 class nsIMEStateManager;
 class nsIWidget;
-class nsPresContext;
 
 namespace mozilla {
 
 /**
  * TextComposition represents a text composition.  This class stores the
  * composition event target and its presContext.  At dispatching the event via
  * this class, the instances use the stored event target.
  */
--- a/content/events/src/Touch.cpp
+++ b/content/events/src/Touch.cpp
@@ -2,20 +2,18 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "mozilla/dom/Touch.h"
 
 #include "mozilla/dom/EventTarget.h"
 #include "mozilla/dom/TouchBinding.h"
-#include "mozilla/Preferences.h"
 #include "nsContentUtils.h"
 #include "nsDOMTouchEvent.h"
-#include "nsPresContext.h"
 
 namespace mozilla {
 namespace dom {
 
 Touch::Touch(mozilla::dom::EventTarget* aTarget,
              int32_t aIdentifier,
              int32_t aPageX,
              int32_t aPageY,
--- a/content/events/src/nsContentEventHandler.h
+++ b/content/events/src/nsContentEventHandler.h
@@ -1,26 +1,22 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef nsContentEventHandler_h__
 #define nsContentEventHandler_h__
 
-#include "nscore.h"
 #include "nsCOMPtr.h"
 
 #include "nsISelection.h"
 #include "nsRange.h"
-#include "nsIDOMTreeWalker.h"
 
 class nsCaret;
-class nsIContent;
-class nsIPresShell;
 class nsPresContext;
 class nsQueryContentEvent;
 class nsSelectionEvent;
 
 struct nsRect;
 
 /*
  * Query Content Event Handler
--- a/content/events/src/nsDOMAnimationEvent.h
+++ b/content/events/src/nsDOMAnimationEvent.h
@@ -2,20 +2,19 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 #ifndef nsDOMAnimationEvent_h_
 #define nsDOMAnimationEvent_h_
 
 #include "nsDOMEvent.h"
 #include "nsIDOMAnimationEvent.h"
-#include "nsString.h"
 #include "mozilla/dom/AnimationEventBinding.h"
 
-class nsAnimationEvent;
+class nsAString;
 
 class nsDOMAnimationEvent : public nsDOMEvent,
                             public nsIDOMAnimationEvent
 {
 public:
   nsDOMAnimationEvent(mozilla::dom::EventTarget* aOwner,
                       nsPresContext *aPresContext,
                       nsAnimationEvent *aEvent);
--- a/content/events/src/nsDOMClipboardEvent.cpp
+++ b/content/events/src/nsDOMClipboardEvent.cpp
@@ -1,15 +1,14 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsDOMClipboardEvent.h"
-#include "nsClientRect.h"
 #include "nsDOMDataTransfer.h"
 #include "nsIClipboard.h"
 
 nsDOMClipboardEvent::nsDOMClipboardEvent(mozilla::dom::EventTarget* aOwner,
                                          nsPresContext* aPresContext,
                                          nsClipboardEvent* aEvent)
   : nsDOMEvent(aOwner, aPresContext, aEvent ? aEvent :
                new nsClipboardEvent(false, 0))
--- a/content/events/src/nsDOMDataTransfer.cpp
+++ b/content/events/src/nsDOMDataTransfer.cpp
@@ -2,36 +2,30 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "mozilla/Util.h"
 
 #include "nsDOMDataTransfer.h"
 
-#include "prlog.h"
-#include "nsString.h"
 #include "nsIDOMDocument.h"
-#include "nsIServiceManager.h"
-#include "nsIInterfaceRequestorUtils.h"
 #include "nsIVariant.h"
 #include "nsISupportsPrimitives.h"
 #include "nsDOMClassInfoID.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsDOMLists.h"
 #include "nsGUIEvent.h"
 #include "nsError.h"
 #include "nsIDragService.h"
 #include "nsIClipboard.h"
-#include "nsIScriptableRegion.h"
 #include "nsContentUtils.h"
 #include "nsIContent.h"
 #include "nsCRT.h"
 #include "nsIScriptObjectPrincipal.h"
-#include "nsIWebNavigation.h"
 #include "nsIScriptContext.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 NS_IMPL_CYCLE_COLLECTION_CLASS(nsDOMDataTransfer)
 
 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsDOMDataTransfer)
--- a/content/events/src/nsDOMDataTransfer.h
+++ b/content/events/src/nsDOMDataTransfer.h
@@ -6,26 +6,26 @@
 #ifndef nsDOMDataTransfer_h__
 #define nsDOMDataTransfer_h__
 
 #include "nsString.h"
 #include "nsTArray.h"
 #include "nsIVariant.h"
 #include "nsIPrincipal.h"
 #include "nsIDOMDataTransfer.h"
-#include "nsIDragService.h"
 #include "nsIDOMElement.h"
 #include "nsCycleCollectionParticipant.h"
 
 #include "nsAutoPtr.h"
-#include "nsIFile.h"
 #include "nsDOMFile.h"
 #include "mozilla/Attributes.h"
 
 class nsITransferable;
+class nsISupportsArray;
+class nsILoadContext;
 
 /**
  * TransferItem is used to hold data for a particular format. Each piece of
  * data has a principal set from the caller which added it. This allows a
  * caller that wishes to retrieve the data to only be able to access the data
  * it is allowed to, yet still allow a chrome caller to retrieve any of the
  * data.
  */
--- a/content/events/src/nsDOMDragEvent.cpp
+++ b/content/events/src/nsDOMDragEvent.cpp
@@ -1,19 +1,18 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsDOMDragEvent.h"
-#include "nsIServiceManager.h"
 #include "nsGUIEvent.h"
 #include "nsContentUtils.h"
-#include "nsDOMDataTransfer.h"
-#include "nsIDragService.h"
+#include "nsIDOMDataTransfer.h"
+#include "prtime.h"
 
 nsDOMDragEvent::nsDOMDragEvent(mozilla::dom::EventTarget* aOwner,
                                nsPresContext* aPresContext,
                                nsInputEvent* aEvent)
   : nsDOMMouseEvent(aOwner, aPresContext, aEvent ? aEvent :
                     new nsDragEvent(false, 0, nullptr))
 {
   if (aEvent) {
--- a/content/events/src/nsDOMDragEvent.h
+++ b/content/events/src/nsDOMDragEvent.h
@@ -5,18 +5,16 @@
 
 #ifndef nsDOMDragEvent_h__
 #define nsDOMDragEvent_h__
 
 #include "nsIDOMDragEvent.h"
 #include "nsDOMMouseEvent.h"
 #include "mozilla/dom/DragEventBinding.h"
 
-class nsEvent;
-
 class nsDOMDragEvent : public nsDOMMouseEvent,
                        public nsIDOMDragEvent
 {
 public:
   nsDOMDragEvent(mozilla::dom::EventTarget* aOwner,
                  nsPresContext* aPresContext, nsInputEvent* aEvent);
   virtual ~nsDOMDragEvent();
 
--- a/content/events/src/nsDOMEvent.cpp
+++ b/content/events/src/nsDOMEvent.cpp
@@ -1,39 +1,28 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "base/basictypes.h"
 
-/* This must occur *after* base/basictypes.h to avoid typedefs conflicts. */
-#include "mozilla/Util.h"
-
 #include "ipc/IPCMessageUtils.h"
 #include "nsCOMPtr.h"
 #include "nsError.h"
 #include "nsDOMEvent.h"
 #include "nsEventStateManager.h"
 #include "nsIFrame.h"
 #include "nsIContent.h"
 #include "nsIPresShell.h"
 #include "nsIDocument.h"
-#include "nsIInterfaceRequestor.h"
-#include "nsIInterfaceRequestorUtils.h"
-#include "nsGkAtoms.h"
 #include "nsMutationEvent.h"
 #include "nsContentUtils.h"
 #include "nsJSEnvironment.h"
-#include "nsIURI.h"
-#include "nsIScriptSecurityManager.h"
-#include "nsIScriptError.h"
 #include "mozilla/Preferences.h"
-#include "nsJSUtils.h"
-#include "DictionaryHelpers.h"
 #include "nsLayoutUtils.h"
 #include "nsIScrollableFrame.h"
 #include "nsDOMEventTargetHelper.h"
 #include "nsPIWindowRoot.h"
 #include "nsGlobalWindow.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
@@ -329,16 +318,19 @@ NS_IMETHODIMP_(void)
 nsDOMEvent::SetTrusted(bool aTrusted)
 {
   mEvent->mFlags.mIsTrusted = aTrusted;
 }
 
 bool
 nsDOMEvent::Init(mozilla::dom::EventTarget* aGlobal)
 {
+  if (!mIsMainThreadEvent) {
+    return nsContentUtils::ThreadsafeIsCallerChrome();
+  }
   bool trusted = false;
   nsCOMPtr<nsPIDOMWindow> w = do_QueryInterface(aGlobal);
   if (w) {
     nsCOMPtr<nsIDocument> d = w->GetExtantDoc();
     if (d) {
       trusted = nsContentUtils::IsChromeDoc(d);
       nsIPresShell* s = d->GetShell();
       if (s) {
@@ -474,17 +466,17 @@ nsDOMEvent::SetEventType(const nsAString
 NS_IMETHODIMP
 nsDOMEvent::InitEvent(const nsAString& aEventTypeArg, bool aCanBubbleArg, bool aCancelableArg)
 {
   // Make sure this event isn't already being dispatched.
   NS_ENSURE_TRUE(!mEvent->mFlags.mIsBeingDispatched, NS_OK);
 
   if (IsTrusted()) {
     // Ensure the caller is permitted to dispatch trusted DOM events.
-    if (!nsContentUtils::IsCallerChrome()) {
+    if (!nsContentUtils::ThreadsafeIsCallerChrome()) {
       SetTrusted(false);
     }
   }
 
   SetEventType(aEventTypeArg);
 
   mEvent->mFlags.mBubbles = aCanBubbleArg;
   mEvent->mFlags.mCancelable = aCancelableArg;
@@ -506,145 +498,148 @@ nsDOMEvent::DuplicatePrivateData()
   
   NS_ASSERTION(mEvent, "No nsEvent for nsDOMEvent duplication!");
   if (mEventIsInternal) {
     return NS_OK;
   }
 
   nsEvent* newEvent = nullptr;
   uint32_t msg = mEvent->message;
-  bool isInputEvent = false;
 
   switch (mEvent->eventStructType) {
     case NS_EVENT:
     {
       newEvent = new nsEvent(false, msg);
+      newEvent->AssignEventData(*mEvent, true);
       break;
     }
     case NS_GUI_EVENT:
     {
+      nsGUIEvent* oldGUIEvent = static_cast<nsGUIEvent*>(mEvent);
       // Not copying widget, it is a weak reference.
-      newEvent = new nsGUIEvent(false, msg, nullptr);
+      nsGUIEvent* guiEvent = new nsGUIEvent(false, msg, nullptr);
+      guiEvent->AssignGUIEventData(*oldGUIEvent, true);
+      newEvent = guiEvent;
       break;
     }
     case NS_SCROLLBAR_EVENT:
     {
-      newEvent = new nsScrollbarEvent(false, msg, nullptr);
-      static_cast<nsScrollbarEvent*>(newEvent)->position =
-        static_cast<nsScrollbarEvent*>(mEvent)->position;
+      nsScrollbarEvent* oldScrollbarEvent =
+        static_cast<nsScrollbarEvent*>(mEvent);
+      nsScrollbarEvent* scrollbarEvent =
+        new nsScrollbarEvent(false, msg, nullptr);
+      scrollbarEvent->AssignGUIEventData(*scrollbarEvent, true);
+      scrollbarEvent->position = oldScrollbarEvent->position;
+      newEvent = scrollbarEvent;
       break;
     }
     case NS_INPUT_EVENT:
     {
-      newEvent = new nsInputEvent(false, msg, nullptr);
-      isInputEvent = true;
+      nsInputEvent* oldInputEvent = static_cast<nsInputEvent*>(mEvent);
+      nsInputEvent* inputEvent = new nsInputEvent(false, msg, nullptr);
+      inputEvent->AssignInputEventData(*oldInputEvent, true);
+      newEvent = inputEvent;
       break;
     }
     case NS_KEY_EVENT:
     {
+      nsKeyEvent* oldKeyEvent = static_cast<nsKeyEvent*>(mEvent);
       nsKeyEvent* keyEvent = new nsKeyEvent(false, msg, nullptr);
-      nsKeyEvent* oldKeyEvent = static_cast<nsKeyEvent*>(mEvent);
-      isInputEvent = true;
-      keyEvent->keyCode = oldKeyEvent->keyCode;
-      keyEvent->charCode = oldKeyEvent->charCode;
-      keyEvent->location = oldKeyEvent->location;
-      keyEvent->isChar = oldKeyEvent->isChar;
-      keyEvent->mKeyNameIndex = oldKeyEvent->mKeyNameIndex;
+      keyEvent->AssignKeyEventData(*oldKeyEvent, true);
       newEvent = keyEvent;
       break;
     }
     case NS_MOUSE_EVENT:
     {
       nsMouseEvent* oldMouseEvent = static_cast<nsMouseEvent*>(mEvent);
       nsMouseEvent* mouseEvent =
         new nsMouseEvent(false, msg, nullptr, oldMouseEvent->reason);
-      isInputEvent = true;
-      mouseEvent->clickCount = oldMouseEvent->clickCount;
-      mouseEvent->acceptActivation = oldMouseEvent->acceptActivation;
-      mouseEvent->context = oldMouseEvent->context;
-      mouseEvent->relatedTarget = oldMouseEvent->relatedTarget;
-      mouseEvent->button = oldMouseEvent->button;
-      mouseEvent->buttons = oldMouseEvent->buttons;
-      mouseEvent->pressure = oldMouseEvent->pressure;
-      mouseEvent->inputSource = oldMouseEvent->inputSource;
+      mouseEvent->AssignMouseEventData(*oldMouseEvent, true);
       newEvent = mouseEvent;
       break;
     }
     case NS_DRAG_EVENT:
     {
       nsDragEvent* oldDragEvent = static_cast<nsDragEvent*>(mEvent);
       nsDragEvent* dragEvent =
         new nsDragEvent(false, msg, nullptr);
-      isInputEvent = true;
+      dragEvent->AssignInputEventData(*oldDragEvent, true);
       dragEvent->dataTransfer = oldDragEvent->dataTransfer;
       dragEvent->clickCount = oldDragEvent->clickCount;
       dragEvent->acceptActivation = oldDragEvent->acceptActivation;
       dragEvent->relatedTarget = oldDragEvent->relatedTarget;
       dragEvent->button = oldDragEvent->button;
       dragEvent->buttons = oldDragEvent->buttons;
       static_cast<nsMouseEvent*>(dragEvent)->inputSource =
         static_cast<nsMouseEvent*>(oldDragEvent)->inputSource;
       newEvent = dragEvent;
       break;
     }
     case NS_CLIPBOARD_EVENT:
     {
       nsClipboardEvent* oldClipboardEvent = static_cast<nsClipboardEvent*>(mEvent);
       nsClipboardEvent* clipboardEvent = new nsClipboardEvent(false, msg);
+      clipboardEvent->AssignEventData(*oldClipboardEvent, true);
       clipboardEvent->clipboardData = oldClipboardEvent->clipboardData;
       newEvent = clipboardEvent;
       break;
     }
     case NS_SCRIPT_ERROR_EVENT:
     {
-      newEvent = new nsScriptErrorEvent(false, msg);
-      static_cast<nsScriptErrorEvent*>(newEvent)->lineNr =
-        static_cast<nsScriptErrorEvent*>(mEvent)->lineNr;
+      nsScriptErrorEvent* oldScriptErrorEvent =
+        static_cast<nsScriptErrorEvent*>(mEvent);
+      nsScriptErrorEvent* scriptErrorEvent = new nsScriptErrorEvent(false, msg);
+      scriptErrorEvent->AssignEventData(*oldScriptErrorEvent, true);
+      scriptErrorEvent->lineNr = oldScriptErrorEvent->lineNr;
+      newEvent = scriptErrorEvent;
       break;
     }
     case NS_TEXT_EVENT:
     {
-      newEvent = new nsTextEvent(false, msg, nullptr);
-      isInputEvent = true;
+      nsTextEvent* oldTextEvent = static_cast<nsTextEvent*>(mEvent);
+      nsTextEvent* textEvent = new nsTextEvent(false, msg, nullptr);
+      textEvent->AssignGUIEventData(*oldTextEvent, true);
+      newEvent = textEvent;
       break;
     }
     case NS_COMPOSITION_EVENT:
     {
       nsCompositionEvent* compositionEvent =
         new nsCompositionEvent(false, msg, nullptr);
       nsCompositionEvent* oldCompositionEvent =
         static_cast<nsCompositionEvent*>(mEvent);
+      compositionEvent->AssignGUIEventData(*oldCompositionEvent, true);
       compositionEvent->data = oldCompositionEvent->data;
       newEvent = compositionEvent;
       break;
     }
     case NS_MOUSE_SCROLL_EVENT:
     {
+      nsMouseScrollEvent* oldMouseScrollEvent =
+        static_cast<nsMouseScrollEvent*>(mEvent);
       nsMouseScrollEvent* mouseScrollEvent =
         new nsMouseScrollEvent(false, msg, nullptr);
-      isInputEvent = true;
-      nsMouseScrollEvent* oldMouseScrollEvent =
-        static_cast<nsMouseScrollEvent*>(mEvent);
+      mouseScrollEvent->AssignInputEventData(*oldMouseScrollEvent, true);
       mouseScrollEvent->isHorizontal = oldMouseScrollEvent->isHorizontal;
       mouseScrollEvent->delta = oldMouseScrollEvent->delta;
       mouseScrollEvent->relatedTarget = oldMouseScrollEvent->relatedTarget;
       mouseScrollEvent->button = oldMouseScrollEvent->button;
       mouseScrollEvent->buttons = oldMouseScrollEvent->buttons;
       static_cast<nsMouseEvent_base*>(mouseScrollEvent)->inputSource =
         static_cast<nsMouseEvent_base*>(oldMouseScrollEvent)->inputSource;
       newEvent = mouseScrollEvent;
       break;
     }
     case NS_WHEEL_EVENT:
     {
+      widget::WheelEvent* oldWheelEvent =
+        static_cast<widget::WheelEvent*>(mEvent);
       widget::WheelEvent* wheelEvent =
         new widget::WheelEvent(false, msg, nullptr);
-      isInputEvent = true;
-      widget::WheelEvent* oldWheelEvent =
-        static_cast<widget::WheelEvent*>(mEvent);
+      wheelEvent->AssignInputEventData(*oldWheelEvent, true);
       wheelEvent->deltaX = oldWheelEvent->deltaX;
       wheelEvent->deltaY = oldWheelEvent->deltaY;
       wheelEvent->deltaZ = oldWheelEvent->deltaZ;
       wheelEvent->deltaMode = oldWheelEvent->deltaMode;
       wheelEvent->relatedTarget = oldWheelEvent->relatedTarget;
       wheelEvent->button = oldWheelEvent->button;
       wheelEvent->buttons = oldWheelEvent->buttons;
       wheelEvent->modifiers = oldWheelEvent->modifiers;
@@ -657,140 +652,159 @@ nsDOMEvent::DuplicatePrivateData()
       wheelEvent->scrollType = oldWheelEvent->scrollType;
       wheelEvent->overflowDeltaX = oldWheelEvent->overflowDeltaX;
       wheelEvent->overflowDeltaY = oldWheelEvent->overflowDeltaY;
       newEvent = wheelEvent;
       break;
     }
     case NS_SCROLLPORT_EVENT:
     {
-      newEvent = new nsScrollPortEvent(false, msg, nullptr);
-      static_cast<nsScrollPortEvent*>(newEvent)->orient =
-        static_cast<nsScrollPortEvent*>(mEvent)->orient;
+      nsScrollPortEvent* oldScrollPortEvent =
+        static_cast<nsScrollPortEvent*>(mEvent);
+      nsScrollPortEvent* scrollPortEvent =
+        new nsScrollPortEvent(false, msg, nullptr);
+      scrollPortEvent->AssignGUIEventData(*oldScrollPortEvent, true);
+      scrollPortEvent->orient = oldScrollPortEvent->orient;
+      newEvent = scrollPortEvent;
       break;
     }
     case NS_SCROLLAREA_EVENT:
     {
-      nsScrollAreaEvent *newScrollAreaEvent = 
+      nsScrollAreaEvent* oldScrollAreaEvent =
+        static_cast<nsScrollAreaEvent*>(mEvent);
+      nsScrollAreaEvent* scrollAreaEvent = 
         new nsScrollAreaEvent(false, msg, nullptr);
-      newScrollAreaEvent->mArea =
-        static_cast<nsScrollAreaEvent *>(mEvent)->mArea;
-      newEvent = newScrollAreaEvent;
+      scrollAreaEvent->AssignGUIEventData(*oldScrollAreaEvent, true);
+      scrollAreaEvent->mArea = oldScrollAreaEvent->mArea;
+      newEvent = scrollAreaEvent;
       break;
     }
     case NS_MUTATION_EVENT:
     {
       nsMutationEvent* mutationEvent = new nsMutationEvent(false, msg);
       nsMutationEvent* oldMutationEvent =
         static_cast<nsMutationEvent*>(mEvent);
+      mutationEvent->AssignEventData(*oldMutationEvent, true);
       mutationEvent->mRelatedNode = oldMutationEvent->mRelatedNode;
       mutationEvent->mAttrName = oldMutationEvent->mAttrName;
       mutationEvent->mPrevAttrValue = oldMutationEvent->mPrevAttrValue;
       mutationEvent->mNewAttrValue = oldMutationEvent->mNewAttrValue;
       mutationEvent->mAttrChange = oldMutationEvent->mAttrChange;
       newEvent = mutationEvent;
       break;
     }
     case NS_FORM_EVENT:
     {
-      newEvent = new nsFormEvent(false, msg);
+      nsFormEvent* oldFormEvent = static_cast<nsFormEvent*>(mEvent);
+      nsFormEvent* formEvent = new nsFormEvent(false, msg);
+      formEvent->AssignEventData(*oldFormEvent, true);
+      newEvent = formEvent;
       break;
     }
     case NS_FOCUS_EVENT:
     {
       nsFocusEvent* newFocusEvent = new nsFocusEvent(false, msg);
       nsFocusEvent* oldFocusEvent = static_cast<nsFocusEvent*>(mEvent);
+      newFocusEvent->AssignGUIEventData(*oldFocusEvent, true);
       newFocusEvent->fromRaise = oldFocusEvent->fromRaise;
       newFocusEvent->isRefocus = oldFocusEvent->isRefocus;
       newEvent = newFocusEvent;
       break;
     }
     case NS_COMMAND_EVENT:
     {
-      newEvent = new nsCommandEvent(false, mEvent->userType,
-        static_cast<nsCommandEvent*>(mEvent)->command, nullptr);
+      nsCommandEvent* oldCommandEvent = static_cast<nsCommandEvent*>(mEvent);
+      nsCommandEvent* commandEvent =
+        new nsCommandEvent(false, mEvent->userType,
+                           oldCommandEvent->command, nullptr);
+      commandEvent->AssignGUIEventData(*oldCommandEvent, true);
+      newEvent = commandEvent;
       break;
     }
     case NS_UI_EVENT:
     {
-      newEvent = new nsUIEvent(false, msg,
-                               static_cast<nsUIEvent*>(mEvent)->detail);
+      nsUIEvent* oldUIEvent = static_cast<nsUIEvent*>(mEvent);
+      nsUIEvent* uiEvent = new nsUIEvent(false, msg, oldUIEvent->detail);
+      uiEvent->AssignEventData(*oldUIEvent, true);
+      newEvent = uiEvent;
       break;
     }
     case NS_SVGZOOM_EVENT:
     {
-      newEvent = new nsGUIEvent(false, msg, nullptr);
-      newEvent->eventStructType = NS_SVGZOOM_EVENT;
+      nsGUIEvent* oldGUIEvent = static_cast<nsGUIEvent*>(mEvent);
+      nsGUIEvent* guiEvent = new nsGUIEvent(false, msg, nullptr);
+      guiEvent->eventStructType = NS_SVGZOOM_EVENT;
+      guiEvent->AssignGUIEventData(*oldGUIEvent, true);
+      newEvent = guiEvent;
       break;
     }
     case NS_SMIL_TIME_EVENT:
     {
-      newEvent = new nsUIEvent(false, msg, 0);
-      newEvent->eventStructType = NS_SMIL_TIME_EVENT;
+      nsUIEvent* oldUIEvent = static_cast<nsUIEvent*>(mEvent);
+      nsUIEvent* uiEvent = new nsUIEvent(false, msg, 0);
+      uiEvent->eventStructType = NS_SMIL_TIME_EVENT;
+      uiEvent->AssignGUIEventData(*oldUIEvent, true);
+      newEvent = uiEvent;
       break;
     }
     case NS_SIMPLE_GESTURE_EVENT:
     {
-      nsSimpleGestureEvent* oldSimpleGestureEvent = static_cast<nsSimpleGestureEvent*>(mEvent);
+      nsSimpleGestureEvent* oldSimpleGestureEvent =
+        static_cast<nsSimpleGestureEvent*>(mEvent);
       nsSimpleGestureEvent* simpleGestureEvent = 
         new nsSimpleGestureEvent(false, msg, nullptr, 0, 0.0);
-      isInputEvent = true;
+      simpleGestureEvent->AssignInputEventData(*oldSimpleGestureEvent, true);
       simpleGestureEvent->direction = oldSimpleGestureEvent->direction;
       simpleGestureEvent->delta = oldSimpleGestureEvent->delta;
       simpleGestureEvent->clickCount = oldSimpleGestureEvent->clickCount;
       newEvent = simpleGestureEvent;
       break;
     }
     case NS_TRANSITION_EVENT:
     {
       nsTransitionEvent* oldTransitionEvent =
         static_cast<nsTransitionEvent*>(mEvent);
-      newEvent = new nsTransitionEvent(false, msg,
-                                       oldTransitionEvent->propertyName,
-                                       oldTransitionEvent->elapsedTime,
-                                       oldTransitionEvent->pseudoElement);
+      nsTransitionEvent* transitionEvent =
+         new nsTransitionEvent(false, msg,
+                               oldTransitionEvent->propertyName,
+                               oldTransitionEvent->elapsedTime,
+                               oldTransitionEvent->pseudoElement);
+      transitionEvent->AssignEventData(*oldTransitionEvent, true);
+      newEvent = transitionEvent;
       break;
     }
     case NS_ANIMATION_EVENT:
     {
       nsAnimationEvent* oldAnimationEvent =
         static_cast<nsAnimationEvent*>(mEvent);
-      newEvent = new nsAnimationEvent(false, msg,
-                                      oldAnimationEvent->animationName,
-                                      oldAnimationEvent->elapsedTime,
-                                      oldAnimationEvent->pseudoElement);
+      nsAnimationEvent* animationEvent =
+        new nsAnimationEvent(false, msg,
+                             oldAnimationEvent->animationName,
+                             oldAnimationEvent->elapsedTime,
+                             oldAnimationEvent->pseudoElement);
+      animationEvent->AssignEventData(*oldAnimationEvent, true);
+      newEvent = animationEvent;
       break;
     }
     case NS_TOUCH_EVENT:
     {
-      nsTouchEvent *oldTouchEvent = static_cast<nsTouchEvent*>(mEvent);
-      newEvent = new nsTouchEvent(false, oldTouchEvent);
-      isInputEvent = true;
+      nsTouchEvent* oldTouchEvent = static_cast<nsTouchEvent*>(mEvent);
+      nsTouchEvent* touchEvent = new nsTouchEvent(false, oldTouchEvent);
+      touchEvent->AssignInputEventData(*oldTouchEvent, true);
+      newEvent = touchEvent;
       break;
     }
     default:
     {
       NS_WARNING("Unknown event type!!!");
       return NS_ERROR_FAILURE;
     }
   }
 
-  if (isInputEvent) {
-    nsInputEvent* oldInputEvent = static_cast<nsInputEvent*>(mEvent);
-    nsInputEvent* newInputEvent = static_cast<nsInputEvent*>(newEvent);
-    newInputEvent->modifiers = oldInputEvent->modifiers;
-  }
-
-  newEvent->target                 = mEvent->target;
-  newEvent->currentTarget          = mEvent->currentTarget;
-  newEvent->originalTarget         = mEvent->originalTarget;
-  newEvent->mFlags                 = mEvent->mFlags;
-  newEvent->time                   = mEvent->time;
-  newEvent->refPoint               = mEvent->refPoint;
-  newEvent->userType               = mEvent->userType;
+  newEvent->mFlags = mEvent->mFlags;
 
   mEvent = newEvent;
   mPresContext = nullptr;
   mEventIsInternal = true;
   mPrivateDataDuplicated = true;
 
   return NS_OK;
 }
--- a/content/events/src/nsDOMEventTargetHelper.cpp
+++ b/content/events/src/nsDOMEventTargetHelper.cpp
@@ -1,22 +1,19 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsDOMEventTargetHelper.h"
 #include "nsContentUtils.h"
 #include "nsEventDispatcher.h"
-#include "nsGUIEvent.h"
 #include "nsIDocument.h"
-#include "nsDOMJSUtils.h"
 #include "prprf.h"
 #include "nsGlobalWindow.h"
-#include "nsDOMEvent.h"
 #include "mozilla/Likely.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 NS_IMPL_CYCLE_COLLECTION_CLASS(nsDOMEventTargetHelper)
 
 NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(nsDOMEventTargetHelper)
--- a/content/events/src/nsDOMEventTargetHelper.h
+++ b/content/events/src/nsDOMEventTargetHelper.h
@@ -12,18 +12,16 @@
 #include "nsPIDOMWindow.h"
 #include "nsIScriptGlobalObject.h"
 #include "nsEventListenerManager.h"
 #include "nsIScriptContext.h"
 #include "nsThreadUtils.h"
 #include "mozilla/Attributes.h"
 #include "mozilla/dom/EventTarget.h"
 
-class nsDOMEvent;
-
 #define NS_DOMEVENTTARGETHELPER_IID \
 { 0xda0e6d40, 0xc17b, 0x4937, \
   { 0x8e, 0xa2, 0x99, 0xca, 0x1c, 0x81, 0xea, 0xbe } }
 
 class nsDOMEventTargetHelper : public mozilla::dom::EventTarget
 {
 public:
   nsDOMEventTargetHelper()
--- a/content/events/src/nsDOMMouseEvent.h
+++ b/content/events/src/nsDOMMouseEvent.h
@@ -5,18 +5,16 @@
 
 #ifndef nsDOMMouseEvent_h__
 #define nsDOMMouseEvent_h__
 
 #include "nsIDOMMouseEvent.h"
 #include "nsDOMUIEvent.h"
 #include "mozilla/dom/MouseEventBinding.h"
 
-class nsEvent;
-
 class nsDOMMouseEvent : public nsDOMUIEvent,
                         public nsIDOMMouseEvent
 {
 public:
   nsDOMMouseEvent(mozilla::dom::EventTarget* aOwner,
                   nsPresContext* aPresContext, nsInputEvent* aEvent);
   virtual ~nsDOMMouseEvent();
 
--- a/content/events/src/nsDOMNotifyAudioAvailableEvent.h
+++ b/content/events/src/nsDOMNotifyAudioAvailableEvent.h
@@ -4,20 +4,21 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef nsDOMNotifyAudioAvailableEvent_h_
 #define nsDOMNotifyAudioAvailableEvent_h_
 
 #include "nsIDOMNotifyAudioAvailableEvent.h"
 #include "nsDOMEvent.h"
-#include "nsPresContext.h"
 #include "nsCycleCollectionParticipant.h"
 #include "mozilla/dom/NotifyAudioAvailableEventBinding.h"
 
+class nsPresContext;
+
 class nsDOMNotifyAudioAvailableEvent : public nsDOMEvent,
                                        public nsIDOMNotifyAudioAvailableEvent
 {
 public:
   nsDOMNotifyAudioAvailableEvent(mozilla::dom::EventTarget* aOwner,
                                  nsPresContext* aPresContext, nsEvent* aEvent,
                                  uint32_t aEventType, float * aFrameBuffer,
                                  uint32_t aFrameBufferLength, float aTime);
--- a/content/events/src/nsDOMNotifyPaintEvent.cpp
+++ b/content/events/src/nsDOMNotifyPaintEvent.cpp
@@ -5,17 +5,16 @@
 
 #include "base/basictypes.h"
 #include "ipc/IPCMessageUtils.h"
 #include "mozilla/GfxMessageUtils.h"
 #include "nsDOMNotifyPaintEvent.h"
 #include "nsContentUtils.h"
 #include "nsClientRect.h"
 #include "nsPaintRequest.h"
-#include "nsIFrame.h"
 
 nsDOMNotifyPaintEvent::nsDOMNotifyPaintEvent(mozilla::dom::EventTarget* aOwner,
                                              nsPresContext* aPresContext,
                                              nsEvent* aEvent,
                                              uint32_t aEventType,
                                              nsInvalidateRequestList* aInvalidateRequests)
 : nsDOMEvent(aOwner, aPresContext, aEvent)
 {
--- a/content/events/src/nsDOMScrollAreaEvent.h
+++ b/content/events/src/nsDOMScrollAreaEvent.h
@@ -5,17 +5,16 @@
 
 #ifndef nsDOMScrollAreaEvent_h__
 #define nsDOMScrollAreaEvent_h__
 
 #include "mozilla/Attributes.h"
 #include "nsIDOMScrollAreaEvent.h"
 #include "nsDOMUIEvent.h"
 
-#include "nsGUIEvent.h"
 #include "nsClientRect.h"
 #include "mozilla/dom/ScrollAreaEventBinding.h"
 
 class nsDOMScrollAreaEvent : public nsDOMUIEvent,
                              public nsIDOMScrollAreaEvent
 {
 public:
   nsDOMScrollAreaEvent(mozilla::dom::EventTarget* aOwner,
--- a/content/events/src/nsDOMTouchEvent.cpp
+++ b/content/events/src/nsDOMTouchEvent.cpp
@@ -3,17 +3,16 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsDOMTouchEvent.h"
 #include "nsGUIEvent.h"
 #include "nsContentUtils.h"
 #include "mozilla/Preferences.h"
-#include "nsPresContext.h"
 #include "mozilla/dom/Touch.h"
 #include "mozilla/dom/TouchListBinding.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 // TouchList
 
--- a/content/events/src/nsDOMTouchEvent.h
+++ b/content/events/src/nsDOMTouchEvent.h
@@ -1,23 +1,24 @@
 /* vim: set shiftwidth=2 tabstop=8 autoindent cindent expandtab: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 #ifndef nsDOMTouchEvent_h_
 #define nsDOMTouchEvent_h_
 
 #include "nsDOMUIEvent.h"
-#include "nsString.h"
 #include "nsTArray.h"
 #include "mozilla/Attributes.h"
 #include "nsJSEnvironment.h"
 #include "mozilla/dom/TouchEventBinding.h"
 #include "nsWrapperCache.h"
 
+class nsAString;
+
 class nsDOMTouchList MOZ_FINAL : public nsISupports
                                , public nsWrapperCache
 {
   typedef mozilla::dom::Touch Touch;
 
 public:
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
   NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(nsDOMTouchList)
--- a/content/events/src/nsDOMTransitionEvent.h
+++ b/content/events/src/nsDOMTransitionEvent.h
@@ -2,20 +2,19 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 #ifndef nsDOMTransitionEvent_h_
 #define nsDOMTransitionEvent_h_
 
 #include "nsDOMEvent.h"
 #include "nsIDOMTransitionEvent.h"
-#include "nsString.h"
 #include "mozilla/dom/TransitionEventBinding.h"
 
-class nsTransitionEvent;
+class nsAString;
 
 class nsDOMTransitionEvent : public nsDOMEvent,
                              public nsIDOMTransitionEvent
 {
 public:
   nsDOMTransitionEvent(mozilla::dom::EventTarget* aOwner,
                        nsPresContext *aPresContext,
                        nsTransitionEvent *aEvent);
--- a/content/events/src/nsDOMUIEvent.cpp
+++ b/content/events/src/nsDOMUIEvent.cpp
@@ -2,25 +2,23 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "base/basictypes.h"
 #include "ipc/IPCMessageUtils.h"
 #include "nsCOMPtr.h"
 #include "nsDOMUIEvent.h"
-#include "nsIPresShell.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsIDOMWindow.h"
 #include "nsIDOMNode.h"
 #include "nsIContent.h"
 #include "nsContentUtils.h"
 #include "nsEventStateManager.h"
 #include "nsIFrame.h"
-#include "nsIScrollableFrame.h"
 #include "mozilla/Util.h"
 #include "mozilla/Assertions.h"
 #include "prtime.h"
 
 using namespace mozilla;
 
 nsDOMUIEvent::nsDOMUIEvent(mozilla::dom::EventTarget* aOwner,
                            nsPresContext* aPresContext, nsGUIEvent* aEvent)
--- a/content/events/src/nsEventDispatcher.cpp
+++ b/content/events/src/nsEventDispatcher.cpp
@@ -1,26 +1,24 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsEventDispatcher.h"
-#include "nsDOMEvent.h"
 #include "nsPresContext.h"
 #include "nsEventListenerManager.h"
 #include "nsContentUtils.h"
 #include "nsCxPusher.h"
 #include "nsError.h"
 #include "nsMutationEvent.h"
 #include <new>
 #include "nsINode.h"
 #include "nsPIDOMWindow.h"
-#include "nsFrameLoader.h"
 #include "nsDOMTouchEvent.h"
 #include "GeckoProfiler.h"
 #include "GeneratedEvents.h"
 #include "mozilla/dom/EventTarget.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
@@ -657,17 +655,17 @@ nsEventDispatcher::DispatchDOMEvent(nsIS
       innerEvent->target = nullptr;
       innerEvent->originalTarget = nullptr;
     } else {
       aDOMEvent->GetIsTrusted(&dontResetTrusted);
     }
 
     if (!dontResetTrusted) {
       //Check security state to determine if dispatcher is trusted
-      aDOMEvent->SetTrusted(nsContentUtils::IsCallerChrome());
+      aDOMEvent->SetTrusted(nsContentUtils::ThreadsafeIsCallerChrome());
     }
 
     return nsEventDispatcher::Dispatch(aTarget, aPresContext, innerEvent,
                                        aDOMEvent, aEventStatus);
   } else if (aEvent) {
     return nsEventDispatcher::Dispatch(aTarget, aPresContext, aEvent,
                                        aDOMEvent, aEventStatus);
   }
--- a/content/events/src/nsEventListenerManager.cpp
+++ b/content/events/src/nsEventListenerManager.cpp
@@ -1,63 +1,48 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+#ifdef MOZ_B2G
 #include "mozilla/Hal.h"
+#endif
 #include "mozilla/HalSensor.h"
 
 // Microsoft's API Name hackery sucks
 #undef CreateEvent
 
 #include "nsISupports.h"
 #include "nsGUIEvent.h"
 #include "nsDOMEvent.h"
 #include "nsEventListenerManager.h"
-#include "nsCaret.h"
 #include "nsIDOMEventListener.h"
-#include "nsITextControlFrame.h"
 #include "nsGkAtoms.h"
 #include "nsPIDOMWindow.h"
 #include "nsIJSEventListener.h"
 #include "nsIScriptGlobalObject.h"
-#include "nsLayoutUtils.h"
 #include "nsINameSpaceManager.h"
 #include "nsIContent.h"
 #include "mozilla/MemoryReporting.h"
-#include "mozilla/dom/Element.h"
-#include "nsIFrame.h"
-#include "nsView.h"
-#include "nsViewManager.h"
 #include "nsCOMPtr.h"
-#include "nsIServiceManager.h"
-#include "nsIScriptSecurityManager.h"
 #include "nsError.h"
 #include "nsIDocument.h"
-#include "nsIPresShell.h"
 #include "nsMutationEvent.h"
 #include "nsIXPConnect.h"
 #include "nsDOMCID.h"
-#include "nsFocusManager.h"
-#include "nsIDOMElement.h"
 #include "nsContentUtils.h"
 #include "nsCxPusher.h"
 #include "nsJSUtils.h"
-#include "nsContentCID.h"
 #include "nsEventDispatcher.h"
-#include "nsDOMJSUtils.h"
-#include "nsDataHashtable.h"
 #include "nsCOMArray.h"
 #include "nsEventListenerService.h"
 #include "nsIContentSecurityPolicy.h"
-#include "nsJSEnvironment.h"
 #include "xpcpublic.h"
 #include "nsSandboxFlags.h"
-#include "mozilla/dom/time/TimeChangeObserver.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 using namespace mozilla::hal;
 
 #define EVENT_TYPE_EQUALS(ls, type, userType, typeString, allEvents) \
   ((ls->mEventType == type &&                                        \
     (ls->mEventType != NS_USER_DEFINED_EVENT ||                      \
--- a/content/events/src/nsEventListenerManager.h
+++ b/content/events/src/nsEventListenerManager.h
@@ -3,41 +3,37 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef nsEventListenerManager_h__
 #define nsEventListenerManager_h__
 
 #include "mozilla/dom/EventListenerBinding.h"
 #include "mozilla/MemoryReporting.h"
-#include "nsAutoPtr.h"
-#include "nsCOMArray.h"
 #include "nsCOMPtr.h"
-#include "nsCxPusher.h"
 #include "nsCycleCollectionParticipant.h"
 #include "nsGkAtoms.h"
 #include "nsGUIEvent.h"
 #include "nsIDOMEventListener.h"
 #include "nsIJSEventListener.h"
-#include "nsIScriptContext.h"
 #include "nsTObserverArray.h"
 
 class nsIDOMEvent;
-class nsIAtom;
-class nsIWidget;
-struct nsPoint;
 struct EventTypeData;
 class nsEventTargetChainItem;
 class nsPIDOMWindow;
 class nsCxPusher;
 class nsIEventListenerInfo;
+class nsIScriptContext;
 
 struct nsListenerStruct;
 class nsEventListenerManager;
 
+template<class T> class nsCOMArray;
+
 namespace mozilla {
 namespace dom {
 
 class EventTarget;
 
 typedef CallbackObjectHolder<EventListener, nsIDOMEventListener>
   EventListenerHolder;
 
--- a/content/events/src/nsEventListenerService.cpp
+++ b/content/events/src/nsEventListenerService.cpp
@@ -1,31 +1,28 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 #include "nsEventListenerService.h"
 #include "nsCOMArray.h"
 #include "nsEventListenerManager.h"
-#include "nsIVariant.h"
-#include "nsIServiceManager.h"
 #include "nsMemory.h"
 #include "nsCxPusher.h"
 #include "nsIXPConnect.h"
-#include "nsIDOMWindow.h"
-#include "nsPIDOMWindow.h"
 #include "nsJSUtils.h"
 #include "nsGUIEvent.h"
 #include "nsEventDispatcher.h"
 #include "nsIJSEventListener.h"
 #ifdef MOZ_JSDEBUGGER
 #include "jsdIDebuggerService.h"
 #endif
 #include "nsDOMClassInfoID.h"
 #include "mozilla/Maybe.h"
+#include "nsServiceManagerUtils.h"
 
 using namespace mozilla::dom;
 using mozilla::AutoSafeJSContext;
 
 NS_IMPL_CYCLE_COLLECTION_1(nsEventListenerInfo, mListener)
 
 DOMCI_DATA(EventListenerInfo, nsEventListenerInfo)
 
--- a/content/events/src/nsEventStateManager.cpp
+++ b/content/events/src/nsEventStateManager.cpp
@@ -5,17 +5,16 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "mozilla/Attributes.h"
 #include "mozilla/MathAlgorithms.h"
 #include "mozilla/dom/TabParent.h"
 
 #include "nsCOMPtr.h"
 #include "nsEventStateManager.h"
-#include "nsEventListenerManager.h"
 #include "nsIMEStateManager.h"
 #include "nsContentEventHandler.h"
 #include "nsIContent.h"
 #include "nsINodeInfo.h"
 #include "nsIDocument.h"
 #include "nsIFrame.h"
 #include "nsIWidget.h"
 #include "nsPresContext.h"
@@ -30,45 +29,30 @@
 #include "nsINameSpaceManager.h"
 #include "nsIBaseWindow.h"
 #include "nsISelection.h"
 #include "nsFrameSelection.h"
 #include "nsPIDOMWindow.h"
 #include "nsPIWindowRoot.h"
 #include "nsIWebNavigation.h"
 #include "nsIContentViewer.h"
-#include <algorithm>
-#ifdef MOZ_XUL
-#include "nsXULPopupManager.h"
-#endif
 #include "nsFrameManager.h"
 
-#include "nsIServiceManager.h"
-#include "nsIScriptSecurityManager.h"
-
-#include "nsFocusManager.h"
-
 #include "nsIDOMXULElement.h"
-#include "nsIDOMDocument.h"
 #include "nsIDOMKeyEvent.h"
 #include "nsIObserverService.h"
 #include "nsIDocShell.h"
 #include "nsIMarkupDocumentViewer.h"
 #include "nsIDOMWheelEvent.h"
 #include "nsIDOMDragEvent.h"
 #include "nsIDOMUIEvent.h"
 #include "nsDOMDragEvent.h"
-#include "nsIDOMNSEditableElement.h"
-#include "nsIDOMMozBrowserFrame.h"
 #include "nsIMozBrowserFrame.h"
 
-#include "nsCaret.h"
-
 #include "nsSubDocumentFrame.h"
-#include "nsLayoutCID.h"
 #include "nsLayoutUtils.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsUnicharUtils.h"
 #include "nsContentUtils.h"
 
 #include "imgIContainer.h"
 #include "nsIProperties.h"
 #include "nsISupportsPrimitives.h"
@@ -83,24 +67,21 @@
 #include "nsDOMDataTransfer.h"
 #include "nsContentAreaDragDrop.h"
 #ifdef MOZ_XUL
 #include "nsTreeBodyFrame.h"
 #endif
 #include "nsIController.h"
 #include "nsICommandParams.h"
 #include "mozilla/Services.h"
-#include "mozAutoDocUpdate.h"
 #include "mozilla/dom/HTMLLabelElement.h"
 
 #include "mozilla/Preferences.h"
 #include "mozilla/LookAndFeel.h"
 #include "GeckoProfiler.h"
-
-#include "nsIDOMClientRect.h"
 #include "Units.h"
 
 #ifdef XP_MACOSX
 #import <ApplicationServices/ApplicationServices.h>
 #endif
 
 using namespace mozilla;
 using namespace mozilla::dom;
--- a/content/events/src/nsEventStateManager.h
+++ b/content/events/src/nsEventStateManager.h
@@ -7,39 +7,36 @@
 #define nsEventStateManager_h__
 
 #include "mozilla/TypedEnum.h"
 
 #include "nsEvent.h"
 #include "nsGUIEvent.h"
 #include "nsIObserver.h"
 #include "nsWeakReference.h"
-#include "nsITimer.h"
 #include "nsCOMPtr.h"
 #include "nsCOMArray.h"
-#include "nsIFrameLoader.h"
 #include "nsCycleCollectionParticipant.h"
-#include "nsIMarkupDocumentViewer.h"
-#include "nsIScrollableFrame.h"
 #include "nsFocusManager.h"
-#include "nsEventStates.h"
 #include "mozilla/TimeStamp.h"
 #include "nsIFrame.h"
 #include "Units.h"
 
-class nsIPresShell;
 class nsIContent;
 class nsIDocument;
 class nsIDocShell;
 class nsIDocShellTreeNode;
 class nsIDocShellTreeItem;
 class imgIContainer;
 class nsDOMDataTransfer;
 class MouseEnterLeaveDispatcher;
-class nsIFrame;
+class nsEventStates;
+class nsIMarkupDocumentViewer;
+class nsIScrollableFrame;
+class nsITimer;
 
 namespace mozilla {
 namespace dom {
 class TabParent;
 }
 }
 
 /*
--- a/content/events/src/nsIMEStateManager.cpp
+++ b/content/events/src/nsIMEStateManager.cpp
@@ -1,25 +1,21 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set ts=2 sw=2 et tw=80: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsIMEStateManager.h"
 #include "nsCOMPtr.h"
-#include "nsViewManager.h"
 #include "nsIPresShell.h"
 #include "nsISupports.h"
-#include "nsPIDOMWindow.h"
-#include "nsIInterfaceRequestorUtils.h"
 #include "nsIContent.h"
 #include "nsIDocument.h"
 #include "nsPresContext.h"
-#include "nsIDOMWindow.h"
 #include "nsIDOMMouseEvent.h"
 #include "nsContentUtils.h"
 #include "nsINode.h"
 #include "nsIFrame.h"
 #include "nsRange.h"
 #include "nsIDOMRange.h"
 #include "nsISelection.h"
 #include "nsISelectionPrivate.h"
@@ -28,20 +24,20 @@
 #include "nsIMutationObserver.h"
 #include "nsContentEventHandler.h"
 #include "nsIObserverService.h"
 #include "mozilla/Services.h"
 #include "nsIFormControl.h"
 #include "nsIForm.h"
 #include "mozilla/dom/HTMLFormElement.h"
 #include "mozilla/Attributes.h"
-#include "nsEventDispatcher.h"
 #include "TextComposition.h"
 #include "mozilla/Preferences.h"
 #include "nsAsyncDOMEvent.h"
+#include "nsGUIEvent.h"
 
 using namespace mozilla;
 using namespace mozilla::widget;
 
 // nsTextStateManager notifies widget of any text and selection changes
 //  in the currently focused editor
 // sTextStateObserver points to the currently active nsTextStateManager
 // sTextStateObserver is null if there is no focused editor
--- a/content/events/src/nsIMEStateManager.h
+++ b/content/events/src/nsIMEStateManager.h
@@ -1,17 +1,16 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef nsIMEStateManager_h__
 #define nsIMEStateManager_h__
 
-#include "nscore.h"
 #include "nsEvent.h"
 #include "nsIWidget.h"
 
 class nsDispatchingCallback;
 class nsIContent;
 class nsIDOMMouseEvent;
 class nsINode;
 class nsPIDOMWindow;
--- a/content/events/src/nsPaintRequest.cpp
+++ b/content/events/src/nsPaintRequest.cpp
@@ -1,18 +1,18 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsPaintRequest.h"
 
-#include "nsIFrame.h"
 #include "mozilla/dom/PaintRequestBinding.h"
 #include "mozilla/dom/PaintRequestListBinding.h"
+#include "nsClientRect.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE_1(nsPaintRequest, mParent)
 
 NS_INTERFACE_TABLE_HEAD(nsPaintRequest)
   NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
--- a/content/events/src/nsPaintRequest.h
+++ b/content/events/src/nsPaintRequest.h
@@ -5,19 +5,20 @@
 
 #ifndef NSPAINTREQUEST_H_
 #define NSPAINTREQUEST_H_
 
 #include "nsIDOMPaintRequest.h"
 #include "nsPresContext.h"
 #include "nsIDOMEvent.h"
 #include "mozilla/Attributes.h"
-#include "nsClientRect.h"
 #include "nsWrapperCache.h"
 
+class nsClientRect;
+
 class nsPaintRequest MOZ_FINAL : public nsIDOMPaintRequest
                                , public nsWrapperCache
 {
 public:
   nsPaintRequest(nsIDOMEvent* aParent)
     : mParent(aParent)
   {
     mRequest.mFlags = 0;
--- a/content/media/MediaResource.h
+++ b/content/media/MediaResource.h
@@ -188,17 +188,18 @@ inline MediaByteRange::MediaByteRange(Ti
  * support efficient random access, such as HTTP.
  *
  * Instances of this class must be created on the main thread.
  * Most methods must be called on the main thread only. Read, Seek and
  * Tell must only be called on non-main threads. In the case of the Ogg
  * Decoder they are called on the Decode thread for example. You must
  * ensure that no threads are calling these methods once Close is called.
  *
- * Instances of this class are explicitly managed. 'delete' it when done.
+ * Instances of this class are reference counted. Use nsRefPtr for
+ * managing the lifetime of instances of this class.
  *
  * The generic implementation of this class is ChannelMediaResource, which can
  * handle any URI for which Necko supports AsyncOpen.
  * The 'file:' protocol can be implemented efficiently with direct random
  * access, so the FileMediaResource implementation class bypasses the cache.
  * MediaResource::Create automatically chooses the best implementation class.
  */
 class MediaResource
--- a/content/media/plugins/MediaPluginHost.cpp
+++ b/content/media/plugins/MediaPluginHost.cpp
@@ -9,16 +9,17 @@
 #include "mozilla/dom/HTMLMediaElement.h"
 #include "MediaPluginHost.h"
 #include "nsXPCOMStrings.h"
 #include "nsISeekableStream.h"
 #include "MediaPluginReader.h"
 #include "nsIGfxInfo.h"
 #include "gfxCrashReporterUtils.h"
 #include "prmem.h"
+#include "MediaResourceServer.h"
 
 #include "MPAPI.h"
 
 #if defined(ANDROID) || defined(MOZ_WIDGET_GONK)
 #include "android/log.h"
 #define ALOG(args...)  __android_log_print(ANDROID_LOG_INFO, "MediaPluginHost" , ## args)
 #else
 #define ALOG(args...) /* do nothing */
@@ -28,50 +29,19 @@ using namespace MPAPI;
 
 Decoder::Decoder() :
   mResource(NULL), mPrivate(NULL)
 {
 }
 
 namespace mozilla {
 
-static MediaResource *GetResource(Decoder *aDecoder)
-{
-  return reinterpret_cast<MediaResource *>(aDecoder->mResource);
-}
-
-static bool Read(Decoder *aDecoder, char *aBuffer, int64_t aOffset, uint32_t aCount, uint32_t* aBytes)
+static char* GetResource(Decoder *aDecoder)
 {
-  MediaResource *resource = GetResource(aDecoder);
-  if (aOffset != resource->Tell()) {
-    nsresult rv = resource->Seek(nsISeekableStream::NS_SEEK_SET, aOffset);
-    if (NS_FAILED(rv)) {
-      return false;
-    }
-  }
-  nsresult rv = resource->Read(aBuffer, aCount, aBytes);
-  if (NS_FAILED(rv)) {
-    return false;
-  }
-  return true;
-}
-
-static uint64_t GetLength(Decoder *aDecoder)
-{
-  return GetResource(aDecoder)->GetLength();
-}
-
-static void SetMetaDataReadMode(Decoder *aDecoder)
-{
-  GetResource(aDecoder)->SetReadMode(MediaCacheStream::MODE_METADATA);
-}
-
-static void SetPlaybackReadMode(Decoder *aDecoder)
-{
-  GetResource(aDecoder)->SetReadMode(MediaCacheStream::MODE_PLAYBACK);
+  return static_cast<char*>(aDecoder->mResource);
 }
 
 class GetIntPrefEvent : public nsRunnable {
 public:
   GetIntPrefEvent(const char* aPref, int32_t* aResult)
     : mPref(aPref), mResult(aResult) {}
   NS_IMETHOD Run() {
     return Preferences::GetInt(mPref, mResult);
@@ -87,20 +57,20 @@ static bool GetIntPref(const char* aPref
   // can only be called on the main thread. Post a runnable and wait.
   NS_ENSURE_TRUE(aPref, false);
   NS_ENSURE_TRUE(aResult, false);
   nsCOMPtr<GetIntPrefEvent> event = new GetIntPrefEvent(aPref, aResult);
   return NS_SUCCEEDED(NS_DispatchToMainThread(event, NS_DISPATCH_SYNC));
 }
 
 static PluginHost sPluginHost = {
-  Read,
-  GetLength,
-  SetMetaDataReadMode,
-  SetPlaybackReadMode,
+  nullptr,
+  nullptr,
+  nullptr,
+  nullptr,
   GetIntPref
 };
 
 // Return true if Omx decoding is supported on the device. This checks the
 // built in whitelist/blacklist and preferences to see if that is overridden.
 static bool IsOmxSupported()
 {
   bool forceEnabled =
@@ -216,16 +186,18 @@ static const char* GetOmxLibraryName()
 #else
   return nullptr;
 #endif
 }
 
 MediaPluginHost::MediaPluginHost() {
   MOZ_COUNT_CTOR(MediaPluginHost);
 
+  mResourceServer = MediaResourceServer::Start();
+
   const char* name = GetOmxLibraryName();
   ALOG("Loading OMX Plugin: %s", name ? name : "nullptr");
   if (name) {
     char *path = PR_GetLibraryFilePathname("libxul.so", (PRFuncPtr) GetOmxLibraryName);
     PRLibrary *lib = NULL;
     if (path) {
       nsAutoCString libpath(path);
       PR_Free(path);
@@ -245,16 +217,17 @@ MediaPluginHost::MediaPluginHost() {
         mPlugins.AppendElement(manifest);
         ALOG("OMX plugin successfully loaded");
      }
     }
   }
 }
 
 MediaPluginHost::~MediaPluginHost() {
+  mResourceServer->Stop();
   MOZ_COUNT_DTOR(MediaPluginHost);
 }
 
 bool MediaPluginHost::FindDecoder(const nsACString& aMimeType, const char* const** aCodecs)
 {
   const char *chars;
   size_t len = NS_CStringGetData(aMimeType, &chars, nullptr);
   for (size_t n = 0; n < mPlugins.Length(); ++n) {
@@ -272,43 +245,49 @@ bool MediaPluginHost::FindDecoder(const 
 MPAPI::Decoder *MediaPluginHost::CreateDecoder(MediaResource *aResource, const nsACString& aMimeType)
 {
   NS_ENSURE_TRUE(aResource, nullptr);
 
   nsAutoPtr<Decoder> decoder(new Decoder());
   if (!decoder) {
     return nullptr;
   }
-  decoder->mResource = aResource;
 
   const char *chars;
   size_t len = NS_CStringGetData(aMimeType, &chars, nullptr);
   for (size_t n = 0; n < mPlugins.Length(); ++n) {
     Manifest *plugin = mPlugins[n];
     const char* const *codecs;
     if (!plugin->CanDecode(chars, len, &codecs)) {
       continue;
     }
+
+    nsCString url;
+    nsresult rv = mResourceServer->AddResource(aResource, url);
+    if (NS_FAILED (rv)) continue;
+
+    decoder->mResource = strdup(url.get());
     if (plugin->CreateDecoder(&sPluginHost, decoder, chars, len)) {
       aResource->AddRef();
       return decoder.forget();
     }
   }
 
   return nullptr;
 }
 
 void MediaPluginHost::DestroyDecoder(Decoder *aDecoder)
 {
   aDecoder->DestroyDecoder(aDecoder);
-  MediaResource* resource = GetResource(aDecoder);
+  char* resource = GetResource(aDecoder);
   if (resource) {
     // resource *shouldn't* be null, but check anyway just in case the plugin
     // decoder does something stupid.
-    resource->Release();
+    mResourceServer->RemoveResource(nsCString(resource));
+    free(resource);
   }
   delete aDecoder;
 }
 
 MediaPluginHost *sMediaPluginHost = nullptr;
 MediaPluginHost *GetMediaPluginHost()
 {
   if (!sMediaPluginHost) {
--- a/content/media/plugins/MediaPluginHost.h
+++ b/content/media/plugins/MediaPluginHost.h
@@ -4,23 +4,26 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 #if !defined(MediaPluginHost_h_)
 #define MediaPluginHost_h_
 
 #include "nsTArray.h"
 #include "MediaResource.h"
 #include "MPAPI.h"
+#include "MediaResourceServer.h"
 
 namespace mozilla {
 
 class MediaPluginReader;
 
 class MediaPluginHost {
+  nsCOMPtr<MediaResourceServer> mResourceServer;
   nsTArray<MPAPI::Manifest *> mPlugins;
+
   MPAPI::Manifest *FindPlugin(const nsACString& aMimeType);
 public:
   MediaPluginHost();
   ~MediaPluginHost();
 
   static void Shutdown();
 
   bool FindDecoder(const nsACString& aMimeType, const char* const** aCodecs);
new file mode 100644
--- /dev/null
+++ b/content/media/plugins/MediaResourceServer.cpp
@@ -0,0 +1,526 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim:set ts=2 sw=2 sts=2 et cindent: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+#include "mozilla/Assertions.h"
+#include "mozilla/Base64.h"
+#include "nsThreadUtils.h"
+#include "nsIServiceManager.h"
+#include "nsISocketTransport.h"
+#include "nsIOutputStream.h"
+#include "nsIInputStream.h"
+#include "nsIRandomGenerator.h"
+#include "nsReadLine.h"
+#include "nsNetCID.h"
+#include "VideoUtils.h"
+#include "MediaResource.h"
+#include "MediaResourceServer.h"
+
+#if defined(_MSC_VER)
+#define strtoll _strtoi64
+#define snprintf _snprintf_s
+#endif
+
+using namespace mozilla;
+
+/*
+  ReadCRLF is a variant of NS_ReadLine from nsReadLine.h that deals
+  with the carriage return/line feed requirements of HTTP requests.
+*/
+template<typename CharT, class StreamType, class StringType>
+nsresult
+ReadCRLF (StreamType* aStream, nsLineBuffer<CharT> * aBuffer,
+          StringType & aLine, bool *aMore)
+{
+  // eollast is true if the last character in the buffer is a '\r',
+  // signaling a potential '\r\n' sequence split between reads.
+  bool eollast = false;
+
+  aLine.Truncate();
+
+  while (1) { // will be returning out of this loop on eol or eof
+    if (aBuffer->start == aBuffer->end) { // buffer is empty.  Read into it.
+      uint32_t bytesRead;
+      nsresult rv = aStream->Read(aBuffer->buf, kLineBufferSize, &bytesRead);
+      if (NS_FAILED(rv) || bytesRead == 0) {
+        *aMore = false;
+        return rv;
+      }
+      aBuffer->start = aBuffer->buf;
+      aBuffer->end = aBuffer->buf + bytesRead;
+      *(aBuffer->end) = '\0';
+    }
+
+    /*
+     * Walk the buffer looking for an end-of-line.
+     * There are 4 cases to consider:
+     *  1. the CR char is the last char in the buffer
+     *  2. the CRLF sequence are the last characters in the buffer
+     *  3. the CRLF sequence + one or more chars at the end of the buffer
+     *      we need at least one char after the first CRLF sequence to
+     *      set |aMore| correctly.
+     *  4. The LF character is the first char in the buffer when eollast is
+     *      true.
+     */
+    CharT* current = aBuffer->start;
+    if (eollast) { // Case 4
+      if (*current == '\n') {
+        aBuffer->start = ++current;
+        *aMore = true;
+        return NS_OK;
+      }
+      else {
+        eollast = false;
+        aLine.Append('\r');
+      }
+    }
+    // Cases 2 and 3
+    for ( ; current < aBuffer->end-1; ++current) {
+      if (*current == '\r' && *(current+1) == '\n') {
+        *current++ = '\0';
+        *current++ = '\0';
+        aLine.Append(aBuffer->start);
+        aBuffer->start = current;
+        *aMore = true;
+        return NS_OK;
+      }
+    }
+    // Case 1
+    if (*current == '\r') {
+      eollast = true;
+      *current++ = '\0';
+    }
+
+    aLine.Append(aBuffer->start);
+    aBuffer->start = aBuffer->end; // mark the buffer empty
+  }
+}
+
+// Each client HTTP request results in a thread being spawned to process it.
+// That thread has a single event dispatched to it which handles the HTTP
+// protocol. It parses the headers and forwards data from the MediaResource
+// associated with the URL back to client. When the request is complete it will
+// shutdown the thread.
+class ServeResourceEvent : public nsRunnable {
+private:
+  // Reading from this reads the data sent from the client.
+  nsCOMPtr<nsIInputStream> mInput;
+
+  // Writing to this sends data to the client.
+  nsCOMPtr<nsIOutputStream> mOutput;
+
+  // The MediaResourceServer that owns the MediaResource instances
+  // served. This is used to lookup the MediaResource from the URL.
+  nsCOMPtr<MediaResourceServer> mServer;
+
+  // Write 'aBufferLength' bytes from 'aBuffer' to 'mOutput'. This
+  // method ensures all the data is written by checking the number
+  // of bytes returned from the output streams 'Write' method and
+  // looping until done.
+  nsresult WriteAll(char const* aBuffer, int32_t aBufferLength);
+
+public:
+  ServeResourceEvent(nsIInputStream* aInput, nsIOutputStream* aOutput,
+                     MediaResourceServer* aServer)
+    : mInput(aInput), mOutput(aOutput), mServer(aServer) {}
+
+  // This method runs on the thread and exits when it has completed the
+  // HTTP request.
+  NS_IMETHOD Run();
+
+  // Given the first line of an HTTP request, parse the URL requested and
+  // return the MediaResource for that URL.
+  already_AddRefed<MediaResource> GetMediaResource(nsCString const& aHTTPRequest);
+
+  // Gracefully shutdown the thread and cleanup resources
+  void Shutdown();
+};
+
+nsresult
+ServeResourceEvent::WriteAll(char const* aBuffer, int32_t aBufferLength)
+{
+  while (aBufferLength > 0) {
+    uint32_t written = 0;
+    nsresult rv = mOutput->Write(aBuffer, aBufferLength, &written);
+    if (NS_FAILED (rv)) return rv;
+
+    aBufferLength -= written;
+    aBuffer += written;
+  }
+
+  return NS_OK;
+}
+
+already_AddRefed<MediaResource>
+ServeResourceEvent::GetMediaResource(nsCString const& aHTTPRequest)
+{
+  // Check that the HTTP method is GET
+  const char* HTTP_METHOD = "GET ";
+  if (strncmp(aHTTPRequest.get(), HTTP_METHOD, strlen(HTTP_METHOD)) != 0) {
+    return nullptr;
+  }
+
+  const char* url_start = strchr(aHTTPRequest.get(), ' ');
+  if (!url_start) {
+    return nullptr;
+  }
+
+  const char* url_end = strrchr(++url_start, ' ');
+  if (!url_end) {
+    return nullptr;
+  }
+
+  // The path extracted from the HTTP request is used as a key in hash
+  // table. It is not related to retrieving data from the filesystem so
+  // we don't need to do any sanity checking on ".." paths and similar
+  // exploits.
+  nsCString relative(url_start, url_end - url_start);
+  nsRefPtr<MediaResource> resource =
+    mServer->GetResource(mServer->GetURLPrefix() + relative);
+  return resource.forget();
+}
+
+NS_IMETHODIMP
+ServeResourceEvent::Run() {
+  bool more = false; // Are there HTTP headers to read after the first line
+  nsCString line;    // Contains the current line read from input stream
+  nsLineBuffer<char>* buffer = new nsLineBuffer<char>();
+  nsresult rv = ReadCRLF(mInput.get(), buffer, line, &more);
+  if (NS_FAILED(rv)) { Shutdown(); return rv; }
+
+  // First line contains the HTTP GET request. Extract the URL and obtain
+  // the MediaResource for it.
+  nsRefPtr<MediaResource> resource = GetMediaResource(line);
+  if (!resource) {
+    const char* response_404 = "HTTP/1.1 404 Not Found\r\n"
+                               "Content-Length: 0\r\n\r\n";
+    rv = WriteAll(response_404, strlen(response_404));
+    Shutdown();
+    return rv;
+  }
+
+  // Offset in bytes to start reading from resource.
+  // This is zero by default but can be set to another starting value if
+  // this HTTP request includes a byte range request header.
+  int64_t start = 0;
+
+  // Keep reading lines until we get a zero length line, which is the HTTP
+  // protocol's way of signifying the end of headers and start of body, or
+  // until we have no more data to read.
+  while (more && line.Length() > 0) {
+    rv = ReadCRLF(mInput.get(), buffer, line, &more);
+    if (NS_FAILED(rv)) { Shutdown(); return rv; }
+
+    // Look for a byte range request header. If there is one, set the
+    // media resource offset to start from to that requested. Here we
+    // only check for the range request format used by Android rather
+    // than implementing all possibilities in the HTTP specification.
+    // That is, the range request is of the form:
+    //   Range: bytes=nnnn-
+    // Were 'nnnn' is an integer number.
+    // The end of the range is not checked, instead we return up to
+    // the end of the resource and the client is informed of this via
+    // the content-range header.
+    NS_NAMED_LITERAL_CSTRING(byteRange, "Range: bytes=");
+    const char* s = strstr(line.get(), byteRange.get());
+    if (s) {
+      start = strtoll(s+byteRange.Length(), NULL, 10);
+
+      // Clamp 'start' to be between 0 and the resource length.
+      start = std::max(0ll, std::min(resource->GetLength(), start));
+    }
+  }
+
+  // HTTP response to use if this is a non byte range request
+  const char* response_normal = "HTTP/1.1 200 OK\r\n";
+
+  // HTTP response to use if this is a byte range request
+  const char* response_range = "HTTP/1.1 206 Partial Content\r\n";
+
+  // End of HTTP reponse headers is indicated by an empty line.
+  const char* response_end = "\r\n";
+
+  // If the request was a byte range request, we need to read from the
+  // requested offset. If the resource is non-seekable, or the seek
+  // fails, then the start offset is set back to zero. This results in all
+  // HTTP response data being as if the byte range request was not made.
+  if (start > 0 && !resource->IsTransportSeekable()) {
+    start = 0;
+  }
+
+  const char* response_line = start > 0 ?
+                                response_range :
+                                response_normal;
+  rv = WriteAll(response_line, strlen(response_line));
+  if (NS_FAILED(rv)) { Shutdown(); return NS_OK; }
+
+  // Buffer used for reading from the input stream and writing to
+  // the output stream. The buffer size should be big enough for the
+  // HTTP response headers sent below. A static_assert ensures
+  // this where the buffer is used.
+  const int buffer_size = 32768;
+  nsAutoArrayPtr<char> b(new char[buffer_size]);
+
+  // If we know the length of the resource, send a Content-Length header.
+  int64_t contentlength = resource->GetLength() - start;
+  if (contentlength > 0) {
+    static_assert (buffer_size > 1024,
+                   "buffer_size must be large enough "
+                   "to hold response headers");
+    snprintf(b, buffer_size, "Content-Length: %lld\r\n", contentlength);
+    rv = WriteAll(b, strlen(b));
+    if (NS_FAILED(rv)) { Shutdown(); return NS_OK; }
+  }
+
+  // If the request was a byte range request, respond with a Content-Range
+  // header which details the extent of the data returned.
+  if (start > 0) {
+    static_assert (buffer_size > 1024,
+                   "buffer_size must be large enough "
+                   "to hold response headers");
+    snprintf(b, buffer_size, "Content-Range: bytes %lld-%lld/%lld\r\n",
+             start, resource->GetLength() - 1, resource->GetLength());
+    rv = WriteAll(b, strlen(b));
+    if (NS_FAILED(rv)) { Shutdown(); return NS_OK; }
+  }
+
+  rv = WriteAll(response_end, strlen(response_end));
+  if (NS_FAILED(rv)) { Shutdown(); return NS_OK; }
+
+  rv = mOutput->Flush();
+  if (NS_FAILED(rv)) { Shutdown(); return NS_OK; }
+
+  // Read data from media resource
+  uint32_t bytesRead = 0; // Number of bytes read/written to streams
+  rv = resource->ReadAt(start, b, buffer_size, &bytesRead);
+  while (NS_SUCCEEDED(rv) && bytesRead != 0) {
+    // Keep track of what we think the starting position for the next read
+    // is. This is used in subsequent ReadAt calls to ensure we are reading
+    // from the correct offset in the case where another thread is reading
+    // from th same MediaResource.
+    start += bytesRead;
+
+    // Write data obtained from media resource to output stream
+    rv = WriteAll(b, bytesRead);
+    if (NS_FAILED (rv)) break;
+
+    rv = resource->ReadAt(start, b, 32768, &bytesRead);
+  }
+
+  Shutdown();
+  return NS_OK;
+}
+
+void
+ServeResourceEvent::Shutdown()
+{
+  // Cleanup resources and exit.
+  mInput->Close();
+  mOutput->Close();
+
+  // To shutdown the current thread we need to first exit this event.
+  // The Shutdown event below is posted to the main thread to do this.
+  nsCOMPtr<nsIRunnable> event = new ShutdownThreadEvent(NS_GetCurrentThread());
+  NS_DispatchToMainThread(event, NS_DISPATCH_NORMAL);
+}
+
+/*
+  This is the listener attached to the server socket. When an HTTP
+  request is made by the client the OnSocketAccepted method is
+  called. This method will spawn a thread to process the request.
+  The thread receives a single event which does the parsing of
+  the HTTP request and forwarding the data from the MediaResource
+  to the output stream of the request.
+
+  The MediaResource used for providing the request data is obtained
+  from the MediaResourceServer that created this listener, using the
+  URL the client requested.
+*/
+class ResourceSocketListener : public nsIServerSocketListener
+{
+public:
+  // The MediaResourceServer used to look up the MediaResource
+  // on requests.
+  nsCOMPtr<MediaResourceServer> mServer;
+
+public:
+  NS_DECL_THREADSAFE_ISUPPORTS
+  NS_DECL_NSISERVERSOCKETLISTENER
+
+  ResourceSocketListener(MediaResourceServer* aServer) :
+    mServer(aServer)
+  {
+  }
+
+  virtual ~ResourceSocketListener() { }
+};
+
+NS_IMPL_ISUPPORTS1(ResourceSocketListener, nsIServerSocketListener)
+
+NS_IMETHODIMP
+ResourceSocketListener::OnSocketAccepted(nsIServerSocket* aServ,
+                                         nsISocketTransport* aTrans)
+{
+  nsCOMPtr<nsIInputStream> input;
+  nsCOMPtr<nsIOutputStream> output;
+  nsresult rv;
+
+  rv = aTrans->OpenInputStream(nsITransport::OPEN_BLOCKING, 0, 0, getter_AddRefs(input));
+  if (NS_FAILED(rv)) return rv;
+
+  rv = aTrans->OpenOutputStream(nsITransport::OPEN_BLOCKING, 0, 0, getter_AddRefs(output));
+  if (NS_FAILED(rv)) return rv;
+
+  nsCOMPtr<nsIThread> thread;
+  rv = NS_NewThread(getter_AddRefs(thread));
+  if (NS_FAILED(rv)) return rv;
+
+  nsCOMPtr<nsIRunnable> event = new ServeResourceEvent(input.get(), output.get(), mServer);
+  return thread->Dispatch(event, NS_DISPATCH_NORMAL);
+}
+
+NS_IMETHODIMP
+ResourceSocketListener::OnStopListening(nsIServerSocket* aServ, nsresult aStatus)
+{
+  return NS_OK;
+}
+
+MediaResourceServer::MediaResourceServer() :
+  mMutex("MediaResourceServer")
+{
+}
+
+NS_IMETHODIMP
+MediaResourceServer::Run()
+{
+  MutexAutoLock lock(mMutex);
+
+  nsresult rv;
+  mSocket = do_CreateInstance(NS_SERVERSOCKET_CONTRACTID, &rv);
+  if (NS_FAILED(rv)) return rv;
+
+  rv = mSocket->InitSpecialConnection(-1,
+                                      nsIServerSocket::LoopbackOnly
+                                      | nsIServerSocket::KeepWhenOffline,
+                                      -1);
+  if (NS_FAILED(rv)) return rv;
+
+  rv = mSocket->AsyncListen(new ResourceSocketListener(this));
+  if (NS_FAILED(rv)) return rv;
+
+  return NS_OK;
+}
+
+/* static */
+already_AddRefed<MediaResourceServer>
+MediaResourceServer::Start()
+{
+  nsCOMPtr<MediaResourceServer> server = new MediaResourceServer();
+  NS_DispatchToMainThread(server, NS_DISPATCH_SYNC);
+  return server.forget();
+}
+
+void
+MediaResourceServer::Stop()
+{
+  MutexAutoLock lock(mMutex);
+  mSocket->Close();
+  mSocket = nullptr;
+}
+
+nsresult
+MediaResourceServer::AppendRandomPath(nsCString& aUrl)
+{
+  // Use a cryptographic quality PRNG to generate raw random bytes
+  // and convert that to a base64 string for use as an URL path. This
+  // is based on code from nsExternalAppHandler::SetUpTempFile.
+  nsresult rv;
+  nsCOMPtr<nsIRandomGenerator> rg =
+    do_GetService("@mozilla.org/security/random-generator;1", &rv);
+  if (NS_FAILED(rv)) return rv;
+
+  // For each three bytes of random data we will get four bytes of
+  // ASCII. Request a bit more to be safe and truncate to the length
+  // we want at the end.
+  const uint32_t wantedFileNameLength = 16;
+  const uint32_t requiredBytesLength =
+    static_cast<uint32_t>((wantedFileNameLength + 1) / 4 * 3);
+
+  uint8_t* buffer;
+  rv = rg->GenerateRandomBytes(requiredBytesLength, &buffer);
+  if (NS_FAILED(rv)) return rv;
+
+  nsAutoCString tempLeafName;
+  nsDependentCSubstring randomData(reinterpret_cast<const char*>(buffer),
+                                   requiredBytesLength);
+  rv = Base64Encode(randomData, tempLeafName);
+  NS_Free(buffer);
+  buffer = nullptr;
+  if (NS_FAILED (rv)) return rv;
+
+  tempLeafName.Truncate(wantedFileNameLength);
+
+  // Base64 characters are alphanumeric (a-zA-Z0-9) and '+' and '/', so we need
+  // to replace illegal characters -- notably '/'
+  tempLeafName.ReplaceChar(FILE_PATH_SEPARATOR FILE_ILLEGAL_CHARACTERS, '_');
+
+  aUrl += "/";
+  aUrl += tempLeafName;
+
+  return NS_OK;
+}
+
+nsresult
+MediaResourceServer::AddResource(mozilla::MediaResource* aResource, nsCString& aUrl)
+{
+  nsCString url = GetURLPrefix();
+  nsresult rv = AppendRandomPath(url);
+  if (NS_FAILED (rv)) return rv;
+
+  {
+    MutexAutoLock lock(mMutex);
+
+    // Adding a resource URL that already exists is considered an error.
+    if (mResources.find(aUrl) != mResources.end()) return NS_ERROR_FAILURE;
+    mResources[url] = aResource;
+  }
+
+  aUrl = url;
+
+  return NS_OK;
+}
+
+void
+MediaResourceServer::RemoveResource(nsCString const& aUrl)
+{
+  MutexAutoLock lock(mMutex);
+  mResources.erase(aUrl);
+}
+
+nsCString
+MediaResourceServer::GetURLPrefix()
+{
+  MutexAutoLock lock(mMutex);
+
+  int32_t port = 0;
+  nsresult rv = mSocket->GetPort(&port);
+  if (NS_FAILED (rv) || port < 0) {
+    return nsCString("");
+  }
+
+  char buffer[256];
+  snprintf(buffer, sizeof(buffer), "http://127.0.0.1:%d", port >= 0 ? port : 0);
+  return nsCString(buffer);
+}
+
+already_AddRefed<MediaResource>
+MediaResourceServer::GetResource(nsCString const& aUrl)
+{
+  MutexAutoLock lock(mMutex);
+  ResourceMap::const_iterator it = mResources.find(aUrl);
+  if (it == mResources.end()) return nullptr;
+
+  nsRefPtr<MediaResource> resource = it->second;
+  return resource.forget();
+}
new file mode 100644
--- /dev/null
+++ b/content/media/plugins/MediaResourceServer.h
@@ -0,0 +1,96 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim:set ts=2 sw=2 sts=2 et cindent: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+#if !defined(MediaResourceServer_h_)
+#define MediaResourceServer_h_
+
+#include <map>
+#include "nsIServerSocket.h"
+#include "MediaResource.h"
+
+namespace mozilla {
+
+class MediaResource;
+
+/*
+  MediaResourceServer instantiates a socket server that understands
+  HTTP requests for MediaResource instances. The server runs on an
+  automatically selected port and MediaResource instances are registered.
+  The registration returns a string URL than can be used to fetch the
+  resource. That URL contains a randomly generated path to make it
+  difficult for other local applications on the device to guess it.
+
+  The HTTP protocol is limited in that it supports only what the
+  Android DataSource implementation uses to fetch media. It
+  understands HTTP GET and byte range requests.
+
+  The intent of this class is to be used in Media backends that
+  have a system component that does its own network requests. These
+  requests are made against this server which then uses standard
+  Gecko network requests and media cache usage.
+
+  The MediaResourceServer can be instantiated on any thread and
+  its methods are threadsafe - they can be called on any thread.
+  The server socket itself is always run on the main thread and
+  this is done by the Start() static method by synchronously
+  dispatching to the main thread.
+*/
+class MediaResourceServer : public nsRunnable
+{
+private:
+  // Mutex protecting private members of MediaResourceServer.
+  // All member variables below this point in the class definition
+  // must acquire the mutex before access.
+  mozilla::Mutex mMutex;
+
+  // Server socket used to listen for incoming connections
+  nsCOMPtr<nsIServerSocket> mSocket;
+
+  // Mapping between MediaResource URL's to the MediaResource
+  // object served at that URL.
+  typedef std::map<nsCString,
+                  nsRefPtr<mozilla::MediaResource> > ResourceMap;
+  ResourceMap mResources;
+
+  // Create a MediaResourceServer that will listen on an automatically
+  // selected port when started. This is private as it should only be
+  // called internally from the public 'Start' method.
+  MediaResourceServer();
+  NS_IMETHOD Run();
+
+  // Append a random URL path to a string. This is used for creating a
+  // unique URl for a resource which helps prevent malicious software
+  // running on the same machine as the server from guessing the URL
+  // and accessing video data.
+  nsresult AppendRandomPath(nsCString& aURL);
+
+public:
+  // Create a MediaResourceServer and start it listening. This call will
+  // perform a synchronous request on the main thread.
+  static already_AddRefed<MediaResourceServer> Start();
+
+  // Stops the server from listening and accepting further connections.
+  void Stop();
+
+  // Add a MediaResource to be served by this server. Stores the
+  // absolute URL that can be used to access the resource in 'aUrl'.
+  nsresult AddResource(mozilla::MediaResource* aResource, nsCString& aUrl);
+
+  // Remove a MediaResource so it is no longer served by this server.
+  // The URL provided must match exactly that provided by a previous
+  // call to "AddResource".
+  void RemoveResource(nsCString const& aUrl);
+
+  // Returns the prefix for HTTP requests to the server. This plus
+  // the result of AddResource results in an Absolute URL.
+  nsCString GetURLPrefix();
+
+  // Returns the resource asociated with a given URL
+  already_AddRefed<mozilla::MediaResource> GetResource(nsCString const& aUrl);
+};
+
+} // namespace mozilla
+
+#endif
--- a/content/media/plugins/moz.build
+++ b/content/media/plugins/moz.build
@@ -6,20 +6,22 @@
 
 MODULE = 'content'
 
 EXPORTS += [
     'MPAPI.h',
     'MediaPluginDecoder.h',
     'MediaPluginHost.h',
     'MediaPluginReader.h',
+    'MediaResourceServer.h',
 ]
 
 CPP_SOURCES += [
     'MediaPluginDecoder.cpp',
     'MediaPluginHost.cpp',
     'MediaPluginReader.cpp',
+    'MediaResourceServer.cpp',
 ]
 
 LIBRARY_NAME = 'gkconmediaplugins_s'
 
 LIBXUL_LIBRARY = True
 
--- a/content/media/webrtc/Makefile.in
+++ b/content/media/webrtc/Makefile.in
@@ -14,15 +14,14 @@ OS_CXXFLAGS += -DNOMINMAX
 endif
 
 include $(topsrcdir)/config/rules.mk
 include $(topsrcdir)/ipc/chromium/chromium-config.mk
 
 ifdef MOZ_WEBRTC
 LOCAL_INCLUDES += \
   -I$(topsrcdir)/media/webrtc/trunk \
-  -I$(topsrcdir)/media/webrtc/trunk/webrtc \
   -I$(topsrcdir)/media/webrtc/signaling/src/common \
   -I$(topsrcdir)/media/webrtc/signaling/src/common/browser_logging \
   -I$(topsrcdir)/dom/base \
   -I$(topsrcdir)/dom/camera \
   $(NULL)
 endif
--- a/content/media/webrtc/MediaEngineWebRTC.h
+++ b/content/media/webrtc/MediaEngineWebRTC.h
@@ -25,31 +25,31 @@
 #include "VideoSegment.h"
 #include "AudioSegment.h"
 #include "StreamBuffer.h"
 #include "MediaStreamGraph.h"
 
 // WebRTC library includes follow
 
 // Audio Engine
-#include "voice_engine/include/voe_base.h"
-#include "voice_engine/include/voe_codec.h"
-#include "voice_engine/include/voe_hardware.h"
-#include "voice_engine/include/voe_network.h"
-#include "voice_engine/include/voe_audio_processing.h"
-#include "voice_engine/include/voe_volume_control.h"
-#include "voice_engine/include/voe_external_media.h"
-#include "voice_engine/include/voe_audio_processing.h"
+#include "webrtc/voice_engine/include/voe_base.h"
+#include "webrtc/voice_engine/include/voe_codec.h"
+#include "webrtc/voice_engine/include/voe_hardware.h"
+#include "webrtc/voice_engine/include/voe_network.h"
+#include "webrtc/voice_engine/include/voe_audio_processing.h"
+#include "webrtc/voice_engine/include/voe_volume_control.h"
+#include "webrtc/voice_engine/include/voe_external_media.h"
+#include "webrtc/voice_engine/include/voe_audio_processing.h"
 
 // Video Engine
-#include "video_engine/include/vie_base.h"
-#include "video_engine/include/vie_codec.h"
-#include "video_engine/include/vie_render.h"
-#include "video_engine/include/vie_capture.h"
-#include "video_engine/include/vie_file.h"
+#include "webrtc/video_engine/include/vie_base.h"
+#include "webrtc/video_engine/include/vie_codec.h"
+#include "webrtc/video_engine/include/vie_render.h"
+#include "webrtc/video_engine/include/vie_capture.h"
+#include "webrtc/video_engine/include/vie_file.h"
 #ifdef MOZ_B2G_CAMERA
 #include "CameraPreviewMediaStream.h"
 #include "DOMCameraManager.h"
 #include "GonkCameraControl.h"
 #include "ImageContainer.h"
 #include "nsGlobalWindow.h"
 #include "prprf.h"
 #endif
@@ -296,19 +296,19 @@ public:
                           StreamTime aDesiredTime,
                           TrackTicks &aLastEndTime);
 
   virtual bool IsFake() {
     return false;
   }
 
   // VoEMediaProcess.
-  void Process(const int channel, const webrtc::ProcessingTypes type,
-               WebRtc_Word16 audio10ms[], const int length,
-               const int samplingFreq, const bool isStereo);
+  void Process(int channel, webrtc::ProcessingTypes type,
+               int16_t audio10ms[], int length,
+               int samplingFreq, bool isStereo);
 
   NS_DECL_THREADSAFE_ISUPPORTS
 
 private:
   static const unsigned int KMaxDeviceNameLength = 128;
   static const unsigned int KMaxUniqueIdLength = 256;
 
   void Init();
--- a/content/media/webrtc/MediaEngineWebRTCAudio.cpp
+++ b/content/media/webrtc/MediaEngineWebRTCAudio.cpp
@@ -338,22 +338,22 @@ MediaEngineWebRTCAudioSource::Shutdown()
 
   mVoERender->Release();
   mVoEBase->Release();
 
   mState = kReleased;
   mInitDone = false;
 }
 
-typedef WebRtc_Word16 sample;
+typedef int16_t sample;
 
 void
-MediaEngineWebRTCAudioSource::Process(const int channel,
-  const webrtc::ProcessingTypes type, sample* audio10ms,
-  const int length, const int samplingFreq, const bool isStereo)
+MediaEngineWebRTCAudioSource::Process(int channel,
+  webrtc::ProcessingTypes type, sample* audio10ms,
+  int length, int samplingFreq, bool isStereo)
 {
   MonitorAutoLock lock(mMonitor);
   if (mState != kStarted)
     return;
 
   uint32_t len = mSources.Length();
   for (uint32_t i = 0; i < len; i++) {
     nsRefPtr<SharedBuffer> buffer = SharedBuffer::Create(length * sizeof(sample));
--- a/docshell/base/nsDocShell.cpp
+++ b/docshell/base/nsDocShell.cpp
@@ -112,17 +112,17 @@
 #include "nsIUploadChannel.h"
 #include "nsIProgressEventSink.h"
 #include "nsIWebProgress.h"
 #include "nsILayoutHistoryState.h"
 #include "nsITimer.h"
 #include "nsISHistoryInternal.h"
 #include "nsIPrincipal.h"
 #include "nsIFileURL.h"
-#include "nsIHistoryEntry.h"
+#include "nsISHEntry.h"
 #include "nsISHistoryListener.h"
 #include "nsIWindowWatcher.h"
 #include "nsIPromptFactory.h"
 #include "nsIObserver.h"
 #include "nsINestedURI.h"
 #include "nsITransportSecurityInfo.h"
 #include "nsINSSErrorsService.h"
 #include "nsIApplicationCache.h"
@@ -3778,17 +3778,17 @@ nsDocShell::AddChildSHEntry(nsISHEntry *
         /* You are currently in the rootDocShell.
          * You will get here when a subframe has a new url
          * to load and you have walked up the tree all the 
          * way to the top to clone the current SHEntry hierarchy
          * and replace the subframe where a new url was loaded with
          * a new entry.
          */
         int32_t index = -1;
-        nsCOMPtr<nsIHistoryEntry> currentHE;
+        nsCOMPtr<nsISHEntry> currentHE;
         mSessionHistory->GetIndex(&index);
         if (index < 0)
             return NS_ERROR_FAILURE;
 
         rv = mSessionHistory->GetEntryAtIndex(index, false,
                                               getter_AddRefs(currentHE));
         NS_ENSURE_TRUE(currentHE, NS_ERROR_FAILURE);
 
@@ -8044,21 +8044,18 @@ nsDocShell::CreateContentViewer(const ch
 
         // Be sure to have a correct mLSHE, it may have been cleared by
         // EndPageLoad. See bug 302115.
         if (mSessionHistory && !mLSHE) {
             int32_t idx;
             mSessionHistory->GetRequestedIndex(&idx);
             if (idx == -1)
                 mSessionHistory->GetIndex(&idx);
-
-            nsCOMPtr<nsIHistoryEntry> entry;
             mSessionHistory->GetEntryAtIndex(idx, false,
-                                             getter_AddRefs(entry));
-            mLSHE = do_QueryInterface(entry);
+                                             getter_AddRefs(mLSHE));
         }
 
         mLoadType = LOAD_ERROR_PAGE;
     }
 
     bool onLocationChangeNeeded = OnLoadingSite(aOpenedChannel, false);
 
     // let's try resetting the load group if we need to...
@@ -9150,23 +9147,21 @@ nsDocShell::InternalLoad(nsIURI * aURI,
              */
             SetHistoryEntry(&mLSHE, nullptr);
             /* Set the title for the SH entry for this target url. so that
              * SH menus in go/back/forward buttons won't be empty for this.
              */
             if (mSessionHistory) {
                 int32_t index = -1;
                 mSessionHistory->GetIndex(&index);
-                nsCOMPtr<nsIHistoryEntry> hEntry;
+                nsCOMPtr<nsISHEntry> shEntry;
                 mSessionHistory->GetEntryAtIndex(index, false,
-                                                 getter_AddRefs(hEntry));
-                NS_ENSURE_TRUE(hEntry, NS_ERROR_FAILURE);
-                nsCOMPtr<nsISHEntry> shEntry(do_QueryInterface(hEntry));
-                if (shEntry)
-                    shEntry->SetTitle(mTitle);
+                                                 getter_AddRefs(shEntry));
+                NS_ENSURE_TRUE(shEntry, NS_ERROR_FAILURE);
+                shEntry->SetTitle(mTitle);
             }
 
             /* Set the title for the Global History entry for this anchor url.
              */
             if (mUseGlobalHistory && !mInPrivateBrowsing) {
                 nsCOMPtr<IHistory> history = services::GetHistoryService();
                 if (history) {
                     history->SetURITitle(aURI, mTitle);
--- a/docshell/build/nsDocShellModule.cpp
+++ b/docshell/build/nsDocShellModule.cpp
@@ -117,17 +117,16 @@ NS_DEFINE_NAMED_CID(NS_DBUSHANDLERAPP_CI
 #endif
 #if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_ENABLE_MEEGOTOUCHSHARE)
 NS_DEFINE_NAMED_CID(NS_EXTERNALSHARINGAPPSERVICE_CID);
 #endif
 #if defined(MOZ_WIDGET_ANDROID)
 NS_DEFINE_NAMED_CID(NS_EXTERNALURLHANDLERSERVICE_CID);
 #endif
 NS_DEFINE_NAMED_CID(NS_SHENTRY_CID);
-NS_DEFINE_NAMED_CID(NS_HISTORYENTRY_CID);
 NS_DEFINE_NAMED_CID(NS_SHTRANSACTION_CID);
 NS_DEFINE_NAMED_CID(NS_SHISTORY_CID);
 NS_DEFINE_NAMED_CID(NS_SHISTORY_INTERNAL_CID);
 NS_DEFINE_NAMED_CID(NS_DOWNLOADHISTORY_CID);
 
 
 const mozilla::Module::CIDEntry kDocShellCIDs[] = {
   { &kNS_DOCSHELL_CID, false, nullptr, nsDocShellConstructor },
@@ -147,17 +146,16 @@ const mozilla::Module::CIDEntry kDocShel
 #endif
 #if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_ENABLE_MEEGOTOUCHSHARE)
   { &kNS_EXTERNALSHARINGAPPSERVICE_CID, false, nullptr, nsExternalSharingAppServiceConstructor },
 #endif
 #if defined(MOZ_WIDGET_ANDROID)
   { &kNS_EXTERNALURLHANDLERSERVICE_CID, false, nullptr, nsExternalURLHandlerServiceConstructor },
 #endif
   { &kNS_SHENTRY_CID, false, nullptr, nsSHEntryConstructor },
-  { &kNS_HISTORYENTRY_CID, false, nullptr, nsSHEntryConstructor },
   { &kNS_SHTRANSACTION_CID, false, nullptr, nsSHTransactionConstructor },
   { &kNS_SHISTORY_CID, false, nullptr, nsSHistoryConstructor },
   { &kNS_SHISTORY_INTERNAL_CID, false, nullptr, nsSHistoryConstructor },
   { &kNS_DOWNLOADHISTORY_CID, false, nullptr, nsDownloadHistoryConstructor },
   { nullptr }
 };
 
 const mozilla::Module::ContractIDEntry kDocShellContracts[] = {
@@ -200,17 +198,16 @@ const mozilla::Module::ContractIDEntry k
 #endif
 #if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_ENABLE_MEEGOTOUCHSHARE)
   { NS_EXTERNALSHARINGAPPSERVICE_CONTRACTID, &kNS_EXTERNALSHARINGAPPSERVICE_CID },
 #endif
 #if defined(MOZ_WIDGET_ANDROID)
   { NS_EXTERNALURLHANDLERSERVICE_CONTRACTID, &kNS_EXTERNALURLHANDLERSERVICE_CID },
 #endif
   { NS_SHENTRY_CONTRACTID, &kNS_SHENTRY_CID },
-  { NS_HISTORYENTRY_CONTRACTID, &kNS_HISTORYENTRY_CID },
   { NS_SHTRANSACTION_CONTRACTID, &kNS_SHTRANSACTION_CID },
   { NS_SHISTORY_CONTRACTID, &kNS_SHISTORY_CID },
   { NS_SHISTORY_INTERNAL_CONTRACTID, &kNS_SHISTORY_INTERNAL_CID },
   { NS_DOWNLOADHISTORY_CONTRACTID, &kNS_DOWNLOADHISTORY_CID },
   { nullptr }
 };
 
 static const mozilla::Module kDocShellModule = {
--- a/docshell/shistory/public/moz.build
+++ b/docshell/shistory/public/moz.build
@@ -1,17 +1,16 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 XPIDL_SOURCES += [
     'nsIBFCacheEntry.idl',
-    'nsIHistoryEntry.idl',
     'nsISHContainer.idl',
     'nsISHEntry.idl',
     'nsISHTransaction.idl',
     'nsISHistory.idl',
     'nsISHistoryInternal.idl',
     'nsISHistoryListener.idl',
 ]
 
deleted file mode 100644
--- a/docshell/shistory/public/nsIHistoryEntry.idl
+++ /dev/null
@@ -1,58 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * An interface to individual entries in session history. Each 
- * document or frame will have a nsIHistoryEntry associated with 
- * it. nsIHistoryEntry provides access to information like URI, 
- * title and frame traversal status for that document.
- * This interface is accessible from javascript.
- */
-#include "nsISupports.idl"
-
-interface nsIURI;
-
-[scriptable, uuid(A41661D4-1417-11D5-9882-00C04FA02F40)]
-interface nsIHistoryEntry : nsISupports 
-{
-
-    /** 
-     * A readonly property that returns the URI
-     * of the current entry. The object returned is
-     * of type nsIURI
-     */
-    readonly attribute nsIURI URI;
-
-    /** 
-     * A readonly property that returns the title
-     * of the current entry.  The object returned
-     * is a encoded string
-     */
-    readonly attribute wstring title;
-
-    /** 
-     * A readonly property that returns a boolean
-     * flag which indicates if the entry was created as a 
-     * result of a subframe navigation. This flag will be
-     * 'false' when a frameset page is visited for
-     * the first time. This flag will be 'true' for all
-     * history entries created as a result of a subframe
-     * navigation.
-     */
-    readonly attribute boolean isSubFrame;
-
-};
-
-
-%{ C++
-// {A41661D5-1417-11D5-9882-00C04FA02F40}
-#define NS_HISTORYENTRY_CID \
-{0xa41661d5, 0x1417, 0x11d5, {0x98, 0x82, 0x0, 0xc0, 0x4f, 0xa0, 0x2f, 0x40}}
-
-#define NS_HISTORYENTRY_CONTRACTID \
-    "@mozilla.org/browser/history-entry;1"
-
-%}
-
--- a/docshell/shistory/public/nsISHEntry.idl
+++ b/docshell/shistory/public/nsISHEntry.idl
@@ -4,17 +4,18 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 /**
  * The interface to nsISHentry. Each document or subframe in 
  * Session History will have a nsISHEntry associated with it which will
  * hold all information required to recreate the document from history
  * 
  */
-#include "nsIHistoryEntry.idl"
+
+#include "nsISupports.idl"
 
 interface nsILayoutHistoryState;
 interface nsIContentViewer;
 interface nsIURI;
 interface nsIInputStream;
 interface nsIDocShellTreeItem;
 interface nsISupportsArray;
 interface nsIStructuredCloneContainer;
@@ -24,19 +25,44 @@ interface nsIBFCacheEntry;
 struct nsIntRect;
 class nsDocShellEditorData;
 class nsSHEntryShared;
 %}
 [ref] native nsIntRect(nsIntRect);
 [ptr] native nsDocShellEditorDataPtr(nsDocShellEditorData);
 [ptr] native nsSHEntryShared(nsSHEntryShared);
 
-[scriptable, uuid(162EA0EB-E577-4B9A-AF9D-A94E8350B029)]
-interface nsISHEntry : nsIHistoryEntry
+[scriptable, uuid(c2a5827e-0fc0-11e3-bb95-59e799890b3c)]
+interface nsISHEntry : nsISupports
 {
+    /**
+     * A readonly property that returns the URI
+     * of the current entry. The object returned is
+     * of type nsIURI
+     */
+    readonly attribute nsIURI URI;
+
+    /**
+     * A readonly property that returns the title
+     * of the current entry.  The object returned
+     * is a encoded string
+     */
+    readonly attribute wstring title;
+
+    /**
+     * A readonly property that returns a boolean
+     * flag which indicates if the entry was created as a
+     * result of a subframe navigation. This flag will be
+     * 'false' when a frameset page is visited for
+     * the first time. This flag will be 'true' for all
+     * history entries created as a result of a subframe
+     * navigation.
+     */
+    readonly attribute boolean isSubFrame;
+
     /** URI for the document */
     void setURI(in nsIURI aURI);
 
     /** Referrer URI */
     attribute nsIURI referrerURI;
 
     /** Content viewer, for fast restoration of presentation */
     attribute nsIContentViewer contentViewer;
--- a/docshell/shistory/public/nsISHistory.idl
+++ b/docshell/shistory/public/nsISHistory.idl
@@ -1,16 +1,16 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsISupports.idl"
 
-interface nsIHistoryEntry;
+interface nsISHEntry;
 interface nsISHistoryListener;
 interface nsISimpleEnumerator;
 /**
  * An interface to the primary properties of the Session History
  * component. In an embedded browser environment, the nsIWebBrowser
  * object creates an instance of session history for each open window.
  * A handle to the session history object can be obtained from
  * nsIWebNavigation. In a non-embedded situation, the  owner of the
@@ -22,17 +22,17 @@ interface nsISimpleEnumerator;
 
 %{C++
 #define NS_SHISTORY_CID \
 {0x7294fe9c, 0x14d8, 0x11d5, {0x98, 0x82, 0x00, 0xC0, 0x4f, 0xa0, 0x2f, 0x40}}
 
 #define NS_SHISTORY_CONTRACTID "@mozilla.org/browser/shistory;1"
 %}
 
-[scriptable, uuid(ef2c9bcb-96b8-4095-933a-cb1c506f2c58)]
+[scriptable, uuid(b4440e2e-0fc2-11e3-971f-59e799890b3c)]
 interface nsISHistory: nsISupports
 {
   /**
    * A readonly property of the interface that returns 
    * the number of toplevel documents currently available
    * in session history.
    */
    readonly attribute long count;
@@ -67,17 +67,17 @@ interface nsISHistory: nsISupports
    *                          index of session history should be modified 
    *                          to the parameter index.
    *
    * @return                  <code>NS_OK</code> history entry for 
    *                          the index is obtained successfully.
    *                          <code>NS_ERROR_FAILURE</code> Error in obtaining
    *                          history entry for the given index.
    */
-   nsIHistoryEntry getEntryAtIndex(in long index, in boolean modifyIndex);
+   nsISHEntry getEntryAtIndex(in long index, in boolean modifyIndex);
 
 
   /**
    * Called to purge older documents from history.
    * Documents can be removed from session history for various 
    * reasons. For example to  control memory usage of the browser, to 
    * prevent users from loading documents from history, to erase evidence of
    * prior page loads etc...
@@ -130,20 +130,20 @@ interface nsISHistory: nsISupports
    * @note  To access individual history entries of the enumerator, perform the
    *        following steps:
    *        1) Call nsISHistory->GetSHistoryEnumerator() to obtain handle 
    *           the nsISimpleEnumerator object.
    *        2) Use nsISimpleEnumerator->GetNext() on the object returned
    *           by step #1 to obtain handle to the next object in the list. 
    *           The object returned by this step is of type nsISupports.
    *        3) Perform a QueryInterface on the object returned by step #2 
-   *           to nsIHistoryEntry.
-   *        4) Use nsIHistoryEntry to access properties of each history entry. 
+   *           to nsISHEntry.
+   *        4) Use nsISHEntry to access properties of each history entry. 
    *
    * @see nsISimpleEnumerator
-   * @see nsIHistoryEntry
+   * @see nsISHEntry
    * @see QueryInterface()
    * @see do_QueryInterface()
    */
    readonly attribute nsISimpleEnumerator SHistoryEnumerator;
 
    void reloadCurrentEntry();
 };
--- a/docshell/shistory/src/nsSHEntry.cpp
+++ b/docshell/shistory/src/nsSHEntry.cpp
@@ -72,18 +72,17 @@ nsSHEntry::~nsSHEntry()
   // Null out the mParent pointers on all our kids.
   mChildren.EnumerateForwards(ClearParentPtr, nullptr);
 }
 
 //*****************************************************************************
 //    nsSHEntry: nsISupports
 //*****************************************************************************
 
-NS_IMPL_ISUPPORTS4(nsSHEntry, nsISHContainer, nsISHEntry, nsIHistoryEntry,
-                   nsISHEntryInternal)
+NS_IMPL_ISUPPORTS3(nsSHEntry, nsISHContainer, nsISHEntry, nsISHEntryInternal)
 
 //*****************************************************************************
 //    nsSHEntry: nsISHEntry
 //*****************************************************************************
 
 NS_IMETHODIMP nsSHEntry::SetScrollPosition(int32_t x, int32_t y)
 {
   mScrollPositionX = x;
--- a/docshell/shistory/src/nsSHEntry.h
+++ b/docshell/shistory/src/nsSHEntry.h
@@ -14,30 +14,28 @@
 #include "nsString.h"
 #include "mozilla/Attributes.h"
 
 // Interfaces needed
 #include "nsIInputStream.h"
 #include "nsISHEntry.h"
 #include "nsISHContainer.h"
 #include "nsIURI.h"
-#include "nsIHistoryEntry.h"
 
 class nsSHEntryShared;
 
 class nsSHEntry MOZ_FINAL : public nsISHEntry,
                             public nsISHContainer,
                             public nsISHEntryInternal
 {
 public: 
   nsSHEntry();
   nsSHEntry(const nsSHEntry &other);
 
   NS_DECL_ISUPPORTS
-  NS_DECL_NSIHISTORYENTRY
   NS_DECL_NSISHENTRY
   NS_DECL_NSISHENTRYINTERNAL
   NS_DECL_NSISHCONTAINER
 
   void DropPresentationState();
 
   static nsresult Startup();
   static void Shutdown();
--- a/docshell/shistory/src/nsSHistory.cpp
+++ b/docshell/shistory/src/nsSHistory.cpp
@@ -422,27 +422,24 @@ nsSHistory::AddEntry(nsISHEntry * aSHEnt
     currentTxn->SetPersist(aPersist);
     return NS_OK;
   }
 
   nsCOMPtr<nsISHTransaction> txn(do_CreateInstance(NS_SHTRANSACTION_CONTRACTID));
   NS_ENSURE_TRUE(txn, NS_ERROR_FAILURE);
 
   nsCOMPtr<nsIURI> uri;
-  nsCOMPtr<nsIHistoryEntry> hEntry(do_QueryInterface(aSHEntry));
-  if (hEntry) {
-    int32_t currentIndex = mIndex;
-    hEntry->GetURI(getter_AddRefs(uri));
-    NOTIFY_LISTENERS(OnHistoryNewEntry, (uri));
+  int32_t currentIndex = mIndex;
+  aSHEntry->GetURI(getter_AddRefs(uri));
+  NOTIFY_LISTENERS(OnHistoryNewEntry, (uri));
 
-    // If a listener has changed mIndex, we need to get currentTxn again,
-    // otherwise we'll be left at an inconsistent state (see bug 320742)
-    if (currentIndex != mIndex) {
-      GetTransactionAtIndex(mIndex, getter_AddRefs(currentTxn));
-    }
+  // If a listener has changed mIndex, we need to get currentTxn again,
+  // otherwise we'll be left at an inconsistent state (see bug 320742)
+  if (currentIndex != mIndex) {
+    GetTransactionAtIndex(mIndex, getter_AddRefs(currentTxn));
   }
 
   // Set the ShEntry and parent for the transaction. setting the 
   // parent will properly set the parent child relationship
   txn->SetPersist(aPersist);
   NS_ENSURE_SUCCESS(txn->Create(aSHEntry, currentTxn), NS_ERROR_FAILURE);
    
   // A little tricky math here...  Basically when adding an object regardless of
@@ -484,16 +481,17 @@ nsSHistory::GetIndex(int32_t * aResult)
 NS_IMETHODIMP
 nsSHistory::GetRequestedIndex(int32_t * aResult)
 {
   NS_PRECONDITION(aResult, "null out param?");
   *aResult = mRequestedIndex;
   return NS_OK;
 }
 
+/* Get the entry at a given index */
 NS_IMETHODIMP
 nsSHistory::GetEntryAtIndex(int32_t aIndex, bool aModifyIndex, nsISHEntry** aResult)
 {
   nsresult rv;
   nsCOMPtr<nsISHTransaction> txn;
 
   /* GetTransactionAtIndex ensures aResult is valid and validates aIndex */
   rv = GetTransactionAtIndex(aIndex, getter_AddRefs(txn));
@@ -505,30 +503,16 @@ nsSHistory::GetEntryAtIndex(int32_t aInd
       if (aModifyIndex) {
         mIndex = aIndex;
       }
     } //entry
   }  //Transaction
   return rv;
 }
 
-
-/* Get the entry at a given index */
-NS_IMETHODIMP
-nsSHistory::GetEntryAtIndex(int32_t aIndex, bool aModifyIndex, nsIHistoryEntry** aResult)
-{
-  nsresult rv;
-  nsCOMPtr<nsISHEntry> shEntry;
-  rv = GetEntryAtIndex(aIndex, aModifyIndex, getter_AddRefs(shEntry));
-  if (NS_SUCCEEDED(rv) && shEntry) 
-    rv = CallQueryInterface(shEntry, aResult);
- 
-  return rv;
-}
-
 /* Get the transaction at a given index */
 NS_IMETHODIMP
 nsSHistory::GetTransactionAtIndex(int32_t aIndex, nsISHTransaction ** aResult)
 {
   nsresult rv;
   NS_ENSURE_ARG_POINTER(aResult);
 
   if ((mLength <= 0) || (aIndex < 0) || (aIndex >= mLength))
@@ -594,21 +578,18 @@ nsSHistory::PrintHistory()
     if (NS_FAILED(rv) && !entry)
       return NS_ERROR_FAILURE;
 
     nsCOMPtr<nsILayoutHistoryState> layoutHistoryState;
     nsCOMPtr<nsIURI>  uri;
     nsXPIDLString title;
 
     entry->GetLayoutHistoryState(getter_AddRefs(layoutHistoryState));
-    nsCOMPtr<nsIHistoryEntry> hEntry(do_QueryInterface(entry));
-    if (hEntry) {
-      hEntry->GetURI(getter_AddRefs(uri));
-      hEntry->GetTitle(getter_Copies(title));              
-    }
+    entry->GetURI(getter_AddRefs(uri));
+    entry->GetTitle(getter_Copies(title));
 
 #if 0
     nsAutoCString url;
     if (uri)
      uri->GetSpec(url);
 
     printf("**** SH Transaction #%d, Entry = %x\n", index, entry.get());
     printf("\t\t URL = %s\n", url.get());
@@ -1251,17 +1232,17 @@ RemoveFromSessionHistoryContainer(nsISHC
     }
   }
   return didRemove;
 }
 
 bool RemoveChildEntries(nsISHistory* aHistory, int32_t aIndex,
                           nsTArray<uint64_t>& aEntryIDs)
 {
-  nsCOMPtr<nsIHistoryEntry> rootHE;
+  nsCOMPtr<nsISHEntry> rootHE;
   aHistory->GetEntryAtIndex(aIndex, false, getter_AddRefs(rootHE));
   nsCOMPtr<nsISHContainer> root = do_QueryInterface(rootHE);
   return root ? RemoveFromSessionHistoryContainer(root, aEntryIDs) : false;
 }
 
 bool IsSameTree(nsISHEntry* aEntry1, nsISHEntry* aEntry2)
 {
   if (!aEntry1 && !aEntry2) {
@@ -1299,21 +1280,19 @@ bool IsSameTree(nsISHEntry* aEntry1, nsI
 bool
 nsSHistory::RemoveDuplicate(int32_t aIndex, bool aKeepNext)
 {
   NS_ASSERTION(aIndex >= 0, "aIndex must be >= 0!");
   NS_ASSERTION(aIndex != 0 || aKeepNext,
                "If we're removing index 0 we must be keeping the next");
   NS_ASSERTION(aIndex != mIndex, "Shouldn't remove mIndex!");
   int32_t compareIndex = aKeepNext ? aIndex + 1 : aIndex - 1;
-  nsCOMPtr<nsIHistoryEntry> rootHE1, rootHE2;
-  GetEntryAtIndex(aIndex, false, getter_AddRefs(rootHE1));
-  GetEntryAtIndex(compareIndex, false, getter_AddRefs(rootHE2));
-  nsCOMPtr<nsISHEntry> root1 = do_QueryInterface(rootHE1);
-  nsCOMPtr<nsISHEntry> root2 = do_QueryInterface(rootHE2);
+  nsCOMPtr<nsISHEntry> root1, root2;
+  GetEntryAtIndex(aIndex, false, getter_AddRefs(root1));
+  GetEntryAtIndex(compareIndex, false, getter_AddRefs(root2));
   if (IsSameTree(root1, root2)) {
     nsCOMPtr<nsISHTransaction> txToRemove, txToKeep, txNext, txPrev;
     GetTransactionAtIndex(aIndex, getter_AddRefs(txToRemove));
     GetTransactionAtIndex(compareIndex, getter_AddRefs(txToKeep));
     NS_ENSURE_TRUE(txToRemove, false);
     NS_ENSURE_TRUE(txToKeep, false);
     txToRemove->GetNext(getter_AddRefs(txNext));
     txToRemove->GetPrev(getter_AddRefs(txPrev));
@@ -1452,17 +1431,17 @@ nsSHistory::GetDocument(nsIDOMDocument**
 
 
 NS_IMETHODIMP
 nsSHistory::GetCurrentURI(nsIURI** aResultURI)
 {
   NS_ENSURE_ARG_POINTER(aResultURI);
   nsresult rv;
 
-  nsCOMPtr<nsIHistoryEntry> currentEntry;
+  nsCOMPtr<nsISHEntry> currentEntry;
   rv = GetEntryAtIndex(mIndex, false, getter_AddRefs(currentEntry));
   if (NS_FAILED(rv) && !currentEntry) return rv;
   rv = currentEntry->GetURI(aResultURI);
   return rv;
 }
 
 
 NS_IMETHODIMP
@@ -1526,34 +1505,33 @@ nsSHistory::LoadEntry(int32_t aIndex, lo
   // Keep note of requested history index in mRequestedIndex.
   mRequestedIndex = aIndex;
 
   nsCOMPtr<nsISHEntry> prevEntry;
   GetEntryAtIndex(mIndex, false, getter_AddRefs(prevEntry));
 
   nsCOMPtr<nsISHEntry> nextEntry;
   GetEntryAtIndex(mRequestedIndex, false, getter_AddRefs(nextEntry));
-  nsCOMPtr<nsIHistoryEntry> nHEntry(do_QueryInterface(nextEntry));
-  if (!nextEntry || !prevEntry || !nHEntry) {
+  if (!nextEntry || !prevEntry) {
     mRequestedIndex = -1;
     return NS_ERROR_FAILURE;
   }
 
   // Remember that this entry is getting loaded at this point in the sequence
   nsCOMPtr<nsISHEntryInternal> entryInternal = do_QueryInterface(nextEntry);
 
   if (entryInternal) {
     entryInternal->SetLastTouched(++gTouchCounter);
   }
 
   // Send appropriate listener notifications
   bool canNavigate = true;
   // Get the uri for the entry we are about to visit
   nsCOMPtr<nsIURI> nextURI;
-  nHEntry->GetURI(getter_AddRefs(nextURI));
+  nextEntry->GetURI(getter_AddRefs(nextURI));
 
   if (aHistCmd == HIST_CMD_BACK) {
     // We are going back one entry. Send GoBack notifications
     NOTIFY_LISTENERS_CANCELABLE(OnHistoryGoBack, canNavigate,
                                 (nextURI, &canNavigate));
   } else if (aHistCmd == HIST_CMD_FORWARD) {
     // We are going forward. Send GoForward notification
     NOTIFY_LISTENERS_CANCELABLE(OnHistoryGoForward, canNavigate,
@@ -1748,18 +1726,17 @@ nsSHistory::InitiateLoad(nsISHEntry * aF
    */
   aFrameEntry->SetLoadType(aLoadType);    
   aFrameDS->CreateLoadInfo (getter_AddRefs(loadInfo));
 
   loadInfo->SetLoadType(aLoadType);
   loadInfo->SetSHEntry(aFrameEntry);
 
   nsCOMPtr<nsIURI> nextURI;
-  nsCOMPtr<nsIHistoryEntry> hEntry(do_QueryInterface(aFrameEntry));
-  hEntry->GetURI(getter_AddRefs(nextURI));
+  aFrameEntry->GetURI(getter_AddRefs(nextURI));
   // Time   to initiate a document load
   return aFrameDS->LoadURI(nextURI, loadInfo, nsIWebNavigation::LOAD_FLAGS_NONE, false);
 
 }
 
 
 
 NS_IMETHODIMP
@@ -1828,15 +1805,15 @@ nsSHEnumerator::GetNext(nsISupports **aI
 {
   NS_ENSURE_ARG_POINTER(aItem);
   int32_t cnt= 0;
 
   nsresult  result = NS_ERROR_FAILURE;
   mSHistory->GetCount(&cnt);
   if (mIndex < (cnt-1)) {
     mIndex++;
-    nsCOMPtr<nsIHistoryEntry> hEntry;
+    nsCOMPtr<nsISHEntry> hEntry;
     result = mSHistory->GetEntryAtIndex(mIndex, false, getter_AddRefs(hEntry));
     if (hEntry)
       result = CallQueryInterface(hEntry, aItem);
   }
   return result;
 }
--- a/docshell/shistory/src/nsSHistory.h
+++ b/docshell/shistory/src/nsSHistory.h
@@ -13,17 +13,17 @@
 //Interfaces Needed
 #include "nsISHistory.h"
 #include "nsISHistoryInternal.h"
 #include "nsISHTransaction.h"
 #include "nsIWebNavigation.h"
 #include "nsIWeakReference.h"
 #include "nsISimpleEnumerator.h"
 #include "nsISHistoryListener.h"
-#include "nsIHistoryEntry.h"
+#include "nsISHEntry.h"
 #include "nsTObserverArray.h"
 
 // Needed to maintain global list of all SHistory objects
 #include "prclist.h"
 
 class nsIDocShell;
 class nsSHEnumerator;
 class nsSHistoryObserver;
@@ -52,17 +52,16 @@ public:
   static uint32_t GetMaxTotalViewers() { return sHistoryMaxTotalViewers; }
 
 protected:
   virtual ~nsSHistory();
   friend class nsSHEnumerator;
   friend class nsSHistoryObserver;
 
    // Could become part of nsIWebNavigation
-   NS_IMETHOD GetEntryAtIndex(int32_t aIndex, bool aModifyIndex, nsISHEntry** aResult);
    NS_IMETHOD GetTransactionAtIndex(int32_t aIndex, nsISHTransaction ** aResult);
    nsresult CompareFrames(nsISHEntry * prevEntry, nsISHEntry * nextEntry, nsIDocShell * rootDocShell, long aLoadType, bool * aIsFrameFound);
    nsresult InitiateLoad(nsISHEntry * aFrameEntry, nsIDocShell * aFrameDS, long aLoadType);
 
    NS_IMETHOD LoadEntry(int32_t aIndex, long aLoadType, uint32_t histCmd);
 
 #ifdef DEBUG
    nsresult PrintHistory();
--- a/docshell/test/navigation/NavigationUtils.js
+++ b/docshell/test/navigation/NavigationUtils.js
@@ -179,18 +179,22 @@ function xpcWaitForFinishedFrames(callba
   function searchForFinishedFrames(win) {
     if ((escape(unescape(win.location)) == escape(target_url) ||
          escape(unescape(win.location)) == escape(target_popup_url)) && 
         win.document && 
         win.document.body && 
         (win.document.body.textContent == body ||
          win.document.body.textContent == popup_body) && 
         win.document.readyState == "complete") {
-      if (!contains(win, finishedWindows)) {
-        finishedWindows.push(win);
+
+      var util = win.QueryInterface(SpecialPowers.Ci.nsIInterfaceRequestor)
+                    .getInterface(SpecialPowers.Ci.nsIDOMWindowUtils);
+      var windowId = util.outerWindowID;
+      if (!contains(windowId, finishedWindows)) {
+        finishedWindows.push(windowId);
         frameFinished();
       }
     }
     for (var i = 0; i < win.frames.length; i++)
       searchForFinishedFrames(win.frames[i]);
   }
 
   function poll() {
--- a/dom/base/nsHistory.cpp
+++ b/dom/base/nsHistory.cpp
@@ -8,17 +8,16 @@
 #include "mozilla/dom/HistoryBinding.h"
 #include "nsCOMPtr.h"
 #include "nsPIDOMWindow.h"
 #include "nsIDocument.h"
 #include "nsIPresShell.h"
 #include "nsPresContext.h"
 #include "nsIDocShell.h"
 #include "nsIWebNavigation.h"
-#include "nsIHistoryEntry.h"
 #include "nsIURI.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsReadableUtils.h"
 #include "nsContentUtils.h"
 #include "nsISHistoryInternal.h"
 #include "mozilla/Preferences.h"
 
 using namespace mozilla;
--- a/dom/bindings/Codegen.py
+++ b/dom/bindings/Codegen.py
@@ -2330,18 +2330,18 @@ numericSuffixes = {
     IDLType.Tags.int16: '',
     IDLType.Tags.uint16: '',
     IDLType.Tags.int32: '',
     IDLType.Tags.uint32: 'U',
     IDLType.Tags.int64: 'LL',
     IDLType.Tags.uint64: 'ULL',
     IDLType.Tags.unrestricted_float: 'F',
     IDLType.Tags.float: 'F',
-    IDLType.Tags.unrestricted_double: 'D',
-    IDLType.Tags.double: 'D'
+    IDLType.Tags.unrestricted_double: '',
+    IDLType.Tags.double: ''
 }
 
 def numericValue(t, v):
     if (t == IDLType.Tags.unrestricted_double or
         t == IDLType.Tags.unrestricted_float):
         if v == float("inf"):
             return "mozilla::PositiveInfinity()"
         if v == float("-inf"):
@@ -2547,16 +2547,38 @@ class JSToNativeConversionInfo():
         assert holderType is None or isinstance(holderType, CGThing)
         self.template = template
         self.declType = declType
         self.holderType = holderType
         self.dealWithOptional = dealWithOptional
         self.declArgs = declArgs
         self.holderArgs = holderArgs
 
+def getHandleDefault(defaultValue):
+    tag = defaultValue.type.tag()
+    if tag in numericSuffixes:
+        # Some numeric literals require a suffix to compile without warnings
+        return numericValue(tag, defaultValue.value)
+    assert(tag == IDLType.Tags.bool)
+    return toStringBool(defaultValue.value)
+
+def handleDefaultStringValue(defaultValue, method):
+    """
+    Returns a string which ends up calling 'method' with a (PRUnichar*, length)
+    pair that sets this string default value.  This string is suitable for
+    passing as the second argument of handleDefault; in particular it does not
+    end with a ';'
+    """
+    assert defaultValue.type.isDOMString()
+    return ("static const PRUnichar data[] = { %s };\n"
+            "%s(data, ArrayLength(data) - 1)" %
+            (", ".join(["'" + char + "'" for char in
+                        defaultValue.value] + ["0"]),
+             method))
+
 # If this function is modified, modify CGNativeMember.getArg and
 # CGNativeMember.getRetvalInfo accordingly.  The latter cares about the decltype
 # and holdertype we end up using, because it needs to be able to return the code
 # that will convert those to the actual return value of the callback function.
 def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None,
                                 isDefinitelyObject=False,
                                 isMember=False,
                                 isOptional=False,
@@ -2884,19 +2906,16 @@ for (uint32_t i = 0; i < length; ++i) {
     if type.isUnion():
         if isMember:
             raise TypeError("Can't handle unions as members, we have a "
                             "holderType")
         nullable = type.nullable();
         if nullable:
             type = type.inner
 
-        assert(defaultValue is None or
-               (isinstance(defaultValue, IDLNullValue) and nullable))
-
         unionArgumentObj = "${holderName}"
         if nullable:
             unionArgumentObj += ".ref()"
 
         memberTypes = type.flatMemberTypes
         names = []
 
         interfaceMemberTypes = filter(lambda t: t.isNonCallbackInterface(), memberTypes)
@@ -3090,25 +3109,46 @@ for (uint32_t i = 0; i < length; ++i) {
             holderType = CGTemplatedType("Maybe", holderType)
             constructHolder = CGGeneric("${holderName}.construct(%s);" % holderArgs)
             # Don't need to pass those args when the holder is being constructed
             holderArgs = None
         else:
             holderArgs = "${declName}"
             constructHolder = None
 
+        if defaultValue and not isinstance(defaultValue, IDLNullValue):
+            tag = defaultValue.type.tag()
+
+            if tag in numericSuffixes or tag is IDLType.Tags.bool:
+                defaultStr = getHandleDefault(defaultValue)
+                value = declLoc + (".Value()" if nullable else "")
+                default = CGGeneric("%s.SetAs%s() = %s;" % (value,
+                                                            defaultValue.type,
+                                                            defaultStr))
+            else:
+                default = CGGeneric(
+                    handleDefaultStringValue(
+                        defaultValue, "%s.SetStringData" % unionArgumentObj) +
+                    ";")
+
+            templateBody = CGIfElseWrapper("!(${haveValue})", default, templateBody)
+
         templateBody = CGList([constructHolder, templateBody], "\n")
+
         if nullable:
             if defaultValue:
-                assert(isinstance(defaultValue, IDLNullValue))
-                valueMissing = "!(${haveValue}) || "
+                if isinstance(defaultValue, IDLNullValue):
+                    extraConditionForNull = "!(${haveValue}) || "
+                else:
+                    extraConditionForNull = "${haveValue} && "
             else:
-                valueMissing = ""
+                extraConditionForNull = ""
             templateBody = handleNull(templateBody, declLoc,
-                                      extraConditionForNull=valueMissing)
+                                      extraConditionForNull=extraConditionForNull)
+
         templateBody = CGList([constructDecl, templateBody], "\n")
 
         return JSToNativeConversionInfo(templateBody.define(),
                                         declType=declType,
                                         holderType=holderType,
                                         holderArgs=holderArgs,
                                         dealWithOptional=isOptional and not nullable)
 
@@ -3344,24 +3384,21 @@ for (uint32_t i = 0; i < length; ++i) {
                 "%s\n"
                 "}" % (nullBehavior, undefinedBehavior, varName,
                        exceptionCodeIndented.define()))
             if defaultValue is None:
                 return conversionCode
 
             if isinstance(defaultValue, IDLNullValue):
                 assert(type.nullable())
-                return handleDefault(conversionCode,
-                                     "%s.SetNull()" % varName)
-            return handleDefault(
-                conversionCode,
-                ("static const PRUnichar data[] = { %s };\n"
-                 "%s.SetData(data, ArrayLength(data) - 1)" %
-                 (", ".join(["'" + char + "'" for char in defaultValue.value] + ["0"]),
-                  varName)))
+                defaultCode = "%s.SetNull()" % varName
+            else:
+                defaultCode = handleDefaultStringValue(defaultValue,
+                                                       "%s.SetData" % varName)
+            return handleDefault(conversionCode, defaultCode)
 
         if isMember:
             # We have to make a copy, because our jsval may well not
             # live as long as our string needs to.
             declType = CGGeneric("nsString")
             return JSToNativeConversionInfo(
                 "{\n"
                 "  FakeDependentString str;\n"
@@ -3687,28 +3724,21 @@ for (uint32_t i = 0; i < length; ++i) {
                      "  //       when passed a non-finite float too.\n"
                      "%s\n"
                      "}" % (readLoc, nonFiniteCode))
 
     if (defaultValue is not None and
         # We already handled IDLNullValue, so just deal with the other ones
         not isinstance(defaultValue, IDLNullValue)):
         tag = defaultValue.type.tag()
-        if tag in numericSuffixes:
-            # Some numeric literals require a suffix to compile without warnings
-            defaultStr = numericValue(tag, defaultValue.value)
-        else:
-            assert(tag == IDLType.Tags.bool)
-            defaultStr = toStringBool(defaultValue.value)
-        template = CGWrapper(CGIndenter(CGGeneric(template)),
-                             pre="if (${haveValue}) {\n",
-                             post=("\n"
-                                   "} else {\n"
-                                   "  %s = %s;\n"
-                                   "}" % (writeLoc, defaultStr))).define()
+        defaultStr = getHandleDefault(defaultValue)
+        template = CGIfElseWrapper("${haveValue}",
+                                   CGGeneric(template),
+                                   CGGeneric("%s = %s;" % (writeLoc,
+                                                           defaultStr))).define()
 
     return JSToNativeConversionInfo(template, declType=declType,
                                     dealWithOptional=isOptional)
 
 def instantiateJSToNativeConversion(info, replacements, checkForValue=False):
     """
     Take a JSToNativeConversionInfo as returned by getJSToNativeConversionInfo
     and a set of replacements as required by the strings in such an object, and
@@ -6104,48 +6134,54 @@ def getUnionTypeTemplateVars(unionType, 
     structType = conversionInfo.declType.define()
     if structType.startswith("const "):
         structType = structType[6:]
     externalType = getUnionAccessorSignatureType(type, descriptorProvider).define()
 
     if type.isObject():
         body = ("mUnion.mValue.mObject.SetValue(cx, obj);\n"
                 "mUnion.mType = mUnion.eObject;")
-        setter = ClassMethod("SetToObject", "void",
-                             [Argument("JSContext*", "cx"),
-                              Argument("JSObject*", "obj")],
-                             inline=True, bodyInHeader=True,
-                             body=body)
+        setters = [ClassMethod("SetToObject", "void",
+                               [Argument("JSContext*", "cx"),
+                                Argument("JSObject*", "obj")],
+                               inline=True, bodyInHeader=True,
+                               body=body)]
 
     else:
         jsConversion = string.Template(conversionInfo.template).substitute(
             {
                 "val": "value",
                 "mutableVal": "pvalue",
                 "declName": "SetAs" + name + "(%s)" % ctorArgs,
                 "holderName": "m" + name + "Holder",
                 }
             )
         jsConversion = CGWrapper(CGGeneric(jsConversion),
                                  pre="tryNext = false;\n",
                                  post="\n"
                                       "return true;")
-        setter = ClassMethod("TrySetTo" + name, "bool",
-                             [Argument("JSContext*", "cx"),
-                              Argument("JS::Handle<JS::Value>", "value"),
-                              Argument("JS::MutableHandle<JS::Value>", "pvalue"),
-                              Argument("bool&", "tryNext")],
-                             inline=True, bodyInHeader=True,
-                             body=jsConversion.define())
+        setters = [ClassMethod("TrySetTo" + name, "bool",
+                               [Argument("JSContext*", "cx"),
+                                Argument("JS::Handle<JS::Value>", "value"),
+                                Argument("JS::MutableHandle<JS::Value>", "pvalue"),
+                                Argument("bool&", "tryNext")],
+                               inline=True, bodyInHeader=True,
+                               body=jsConversion.define())]
+        if type.isString():
+            setters.append(ClassMethod("SetStringData", "void",
+                [Argument("const nsDependentString::char_type*", "aData"),
+                 Argument("nsDependentString::size_type", "aLength")],
+                inline=True, bodyInHeader=True,
+                body="mStringHolder.SetData(aData, aLength);"))
 
     return {
                 "name": name,
                 "structType": structType,
                 "externalType": externalType,
-                "setter": setter,
+                "setters": setters,
                 "holderType": conversionInfo.holderType.define() if conversionInfo.holderType else None,
                 "ctorArgs": ctorArgs,
                 "ctorArgList": [Argument("JSContext*", "cx")] if type.isSpiderMonkeyInterface() else []
                 }
 
 def mapTemplate(template, templateVarArray):
     return map(lambda v: string.Template(template).substitute(v),
                templateVarArray)
@@ -6296,17 +6332,17 @@ class CGUnionConversionStruct(CGThing):
             methods.append(ClassMethod("SetNull", "bool", [],
                                        body=("mUnion.mType = mUnion.eNull;\n"
                                              "return true;"),
                                        inline=True, bodyInHeader=True))
 
         for t in self.type.flatMemberTypes:
             vars = getUnionTypeTemplateVars(self.type,
                                             t, self.descriptorProvider)
-            methods.append(vars["setter"])
+            methods.extend(vars["setters"])
             if vars["name"] != "Object":
                 body=string.Template("mUnion.mType = mUnion.e${name};\n"
                                      "return mUnion.mValue.m${name}.SetValue(${ctorArgs});").substitute(vars)
                 methods.append(ClassMethod("SetAs" + vars["name"],
                                            vars["structType"] + "&",
                                            vars["ctorArgList"],
                                            bodyInHeader=True,
                                            body=body,
--- a/dom/bindings/parser/WebIDL.py
+++ b/dom/bindings/parser/WebIDL.py
@@ -2381,26 +2381,38 @@ class IDLValue(IDLObject):
         assert isinstance(type, IDLType)
 
         self.value = value
 
     def coerceToType(self, type, location):
         if type == self.type:
             return self # Nothing to do
 
+        # We first check for unions to ensure that even if the union is nullable
+        # we end up with the right flat member type, not the union's type.
+        if type.isUnion():
+            for subtype in type.unroll().memberTypes:
+                try:
+                    coercedValue = self.coerceToType(subtype, location)
+                    # Create a new IDLValue to make sure that we have the
+                    # correct float/double type.  This is necessary because we
+                    # use the value's type when it is a default value of a
+                    # union, and the union cares about the exact float type.
+                    return IDLValue(self.location, subtype, coercedValue.value)
+                except:
+                    pass
         # If the type allows null, rerun this matching on the inner type, except
         # nullable enums.  We handle those specially, because we want our
         # default string values to stay strings even when assigned to a nullable
         # enum.
-        if type.nullable() and not type.isEnum():
+        elif type.nullable() and not type.isEnum():
             innerValue = self.coerceToType(type.inner, location)
             return IDLValue(self.location, type, innerValue.value)
 
-        # Else, see if we can coerce to 'type'.
-        if self.type.isInteger() and type.isInteger():
+        elif self.type.isInteger() and type.isInteger():
             # We're both integer types.  See if we fit.
 
             (min, max) = integerTypeSizes[type._typeTag]
             if self.value <= max and self.value >= min:
                 # Promote
                 return IDLValue(self.location, type, self.value)
             else:
                 raise WebIDLError("Value %s is out of range for type %s." %
@@ -2423,19 +2435,18 @@ class IDLValue(IDLObject):
             return self
         elif self.type.isFloat() and type.isFloat():
             if (not type.isUnrestricted() and
                 (self.value == float("inf") or self.value == float("-inf") or
                  math.isnan(self.value))):
                 raise WebIDLError("Trying to convert unrestricted value %s to non-unrestricted"
                                   % self.value, [location]);
             return self
-        else:
-            raise WebIDLError("Cannot coerce type %s to type %s." %
-                              (self.type, type), [location])
+        raise WebIDLError("Cannot coerce type %s to type %s." %
+                          (self.type, type), [location])
 
     def _getDependentObjects(self):
         return set()
 
 class IDLNullValue(IDLObject):
     def __init__(self, location):
         IDLObject.__init__(self, location)
         self.type = None
--- a/dom/bindings/test/TestBindingHeader.h
+++ b/dom/bindings/test/TestBindingHeader.h
@@ -508,16 +508,44 @@ public:
   //void PassUnionWithInterfaces(const TestInterfaceOrTestExternalInterface& arg);
   //void PassUnionWithInterfacesAndNullable(const TestInterfaceOrNullOrTestExternalInterface& arg);
   void PassUnionWithArrayBuffer(const ArrayBufferOrLong&);
   void PassUnionWithString(JSContext*, const StringOrObject&);
   //void PassUnionWithEnum(JSContext*, const TestEnumOrObject&);
   //void PassUnionWithCallback(JSContext*, const TestCallbackOrLong&);
   void PassUnionWithObject(JSContext*, const ObjectOrLong&);
 
+  void PassUnionWithDefaultValue1(const DoubleOrString& arg);
+  void PassUnionWithDefaultValue2(const DoubleOrString& arg);
+  void PassUnionWithDefaultValue3(const DoubleOrString& arg);
+  void PassUnionWithDefaultValue4(const FloatOrString& arg);
+  void PassUnionWithDefaultValue5(const FloatOrString& arg);
+  void PassUnionWithDefaultValue6(const FloatOrString& arg);
+  void PassUnionWithDefaultValue7(const UnrestrictedDoubleOrString& arg);
+  void PassUnionWithDefaultValue8(const UnrestrictedDoubleOrString& arg);
+  void PassUnionWithDefaultValue9(const UnrestrictedDoubleOrString& arg);
+  void PassUnionWithDefaultValue10(const UnrestrictedDoubleOrString& arg);
+  void PassUnionWithDefaultValue11(const UnrestrictedFloatOrString& arg);
+  void PassUnionWithDefaultValue12(const UnrestrictedFloatOrString& arg);
+  void PassUnionWithDefaultValue13(const UnrestrictedFloatOrString& arg);
+  void PassUnionWithDefaultValue14(const UnrestrictedFloatOrString& arg);
+
+  void PassNullableUnionWithDefaultValue1(const Nullable<DoubleOrString>& arg);
+  void PassNullableUnionWithDefaultValue2(const Nullable<DoubleOrString>& arg);
+  void PassNullableUnionWithDefaultValue3(const Nullable<DoubleOrString>& arg);
+  void PassNullableUnionWithDefaultValue4(const Nullable<FloatOrString>& arg);
+  void PassNullableUnionWithDefaultValue5(const Nullable<FloatOrString>& arg);
+  void PassNullableUnionWithDefaultValue6(const Nullable<FloatOrString>& arg);
+  void PassNullableUnionWithDefaultValue7(const Nullable<UnrestrictedDoubleOrString>& arg);
+  void PassNullableUnionWithDefaultValue8(const Nullable<UnrestrictedDoubleOrString>& arg);
+  void PassNullableUnionWithDefaultValue9(const Nullable<UnrestrictedDoubleOrString>& arg);
+  void PassNullableUnionWithDefaultValue10(const Nullable<UnrestrictedFloatOrString>& arg);
+  void PassNullableUnionWithDefaultValue11(const Nullable<UnrestrictedFloatOrString>& arg);
+  void PassNullableUnionWithDefaultValue12(const Nullable<UnrestrictedFloatOrString>& arg);
+
   void ReceiveUnion(const CanvasPatternOrCanvasGradientReturnValue&);
   void ReceiveUnionContainingNull(const CanvasPatternOrNullOrCanvasGradientReturnValue&);
   void ReceiveNullableUnion(const Nullable<CanvasPatternOrCanvasGradientReturnValue>&);
   void GetWritableUnion(const CanvasPatternOrCanvasGradientReturnValue&);
   void SetWritableUnion(const CanvasPatternOrCanvasGradient&);
   void GetWritableUnionContainingNull(const CanvasPatternOrNullOrCanvasGradientReturnValue&);
   void SetWritableUnionContainingNull(const CanvasPatternOrNullOrCanvasGradient&);
   void GetWritableNullableUnion(const Nullable<CanvasPatternOrCanvasGradientReturnValue>&);
--- a/dom/bindings/test/TestCodeGen.webidl
+++ b/dom/bindings/test/TestCodeGen.webidl
@@ -461,16 +461,43 @@ interface TestInterface {
   void passUnionWithString((DOMString or object) arg);
   //void passUnionWithEnum((TestEnum or object) arg);
   // Trying to use a callback in a union won't include the test
   // headers, unfortunately, so won't compile.
   //void passUnionWithCallback((TestCallback or long) arg);
   void passUnionWithObject((object or long) arg);
   //void passUnionWithDict((Dict or long) arg);
 
+  void passUnionWithDefaultValue1(optional (double or DOMString) arg = "");
+  void passUnionWithDefaultValue2(optional (double or DOMString) arg = 1);
+  void passUnionWithDefaultValue3(optional (double or DOMString) arg = 1.5);
+  void passUnionWithDefaultValue4(optional (float or DOMString) arg = "");
+  void passUnionWithDefaultValue5(optional (float or DOMString) arg = 1);
+  void passUnionWithDefaultValue6(optional (float or DOMString) arg = 1.5);
+  void passUnionWithDefaultValue7(optional (unrestricted double or DOMString) arg = "");
+  void passUnionWithDefaultValue8(optional (unrestricted double or DOMString) arg = 1);
+  void passUnionWithDefaultValue9(optional (unrestricted double or DOMString) arg = 1.5);
+  void passUnionWithDefaultValue10(optional (unrestricted double or DOMString) arg = Infinity);
+  void passUnionWithDefaultValue11(optional (unrestricted float or DOMString) arg = "");
+  void passUnionWithDefaultValue12(optional (unrestricted float or DOMString) arg = 1);
+  void passUnionWithDefaultValue13(optional (unrestricted float or DOMString) arg = Infinity);
+
+  void passNullableUnionWithDefaultValue1(optional (double or DOMString)? arg = "");
+  void passNullableUnionWithDefaultValue2(optional (double or DOMString)? arg = 1);
+  void passNullableUnionWithDefaultValue3(optional (double or DOMString)? arg = null);
+  void passNullableUnionWithDefaultValue4(optional (float or DOMString)? arg = "");
+  void passNullableUnionWithDefaultValue5(optional (float or DOMString)? arg = 1);
+  void passNullableUnionWithDefaultValue6(optional (float or DOMString)? arg = null);
+  void passNullableUnionWithDefaultValue7(optional (unrestricted double or DOMString)? arg = "");
+  void passNullableUnionWithDefaultValue8(optional (unrestricted double or DOMString)? arg = 1);
+  void passNullableUnionWithDefaultValue9(optional (unrestricted double or DOMString)? arg = null);
+  void passNullableUnionWithDefaultValue10(optional (unrestricted float or DOMString)? arg = "");
+  void passNullableUnionWithDefaultValue11(optional (unrestricted float or DOMString)? arg = 1);
+  void passNullableUnionWithDefaultValue12(optional (unrestricted float or DOMString)? arg = null);
+
   (CanvasPattern or CanvasGradient) receiveUnion();
   (CanvasPattern? or CanvasGradient) receiveUnionContainingNull();
   (CanvasPattern or CanvasGradient)? receiveNullableUnion();
 
   attribute (CanvasPattern or CanvasGradient) writableUnion;
   attribute (CanvasPattern? or CanvasGradient) writableUnionContainingNull;
   attribute (CanvasPattern or CanvasGradient)? writableNullableUnion;
 
--- a/dom/bindings/test/TestExampleGen.webidl
+++ b/dom/bindings/test/TestExampleGen.webidl
@@ -357,16 +357,43 @@ interface TestExampleInterface {
   void passUnionWithString((DOMString or object) arg);
   //void passUnionWithEnum((TestEnum or object) arg);
   // Trying to use a callback in a union won't include the test
   // headers, unfortunately, so won't compile.
   //  void passUnionWithCallback((TestCallback or long) arg);
   void passUnionWithObject((object or long) arg);
   //void passUnionWithDict((Dict or long) arg);
 
+  void passUnionWithDefaultValue1(optional (double or DOMString) arg = "");
+  void passUnionWithDefaultValue2(optional (double or DOMString) arg = 1);
+  void passUnionWithDefaultValue3(optional (double or DOMString) arg = 1.5);
+  void passUnionWithDefaultValue4(optional (float or DOMString) arg = "");
+  void passUnionWithDefaultValue5(optional (float or DOMString) arg = 1);
+  void passUnionWithDefaultValue6(optional (float or DOMString) arg = 1.5);
+  void passUnionWithDefaultValue7(optional (unrestricted double or DOMString) arg = "");
+  void passUnionWithDefaultValue8(optional (unrestricted double or DOMString) arg = 1);
+  void passUnionWithDefaultValue9(optional (unrestricted double or DOMString) arg = 1.5);
+  void passUnionWithDefaultValue10(optional (unrestricted double or DOMString) arg = Infinity);
+  void passUnionWithDefaultValue11(optional (unrestricted float or DOMString) arg = "");
+  void passUnionWithDefaultValue12(optional (unrestricted float or DOMString) arg = 1);
+  void passUnionWithDefaultValue13(optional (unrestricted float or DOMString) arg = Infinity);
+
+  void passNullableUnionWithDefaultValue1(optional (double or DOMString)? arg = "");
+  void passNullableUnionWithDefaultValue2(optional (double or DOMString)? arg = 1);
+  void passNullableUnionWithDefaultValue3(optional (double or DOMString)? arg = null);
+  void passNullableUnionWithDefaultValue4(optional (float or DOMString)? arg = "");
+  void passNullableUnionWithDefaultValue5(optional (float or DOMString)? arg = 1);
+  void passNullableUnionWithDefaultValue6(optional (float or DOMString)? arg = null);
+  void passNullableUnionWithDefaultValue7(optional (unrestricted double or DOMString)? arg = "");
+  void passNullableUnionWithDefaultValue8(optional (unrestricted double or DOMString)? arg = 1);
+  void passNullableUnionWithDefaultValue9(optional (unrestricted double or DOMString)? arg = null);
+  void passNullableUnionWithDefaultValue10(optional (unrestricted float or DOMString)? arg = "");
+  void passNullableUnionWithDefaultValue11(optional (unrestricted float or DOMString)? arg = 1);
+  void passNullableUnionWithDefaultValue12(optional (unrestricted float or DOMString)? arg = null);
+
   //(CanvasPattern or CanvasGradient) receiveUnion();
   //(CanvasPattern? or CanvasGradient) receiveUnionContainingNull();
   //(CanvasPattern or CanvasGradient)? receiveNullableUnion();
 
   //attribute (CanvasPattern or CanvasGradient) writableUnion;
   //attribute (CanvasPattern? or CanvasGradient) writableUnionContainingNull;
   //attribute (CanvasPattern or CanvasGradient)? writableNullableUnion;
 
--- a/dom/bindings/test/TestJSImplGen.webidl
+++ b/dom/bindings/test/TestJSImplGen.webidl
@@ -381,16 +381,43 @@ interface TestJSImplInterface {
   void passUnionWithString((DOMString or object) arg);
   //void passUnionWithEnum((MyTestEnum or object) arg);
   // Trying to use a callback in a union won't include the test
   // headers, unfortunately, so won't compile.
   //  void passUnionWithCallback((MyTestCallback or long) arg);
   void passUnionWithObject((object or long) arg);
   //void passUnionWithDict((Dict or long) arg);
 
+  void passUnionWithDefaultValue1(optional (double or DOMString) arg = "");
+  void passUnionWithDefaultValue2(optional (double or DOMString) arg = 1);
+  void passUnionWithDefaultValue3(optional (double or DOMString) arg = 1.5);
+  void passUnionWithDefaultValue4(optional (float or DOMString) arg = "");
+  void passUnionWithDefaultValue5(optional (float or DOMString) arg = 1);
+  void passUnionWithDefaultValue6(optional (float or DOMString) arg = 1.5);
+  void passUnionWithDefaultValue7(optional (unrestricted double or DOMString) arg = "");
+  void passUnionWithDefaultValue8(optional (unrestricted double or DOMString) arg = 1);
+  void passUnionWithDefaultValue9(optional (unrestricted double or DOMString) arg = 1.5);
+  void passUnionWithDefaultValue10(optional (unrestricted double or DOMString) arg = Infinity);
+  void passUnionWithDefaultValue11(optional (unrestricted float or DOMString) arg = "");
+  void passUnionWithDefaultValue12(optional (unrestricted float or DOMString) arg = 1);
+  void passUnionWithDefaultValue13(optional (unrestricted float or DOMString) arg = Infinity);
+
+  void passNullableUnionWithDefaultValue1(optional (double or DOMString)? arg = "");
+  void passNullableUnionWithDefaultValue2(optional (double or DOMString)? arg = 1);
+  void passNullableUnionWithDefaultValue3(optional (double or DOMString)? arg = null);
+  void passNullableUnionWithDefaultValue4(optional (float or DOMString)? arg = "");
+  void passNullableUnionWithDefaultValue5(optional (float or DOMString)? arg = 1);
+  void passNullableUnionWithDefaultValue6(optional (float or DOMString)? arg = null);
+  void passNullableUnionWithDefaultValue7(optional (unrestricted double or DOMString)? arg = "");
+  void passNullableUnionWithDefaultValue8(optional (unrestricted double or DOMString)? arg = 1);
+  void passNullableUnionWithDefaultValue9(optional (unrestricted double or DOMString)? arg = null);
+  void passNullableUnionWithDefaultValue10(optional (unrestricted float or DOMString)? arg = "");
+  void passNullableUnionWithDefaultValue11(optional (unrestricted float or DOMString)? arg = 1);
+  void passNullableUnionWithDefaultValue12(optional (unrestricted float or DOMString)? arg = null);
+
   //(CanvasPattern or CanvasGradient) receiveUnion();
   //(CanvasPattern? or CanvasGradient) receiveUnionContainingNull();
   //(CanvasPattern or CanvasGradient)? receiveNullableUnion();
 
   //attribute (CanvasPattern or CanvasGradient) writableUnion;
   //attribute (CanvasPattern? or CanvasGradient) writableUnionContainingNull;
   //attribute (CanvasPattern or CanvasGradient)? writableNullableUnion;
 
--- a/dom/media/Makefile.in
+++ b/dom/media/Makefile.in
@@ -10,15 +10,15 @@ relativesrcdir   = @relativesrcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 include $(topsrcdir)/dom/dom-config.mk
 
 
 ifdef MOZ_WEBRTC
 LOCAL_INCLUDES += \
-  -I$(topsrcdir)/media/webrtc/trunk/webrtc \
+  -I$(topsrcdir)/media/webrtc/trunk \
   -I$(topsrcdir)/media/webrtc/signaling/src/common \
   $(NULL)
 endif
 
 include $(topsrcdir)/config/rules.mk
 include $(topsrcdir)/ipc/chromium/chromium-config.mk
--- a/dom/plugins/base/PluginPRLibrary.cpp
+++ b/dom/plugins/base/PluginPRLibrary.cpp
@@ -255,27 +255,16 @@ PluginPRLibrary::NPP_GetSitesWithData(In
 nsresult
 PluginPRLibrary::AsyncSetWindow(NPP instance, NPWindow* window)
 {
   nsNPAPIPluginInstance* inst = (nsNPAPIPluginInstance*)instance->ndata;
   NS_ENSURE_TRUE(inst, NS_ERROR_NULL_POINTER);
   return NS_ERROR_NOT_IMPLEMENTED;
 }
 
-#if defined(MOZ_WIDGET_QT) && (MOZ_PLATFORM_MAEMO == 6)
-nsresult
-PluginPRLibrary::HandleGUIEvent(NPP instance, const nsGUIEvent& anEvent,
-                                bool* handled)
-{
-  nsNPAPIPluginInstance* inst = (nsNPAPIPluginInstance*)instance->ndata;
-  NS_ENSURE_TRUE(inst, NS_ERROR_NULL_POINTER);
-  return NS_ERROR_NOT_IMPLEMENTED;
-}
-#endif
-
 nsresult
 PluginPRLibrary::GetImageContainer(NPP instance, ImageContainer** aContainer)
 {
   return NS_ERROR_NOT_IMPLEMENTED;
 }
 
 #if defined(XP_MACOSX)
 nsresult
--- a/dom/plugins/base/PluginPRLibrary.h
+++ b/dom/plugins/base/PluginPRLibrary.h
@@ -116,21 +116,16 @@ public:
     virtual nsresult IsRemoteDrawingCoreAnimation(NPP instance, bool *aDrawing);
     virtual nsresult ContentsScaleFactorChanged(NPP instance, double aContentsScaleFactor);
 #endif
     virtual nsresult SetBackgroundUnknown(NPP instance) MOZ_OVERRIDE;
     virtual nsresult BeginUpdateBackground(NPP instance,
                                            const nsIntRect&, gfxContext** aCtx) MOZ_OVERRIDE;
     virtual nsresult EndUpdateBackground(NPP instance,
                                          gfxContext* aCtx, const nsIntRect&) MOZ_OVERRIDE;
-#if defined(MOZ_WIDGET_QT) && (MOZ_PLATFORM_MAEMO == 6)
-    virtual nsresult HandleGUIEvent(NPP instance,
-                                    const nsGUIEvent& anEvent, bool* handled);
-#endif
-
     virtual void GetLibraryPath(nsACString& aPath) { aPath.Assign(mFilePath); }
 
 private:
     NP_InitializeFunc mNP_Initialize;
     NP_ShutdownFunc mNP_Shutdown;
     NP_GetMIMEDescriptionFunc mNP_GetMIMEDescription;
 #if defined(XP_UNIX) && !defined(XP_MACOSX)
     NP_GetValueFunc mNP_GetValue;
--- a/dom/plugins/base/npapi.h
+++ b/dom/plugins/base/npapi.h
@@ -381,19 +381,16 @@ typedef enum {
   NPPVpluginDrawingModel = 1000
 #if defined(XP_MACOSX)
   /* Used for negotiating event models */
   , NPPVpluginEventModel = 1001
   /* In the NPDrawingModelCoreAnimation drawing model, the browser asks the plug-in for a Core Animation layer. */
   , NPPVpluginCoreAnimationLayer = 1003
 #endif
 
-#if defined(MOZ_PLATFORM_MAEMO) && ((MOZ_PLATFORM_MAEMO == 5) || (MOZ_PLATFORM_MAEMO == 6))
-  , NPPVpluginWindowlessLocalBool = 2002
-#endif
 } NPPVariable;
 
 /*
  * List of variable names for which NPN_GetValue should be implemented.
  */
 typedef enum {
   NPNVxDisplay = 1,
   NPNVxtAppContext,
@@ -442,19 +439,16 @@ typedef enum {
   , NPNVsupportsCarbonBool = 3000 /* TRUE if the browser supports the Carbon event model */
 #endif
   , NPNVsupportsCocoaBool = 3001 /* TRUE if the browser supports the Cocoa event model */
   , NPNVsupportsUpdatedCocoaTextInputBool = 3002 /* TRUE if the browser supports the updated
                                                     Cocoa text input specification. */
   , NPNVsupportsCompositingCoreAnimationPluginsBool = 74656 /* TRUE if the browser supports
                                                                CA model compositing */
 #endif
-#if defined(MOZ_PLATFORM_MAEMO) && ((MOZ_PLATFORM_MAEMO == 5) || (MOZ_PLATFORM_MAEMO == 6))
-  , NPNVSupportsWindowlessLocal = 2002
-#endif
 } NPNVariable;
 
 typedef enum {
   NPNURLVCookie = 501,
   NPNURLVProxy
 } NPNURLVariable;
 
 /*
--- a/dom/plugins/base/nsNPAPIPluginInstance.cpp
+++ b/dom/plugins/base/nsNPAPIPluginInstance.cpp
@@ -1198,33 +1198,16 @@ nsNPAPIPluginInstance::AsyncSetWindow(NP
 
   AutoPluginLibraryCall library(this);
   if (!library)
     return NS_ERROR_FAILURE;
 
   return library->AsyncSetWindow(&mNPP, window);
 }
 
-#if defined(MOZ_WIDGET_QT) && (MOZ_PLATFORM_MAEMO == 6)
-nsresult
-nsNPAPIPluginInstance::HandleGUIEvent(const nsGUIEvent& anEvent, bool* handled)
-{
-  if (RUNNING != mRunning) {
-    *handled = false;
-    return NS_OK;
-  }
-
-  AutoPluginLibraryCall library(this);
-  if (!library)
-    return NS_ERROR_FAILURE;
-
-  return library->HandleGUIEvent(&mNPP, anEvent, handled);
-}
-#endif
-
 nsresult
 nsNPAPIPluginInstance::GetImageContainer(ImageContainer**aContainer)
 {
   *aContainer = nullptr;
 
   if (RUNNING != mRunning)
     return NS_OK;
 
--- a/dom/plugins/base/nsNPAPIPluginInstance.h
+++ b/dom/plugins/base/nsNPAPIPluginInstance.h
@@ -113,19 +113,16 @@ public:
   nsresult GetPluginAPIVersion(uint16_t* version);
   nsresult InvalidateRect(NPRect *invalidRect);
   nsresult InvalidateRegion(NPRegion invalidRegion);
   nsresult GetMIMEType(const char* *result);
   nsresult GetJSContext(JSContext* *outContext);
   nsPluginInstanceOwner* GetOwner();
   void SetOwner(nsPluginInstanceOwner *aOwner);
   nsresult ShowStatus(const char* message);
-#if defined(MOZ_WIDGET_QT) && (MOZ_PLATFORM_MAEMO == 6)
-  nsresult HandleGUIEvent(const nsGUIEvent& anEvent, bool* handled);
-#endif
 
   nsNPAPIPlugin* GetPlugin();
 
   nsresult GetNPP(NPP * aNPP);
 
   NPError SetWindowless(bool aWindowless);
 
   NPError SetTransparent(bool aTransparent);
--- a/dom/plugins/base/nsPluginInstanceOwner.cpp
+++ b/dom/plugins/base/nsPluginInstanceOwner.cpp
@@ -1793,34 +1793,16 @@ nsresult nsPluginInstanceOwner::Dispatch
       aFocusEvent->PreventDefault();
       aFocusEvent->StopPropagation();
     }   
   }
   
   return NS_OK;
 }    
 
-#if defined(MOZ_WIDGET_QT) && (MOZ_PLATFORM_MAEMO == 6)
-nsresult nsPluginInstanceOwner::Text(nsIDOMEvent* aTextEvent)
-{
-  if (mInstance) {
-    nsEvent *event = aTextEvent->GetInternalNSEvent();
-    if (event && event->eventStructType == NS_TEXT_EVENT) {
-      nsEventStatus rv = ProcessEvent(*static_cast<nsGUIEvent*>(event));
-      if (nsEventStatus_eConsumeNoDefault == rv) {
-        aTextEvent->PreventDefault();
-        aTextEvent->StopPropagation();
-      }
-    }
-  }
-
-  return NS_OK;
-}
-#endif
-
 nsresult nsPluginInstanceOwner::ProcessKeyPress(nsIDOMEvent* aKeyEvent)
 {
 #ifdef XP_MACOSX
   return DispatchKeyToPlugin(aKeyEvent);
 #else
   if (SendNativeEvents())
     DispatchKeyToPlugin(aKeyEvent);
 
@@ -1948,21 +1930,16 @@ nsPluginInstanceOwner::HandleEvent(nsIDO
   }
   if (eventType.EqualsLiteral("keydown") ||
       eventType.EqualsLiteral("keyup")) {
     return DispatchKeyToPlugin(aEvent);
   }
   if (eventType.EqualsLiteral("keypress")) {
     return ProcessKeyPress(aEvent);
   }
-#if defined(MOZ_WIDGET_QT) && (MOZ_PLATFORM_MAEMO == 6)
-  if (eventType.EqualsLiteral("text")) {
-    return Text(aEvent);
-  }
-#endif
 
   nsCOMPtr<nsIDOMDragEvent> dragEvent(do_QueryInterface(aEvent));
   if (dragEvent && mInstance) {
     nsEvent* ievent = aEvent->GetInternalNSEvent();
     if ((ievent && ievent->mFlags.mIsTrusted) &&
          ievent->message != NS_DRAGDROP_ENTER && ievent->message != NS_DRAGDROP_OVER) {
       aEvent->PreventDefault();
     }
@@ -2391,39 +2368,20 @@ nsEventStatus nsPluginInstanceOwner::Pro
           event.same_screen = False;
         }
       else
         {
           // If we need to send synthesized key events, then
           // DOMKeyCodeToGdkKeyCode(keyEvent.keyCode) and
           // gdk_keymap_get_entries_for_keyval will be useful, but the
           // mappings will not be unique.
-#if defined(MOZ_WIDGET_QT) && (MOZ_PLATFORM_MAEMO == 6)
-          bool handled;
-          if (NS_SUCCEEDED(mInstance->HandleGUIEvent(anEvent, &handled)) &&
-              handled) {
-            rv = nsEventStatus_eConsumeNoDefault;
-          }
-#else
           NS_WARNING("Synthesized key event not sent to plugin");
-#endif
         }
       break;
 
-#if defined(MOZ_WIDGET_QT) && (MOZ_PLATFORM_MAEMO == 6)
-   case NS_TEXT_EVENT:
-        {
-          bool handled;
-          if (NS_SUCCEEDED(mInstance->HandleGUIEvent(anEvent, &handled)) &&
-              handled) {
-            rv = nsEventStatus_eConsumeNoDefault;
-          }
-        }
-      break;
-#endif
     default: 
       switch (anEvent.message)
         {
         case NS_FOCUS_CONTENT:
         case NS_BLUR_CONTENT:
           {
             XFocusChangeEvent &event = pluginEvent.xfocus;
             event.type =
@@ -2577,19 +2535,16 @@ nsPluginInstanceOwner::Destroy()
   mContent->RemoveEventListener(NS_LITERAL_STRING("drag"), this, true);
   mContent->RemoveEventListener(NS_LITERAL_STRING("dragenter"), this, true);
   mContent->RemoveEventListener(NS_LITERAL_STRING("dragover"), this, true);
   mContent->RemoveEventListener(NS_LITERAL_STRING("dragleave"), this, true);
   mContent->RemoveEventListener(NS_LITERAL_STRING("dragexit"), this, true);
   mContent->RemoveEventListener(NS_LITERAL_STRING("dragstart"), this, true);
   mContent->RemoveEventListener(NS_LITERAL_STRING("draggesture"), this, true);
   mContent->RemoveEventListener(NS_LITERAL_STRING("dragend"), this, true);
-#if defined(MOZ_WIDGET_QT) && (MOZ_PLATFORM_MAEMO == 6)
-  mContent->RemoveEventListener(NS_LITERAL_STRING("text"), this, true);
-#endif
 
 #if MOZ_WIDGET_ANDROID
   RemovePluginView();
 #endif
 
   if (mWidget) {
     if (mPluginWindow) {
       mPluginWindow->SetPluginWidget(nullptr);
@@ -3006,19 +2961,16 @@ nsresult nsPluginInstanceOwner::Init(nsI
   mContent->AddEventListener(NS_LITERAL_STRING("drag"), this, true);
   mContent->AddEventListener(NS_LITERAL_STRING("dragenter"), this, true);
   mContent->AddEventListener(NS_LITERAL_STRING("dragover"), this, true);
   mContent->AddEventListener(NS_LITERAL_STRING("dragleave"), this, true);
   mContent->AddEventListener(NS_LITERAL_STRING("dragexit"), this, true);
   mContent->AddEventListener(NS_LITERAL_STRING("dragstart"), this, true);
   mContent->AddEventListener(NS_LITERAL_STRING("draggesture"), this, true);
   mContent->AddEventListener(NS_LITERAL_STRING("dragend"), this, true);
-#if defined(MOZ_WIDGET_QT) && (MOZ_PLATFORM_MAEMO == 6)
-  mContent->AddEventListener(NS_LITERAL_STRING("text"), this, true);
-#endif
 
   return NS_OK; 
 }
 
 void* nsPluginInstanceOwner::GetPluginPortFromWidget()
 {
 //!!! Port must be released for windowless plugins on Windows, because it is HDC !!!
 
--- a/dom/plugins/base/nsPluginInstanceOwner.h
+++ b/dom/plugins/base/nsPluginInstanceOwner.h
@@ -78,20 +78,16 @@ public:
   //nsIPluginTagInfo interface
   NS_DECL_NSIPLUGINTAGINFO
   
   // nsIDOMEventListener interfaces 
   NS_DECL_NSIDOMEVENTLISTENER
   
   nsresult ProcessMouseDown(nsIDOMEvent* aKeyEvent);
   nsresult ProcessKeyPress(nsIDOMEvent* aKeyEvent);
-#if defined(MOZ_WIDGET_QT) && (MOZ_PLATFORM_MAEMO == 6)
-  nsresult Text(nsIDOMEvent* aTextEvent);
-#endif
-
   nsresult Destroy();  
 
 #ifdef XP_WIN
   void Paint(const RECT& aDirty, HDC aDC);
 #elif defined(XP_MACOSX)
   void Paint(const gfxRect& aDirtyRect, CGContextRef cgContext);  
   void RenderCoreAnimation(CGContextRef aCGContext, int aWidth, int aHeight);
   void DoCocoaEventDrawRect(const gfxRect& aDrawRect, CGContextRef cgContext);
--- a/dom/plugins/ipc/PPluginInstance.ipdl
+++ b/dom/plugins/ipc/PPluginInstance.ipdl
@@ -134,21 +134,16 @@ child:
 
   // There is now an opaque background behind this instance (or the
   // background was updated).  The changed area is |rect|.  The
   // browser owns the background surface, and it's read-only from
   // within the plugin process.  |background| is either null_t to
   // refer to the existing background or a fresh descriptor.
   async UpdateBackground(SurfaceDescriptor background, nsIntRect rect);
 
-  rpc HandleTextEvent(nsTextEvent event)
-    returns (bool handled);
-  rpc HandleKeyEvent(nsKeyEvent event)
-    returns (bool handled);
-
   async NPP_DidComposite();
 
   rpc NPP_Destroy()
     returns (NPError rv);
 
 parent:
   rpc NPN_GetValue_NPNVWindowNPObject()
     returns (nullable PPluginScriptableObject value, NPError result);
--- a/dom/plugins/ipc/PluginInstanceChild.cpp
+++ b/dom/plugins/ipc/PluginInstanceChild.cpp
@@ -1,23 +1,14 @@
 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  * vim: sw=4 ts=4 et :
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-#if defined(MOZ_WIDGET_QT) && (MOZ_PLATFORM_MAEMO == 6)
-#include <QEvent>
-#include <QKeyEvent>
-#include <QApplication>
-#include <QInputMethodEvent>
-#include "nsQtKeyUtils.h"
-#include "NestedLoopTimer.h"
-#endif
-
 #include "PluginBackgroundDestroyer.h"
 #include "PluginInstanceChild.h"
 #include "PluginModuleChild.h"
 #include "BrowserStreamChild.h"
 #include "PluginStreamChild.h"
 #include "StreamNotifyChild.h"
 #include "PluginProcessChild.h"
 #include "gfxASurface.h"
@@ -146,19 +137,16 @@ PluginInstanceChild::PluginInstanceChild
     , mIsTransparent(false)
     , mSurfaceType(gfxASurface::SurfaceTypeMax)
     , mCurrentInvalidateTask(nullptr)
     , mCurrentAsyncSetWindowTask(nullptr)
     , mPendingPluginCall(false)
     , mDoAlphaExtraction(false)
     , mHasPainted(false)
     , mSurfaceDifferenceRect(0,0,0,0)
-#if (MOZ_PLATFORM_MAEMO == 5) || (MOZ_PLATFORM_MAEMO == 6)
-    , mMaemoImageRendering(true)
-#endif
 {
     memset(&mWindow, 0, sizeof(mWindow));
     mWindow.type = NPWindowTypeWindow;
     mData.ndata = (void*) this;
     mData.pdata = nullptr;
     mAsyncBitmaps.Init();
 #if defined(MOZ_X11) && defined(XP_UNIX) && !defined(XP_MACOSX)
     mWindow.ws_info = &mWsInfo;
@@ -288,28 +276,16 @@ NPError
 PluginInstanceChild::NPN_GetValue(NPNVariable aVar,
                                   void* aValue)
 {
     PLUGIN_LOG_DEBUG(("%s (aVar=%i)", FULLFUNCTION, (int) aVar));
     AssertPluginThread();
 
     switch(aVar) {
 
-#if (MOZ_PLATFORM_MAEMO == 5) || (MOZ_PLATFORM_MAEMO == 6)
-    case NPNVSupportsWindowlessLocal: {
-#ifdef MOZ_WIDGET_QT
-        const char *graphicsSystem = PR_GetEnv("MOZ_QT_GRAPHICSSYSTEM");
-        // we should set local rendering to false in order to render X-Plugin
-        // there is no possibility to change it later on maemo5 platform
-        mMaemoImageRendering = (!(graphicsSystem && !strcmp(graphicsSystem, "native")));
-#endif
-        *((NPBool*)aValue) = mMaemoImageRendering;
-        return NPERR_NO_ERROR;
-    }
-#endif
 #if defined(MOZ_X11)
     case NPNVToolkit:
         *((NPNToolkitType*)aValue) = NPNVGtk2;
         return NPERR_NO_ERROR;
 
     case NPNVxDisplay:
         if (!mWsInfo.display) {
             // We are called before Initialize() so we have to call it now.
@@ -2724,67 +2700,16 @@ PluginInstanceChild::RecvAsyncSetWindow(
                           gfxSurfaceType, NPRemoteWindow, bool>
         (this, &PluginInstanceChild::DoAsyncSetWindow,
          aSurfaceType, aWindow, true);
     MessageLoop::current()->PostTask(FROM_HERE, mCurrentAsyncSetWindowTask);
 
     return true;
 }
 
-bool
-PluginInstanceChild::AnswerHandleKeyEvent(const nsKeyEvent& aKeyEvent,
-                                          bool* handled)
-{
-    AssertPluginThread();
-#if defined(MOZ_WIDGET_QT) && (MOZ_PLATFORM_MAEMO == 6)
-    Qt::KeyboardModifiers modifier;
-    if (aKeyEvent.IsShift())
-        modifier |= Qt::ShiftModifier;
-    if (aKeyEvent.IsControl())
-        modifier |= Qt::ControlModifier;
-    if (aKeyEvent.IsAlt())
-        modifier |= Qt::AltModifier;
-    if (aKeyEvent.IsMeta())
-        modifier |= Qt::MetaModifier;
-
-    QEvent::Type type;
-    if (aKeyEvent.message == NS_KEY_DOWN) {
-        type = QEvent::KeyPress;
-    } else if (aKeyEvent.message == NS_KEY_UP) {
-        type = QEvent::KeyRelease;
-    } else {
-        *handled = false;
-        return true;
-    }
-    QKeyEvent keyEv(type, DOMKeyCodeToQtKeyCode(aKeyEvent.keyCode), modifier);
-    *handled = QApplication::sendEvent(qApp, &keyEv);
-#else
-    NS_ERROR("Not implemented");
-#endif
-
-    return true;
-}
-
-bool
-PluginInstanceChild::AnswerHandleTextEvent(const nsTextEvent& aEvent,
-                                           bool* handled)
-{
-    AssertPluginThread();
-#if defined(MOZ_WIDGET_QT) && (MOZ_PLATFORM_MAEMO == 6)
-    QInputMethodEvent event;
-    event.setCommitString(QString((const QChar*)aEvent.theText.get(),
-                          aEvent.theText.Length()));
-    *handled = QApplication::sendEvent(qApp, &event);
-#else
-    NS_ERROR("Not implemented");
-#endif
-
-    return true;
-}
-
 void
 PluginInstanceChild::DoAsyncSetWindow(const gfxSurfaceType& aSurfaceType,
                                       const NPRemoteWindow& aWindow,
                                       bool aIsAsync)
 {
     PLUGIN_LOG_DEBUG(
         ("[InstanceChild][%p] AsyncSetWindow to <x=%d,y=%d, w=%d,h=%d>",
          this, aWindow.x, aWindow.y, aWindow.width, aWindow.height));
@@ -2853,27 +2778,16 @@ PluginInstanceChild::CreateOptSurface(vo
     nsRefPtr<gfxASurface> retsurf;
     // Use an opaque surface unless we're transparent and *don't* have
     // a background to source from.
     gfxASurface::gfxImageFormat format =
         (mIsTransparent && !mBackground) ? gfxASurface::ImageFormatARGB32 :
                                            gfxASurface::ImageFormatRGB24;
 
 #ifdef MOZ_X11
-#if (MOZ_PLATFORM_MAEMO == 5) || (MOZ_PLATFORM_MAEMO == 6)
-    // On Maemo 5, we must send the Visibility event to activate the plugin
-    if (mMaemoImageRendering) {
-        NPEvent pluginEvent;
-        XVisibilityEvent& visibilityEvent = pluginEvent.xvisibility;
-        visibilityEvent.type = VisibilityNotify;
-        visibilityEvent.display = 0;
-        visibilityEvent.state = VisibilityUnobscured;
-        mPluginIface->event(&mData, reinterpret_cast<void*>(&pluginEvent));
-    }
-#endif
     Display* dpy = mWsInfo.display;
     Screen* screen = DefaultScreenOfDisplay(dpy);
     if (format == gfxASurface::ImageFormatRGB24 &&
         DefaultDepth(dpy, DefaultScreen(dpy)) == 16) {
         format = gfxASurface::ImageFormatRGB16_565;
     }
 
     if (mSurfaceType == gfxASurface::SurfaceTypeXlib) {
@@ -2927,22 +2841,17 @@ bool
 PluginInstanceChild::MaybeCreatePlatformHelperSurface(void)
 {
     if (!mCurrentSurface) {
         NS_ERROR("Cannot create helper surface without mCurrentSurface");
         return false;
     }
 
 #ifdef MOZ_X11
-#ifdef MOZ_PLATFORM_MAEMO
-    // On maemo plugins support non-default visual rendering
-    bool supportNonDefaultVisual = true;
-#else
     bool supportNonDefaultVisual = false;
-#endif
     Screen* screen = DefaultScreenOfDisplay(mWsInfo.display);
     Visual* defaultVisual = DefaultVisualOfScreen(screen);
     Visual* visual = nullptr;
     Colormap colormap = 0;
     mDoAlphaExtraction = false;
     bool createHelperSurface = false;
 
     if (mCurrentSurface->GetType() == gfxASurface::SurfaceTypeXlib) {
@@ -2951,24 +2860,16 @@ PluginInstanceChild::MaybeCreatePlatform
         // Create helper surface if layer surface visual not same as default
         // and we don't support non-default visual rendering
         if (!visual || (defaultVisual != visual && !supportNonDefaultVisual)) {
             createHelperSurface = true;
             visual = defaultVisual;
             mDoAlphaExtraction = mIsTransparent;
         }
     } else if (mCurrentSurface->GetType() == gfxASurface::SurfaceTypeImage) {
-#if (MOZ_PLATFORM_MAEMO == 5) || (MOZ_PLATFORM_MAEMO == 6)
-        if (mMaemoImageRendering) {
-            // No helper surface needed, when mMaemoImageRendering is TRUE.
-            // we can rendering directly into image memory
-            // with NPImageExpose Maemo5 NPAPI
-            return true;
-        }
-#endif
         // For image layer surface we should always create helper surface
         createHelperSurface = true;
         // Check if we can create helper surface with non-default visual
         visual = gfxXlibSurface::FindVisual(screen,
             static_cast<gfxImageSurface*>(mCurrentSurface.get())->Format());
         if (!visual || (defaultVisual != visual && !supportNonDefaultVisual)) {
             visual = defaultVisual;
             mDoAlphaExtraction = mIsTransparent;
@@ -3115,32 +3016,16 @@ PluginInstanceChild::UpdateWindowAttribu
         static_cast<gfxXlibSurface*>(curSurface.get())->
             GetColormapAndVisual(&colormap, &visual);
         if (visual != mWsInfo.visual || colormap != mWsInfo.colormap) {
             mWsInfo.visual = visual;
             mWsInfo.colormap = colormap;
             needWindowUpdate = true;
         }
     }
-#if (MOZ_PLATFORM_MAEMO == 5) || (MOZ_PLATFORM_MAEMO == 6)
-    else if (curSurface && curSurface->GetType() == gfxASurface::SurfaceTypeImage
-             && mMaemoImageRendering) {
-        // For maemo5 we need to setup window/colormap to 0
-        // and specify depth of image surface
-        gfxImageSurface* img = static_cast<gfxImageSurface*>(curSurface.get());
-        if (mWindow.window ||
-            mWsInfo.depth != gfxUtils::ImageFormatToDepth(img->Format()) ||
-            mWsInfo.colormap) {
-            mWindow.window = nullptr;
-            mWsInfo.depth = gfxUtils::ImageFormatToDepth(img->Format());
-            mWsInfo.colormap = 0;
-            needWindowUpdate = true;
-        }
-    }
-#endif // MAEMO
 #endif // MOZ_X11
 #ifdef XP_WIN
     HDC dc = NULL;
 
     if (curSurface) {
         if (!SharedDIBSurface::IsSharedDIBSurface(curSurface))
             NS_RUNTIMEABORT("Expected SharedDIBSurface!");
 
@@ -3213,56 +3098,16 @@ PluginInstanceChild::UpdateWindowAttribu
 
 void
 PluginInstanceChild::PaintRectToPlatformSurface(const nsIntRect& aRect,
                                                 gfxASurface* aSurface)
 {
     UpdateWindowAttributes();
 
 #ifdef MOZ_X11
-#if (MOZ_PLATFORM_MAEMO == 5) || (MOZ_PLATFORM_MAEMO == 6)
-    // On maemo5 we do support Image rendering NPAPI
-    if (mMaemoImageRendering &&
-        aSurface->GetType() == gfxASurface::SurfaceTypeImage) {
-        aSurface->Flush();
-        gfxImageSurface* image = static_cast<gfxImageSurface*>(aSurface);
-        NPImageExpose imgExp;
-        imgExp.depth = gfxUtils::ImageFormatToDepth(image->Format());
-        imgExp.x = aRect.x;
-        imgExp.y = aRect.y;
-        imgExp.width = aRect.width;
-        imgExp.height = aRect.height;
-        imgExp.stride = image->Stride();
-        imgExp.data = (char *)image->Data();
-        imgExp.dataSize.width = image->Width();
-        imgExp.dataSize.height = image->Height();
-        imgExp.translateX = 0;
-        imgExp.translateY = 0;
-        imgExp.scaleX = 1;
-        imgExp.scaleY = 1;
-        NPEvent pluginEvent;
-        XGraphicsExposeEvent& exposeEvent = pluginEvent.xgraphicsexpose;
-        exposeEvent.type = GraphicsExpose;
-        exposeEvent.display = 0;
-        // Store imageExpose structure pointer as drawable member
-        exposeEvent.drawable = (Drawable)&imgExp;
-        exposeEvent.x = imgExp.x;
-        exposeEvent.y = imgExp.y;
-        exposeEvent.width = imgExp.width;
-        exposeEvent.height = imgExp.height;
-        exposeEvent.count = 0;
-        // information not set:
-        exposeEvent.serial = 0;
-        exposeEvent.send_event = False;
-        exposeEvent.major_code = 0;
-        exposeEvent.minor_code = 0;
-        mPluginIface->event(&mData, reinterpret_cast<void*>(&exposeEvent));
-        aSurface->MarkDirty(gfxRect(aRect.x, aRect.y, aRect.width, aRect.height));
-    } else
-#endif
     {
         NS_ASSERTION(aSurface->GetType() == gfxASurface::SurfaceTypeXlib,
                      "Non supported platform surface type");
 
         NPEvent pluginEvent;
         XGraphicsExposeEvent& exposeEvent = pluginEvent.xgraphicsexpose;
         exposeEvent.type = GraphicsExpose;
         exposeEvent.display = mWsInfo.display;
@@ -3319,21 +3164,16 @@ PluginInstanceChild::PaintRectToSurface(
         // Work around a bug in Flash up to 10.1 d51 at least, where expose event
         // top left coordinates within the plugin-rect and not at the drawable
         // origin are misinterpreted.  (We can move the top left coordinate
         // provided it is within the clipRect.), see bug 574583
         plPaintRect.SetRect(0, 0, aRect.XMost(), aRect.YMost());
     }
     if (mHelperSurface) {
         // On X11 we can paint to non Xlib surface only with HelperSurface
-#if (MOZ_PLATFORM_MAEMO == 5) || (MOZ_PLATFORM_MAEMO == 6)
-        // Don't use mHelperSurface if surface is image and mMaemoImageRendering is TRUE
-        if (!mMaemoImageRendering ||
-            renderSurface->GetType() != gfxASurface::SurfaceTypeImage)
-#endif
         renderSurface = mHelperSurface;
     }
 #endif
 
     if (mIsTransparent && !CanPaintOnBackground()) {
        // Clear surface content for transparent rendering
        nsRefPtr<gfxContext> ctx = new gfxContext(renderSurface);
        ctx->SetDeviceColor(aColor);
--- a/dom/plugins/ipc/PluginInstanceChild.h
+++ b/dom/plugins/ipc/PluginInstanceChild.h
@@ -95,21 +95,16 @@ protected:
     RecvAsyncSetWindow(const gfxSurfaceType& aSurfaceType,
                        const NPRemoteWindow& aWindow);
 
     virtual void
     DoAsyncSetWindow(const gfxSurfaceType& aSurfaceType,
                      const NPRemoteWindow& aWindow,
                      bool aIsAsync);
 
-    virtual bool
-    AnswerHandleKeyEvent(const nsKeyEvent& aEvent, bool* handled);
-    virtual bool
-    AnswerHandleTextEvent(const nsTextEvent& aEvent, bool* handled);
-
     virtual PPluginSurfaceChild* AllocPPluginSurfaceChild(const WindowsSharedMemoryHandle&,
                                                           const gfxIntSize&, const bool&) {
         return new PPluginSurfaceChild();
     }
 
     virtual bool DeallocPPluginSurfaceChild(PPluginSurfaceChild* s) {
         delete s;
         return true;
@@ -593,34 +588,29 @@ private:
     bool mPendingPluginCall;
 
     // On some platforms, plugins may not support rendering to a surface with
     // alpha, or not support rendering to an image surface.
     // In those cases we need to draw to a temporary platform surface; we cache
     // that surface here.
     nsRefPtr<gfxASurface> mHelperSurface;
 
-    // true when plugin does not support painting to ARGB32 surface
-    // this is false for maemo platform, and false if plugin
-    // supports NPPVpluginTransparentAlphaBool (which is not part of NPAPI yet)
+    // true when plugin does not support painting to ARGB32
+    // surface this is false if plugin supports
+    // NPPVpluginTransparentAlphaBool (which is not part of
+    // NPAPI yet)
     bool mDoAlphaExtraction;
 
     // true when the plugin has painted at least once. We use this to ensure
     // that we ask a plugin to paint at least once even if it's invisible;
     // some plugin (instances) rely on this in order to work properly.
     bool mHasPainted;
 
     // Cached rectangle rendered to previous surface(mBackSurface)
     // Used for reading back to current surface and syncing data,
     // in plugin coordinates.
     nsIntRect mSurfaceDifferenceRect;
-
-#if (MOZ_PLATFORM_MAEMO == 5) || (MOZ_PLATFORM_MAEMO == 6)
-    // Maemo5 Flash does not remember WindowlessLocal state
-    // we should listen for NPP values negotiation and remember it
-    bool                  mMaemoImageRendering;
-#endif
 };
 
 } // namespace plugins
 } // namespace mozilla
 
 #endif // ifndef dom_plugins_PluginInstanceChild_h
--- a/dom/plugins/ipc/PluginInstanceParent.cpp
+++ b/dom/plugins/ipc/PluginInstanceParent.cpp
@@ -681,41 +681,16 @@ PluginInstanceParent::AsyncSetWindow(NPW
 #endif
     if (!SendAsyncSetWindow(gfxPlatform::GetPlatform()->ScreenReferenceSurface()->GetType(),
                             window))
         return NS_ERROR_FAILURE;
 
     return NS_OK;
 }
 
-#if defined(MOZ_WIDGET_QT) && (MOZ_PLATFORM_MAEMO == 6)
-nsresult
-PluginInstanceParent::HandleGUIEvent(const nsGUIEvent& anEvent, bool* handled)
-{
-    switch (anEvent.eventStructType) {
-    case NS_KEY_EVENT:
-        if (!CallHandleKeyEvent(static_cast<const nsKeyEvent&>(anEvent),
-                                handled)) {
-            return NS_ERROR_FAILURE;
-        }
-        break;
-    case NS_TEXT_EVENT:
-        if (!CallHandleTextEvent(static_cast<const nsTextEvent&>(anEvent),
-                                 handled)) {
-            return NS_ERROR_FAILURE;
-        }
-        break;
-    default:
-        NS_ERROR("Not implemented for this event type");
-        return NS_ERROR_FAILURE;
-    }
-    return NS_OK;
-}
-#endif
-
 nsresult
 PluginInstanceParent::GetImageContainer(ImageContainer** aContainer)
 {
 #ifdef XP_MACOSX
     MacIOSurface* ioSurface = NULL;
   
     if (mFrontIOSurface) {
       ioSurface = mFrontIOSurface;
--- a/dom/plugins/ipc/PluginInstanceParent.h
+++ b/dom/plugins/ipc/PluginInstanceParent.h
@@ -273,20 +273,16 @@ public:
     nsresult IsRemoteDrawingCoreAnimation(bool *aDrawing);
     nsresult ContentsScaleFactorChanged(double aContentsScaleFactor);
 #endif
     nsresult SetBackgroundUnknown();
     nsresult BeginUpdateBackground(const nsIntRect& aRect,
                                    gfxContext** aCtx);
     nsresult EndUpdateBackground(gfxContext* aCtx,
                                  const nsIntRect& aRect);
-#if defined(MOZ_WIDGET_QT) && (MOZ_PLATFORM_MAEMO == 6)
-    nsresult HandleGUIEvent(const nsGUIEvent& anEvent, bool* handled);
-#endif
-
     void DidComposite() { unused << SendNPP_DidComposite(); }
 
 private:
     // Create an appropriate platform surface for a background of size
     // |aSize|.  Return true if successful.
     bool CreateBackground(const nsIntSize& aSize);
     void DestroyBackground();
     SurfaceDescriptor BackgroundDescriptor() /*const*/;
--- a/dom/plugins/ipc/PluginLibrary.h
+++ b/dom/plugins/ipc/PluginLibrary.h
@@ -80,17 +80,14 @@ public:
    * PluginInstanceParent.  They approximately follow the ReadbackSink
    * API.
    */
   virtual nsresult SetBackgroundUnknown(NPP instance) = 0;
   virtual nsresult BeginUpdateBackground(NPP instance,
                                          const nsIntRect&, gfxContext**) = 0;
   virtual nsresult EndUpdateBackground(NPP instance,
                                        gfxContext*, const nsIntRect&) = 0;
-#if defined(MOZ_WIDGET_QT) && (MOZ_PLATFORM_MAEMO == 6)
-  virtual nsresult HandleGUIEvent(NPP instance, const nsGUIEvent&, bool*) = 0;
-#endif
 };
 
 
 } // namespace mozilla
 
 #endif  // ifndef mozilla_PluginLibrary_h
--- a/dom/plugins/ipc/PluginModuleChild.cpp
+++ b/dom/plugins/ipc/PluginModuleChild.cpp
@@ -164,24 +164,22 @@ PluginModuleChild::Init(const std::strin
                     getter_AddRefs(localFile));
 
     bool exists;
     localFile->Exists(&exists);
     NS_ASSERTION(exists, "plugin file ain't there");
 
     nsPluginFile pluginFile(localFile);
 
-    // Maemo flash can render with any provided rectangle and so does not
-    // require this quirk.
-#if (defined(MOZ_X11) && !defined(MOZ_PLATFORM_MAEMO)) || defined(OS_MACOSX)
+#if defined(MOZ_X11) || defined(OS_MACOSX)
     nsPluginInfo info = nsPluginInfo();
     if (NS_FAILED(pluginFile.GetPluginInfo(info, &mLibrary)))
         return false;
 
-#if defined(MOZ_X11) && !defined(MOZ_PLATFORM_MAEMO)
+#if defined(MOZ_X11)
     NS_NAMED_LITERAL_CSTRING(flash10Head, "Shockwave Flash 10.");
     if (StringBeginsWith(nsDependentCString(info.fDescription), flash10Head)) {
         AddQuirk(QUIRK_FLASH_EXPOSE_COORD_TRANSLATION);
     }
 #else // defined(OS_MACOSX)
     mozilla::plugins::PluginUtilsOSX::SetProcessName(info.fName);
 #endif
 
--- a/dom/plugins/ipc/PluginModuleParent.cpp
+++ b/dom/plugins/ipc/PluginModuleParent.cpp
@@ -1110,30 +1110,16 @@ PluginModuleParent::AsyncSetWindow(NPP i
 {
     PluginInstanceParent* i = InstCast(instance);
     if (!i)
         return NS_ERROR_FAILURE;
 
     return i->AsyncSetWindow(window);
 }
 
-#if defined(MOZ_WIDGET_QT) && (MOZ_PLATFORM_MAEMO == 6)
-nsresult
-PluginModuleParent::HandleGUIEvent(NPP instance,
-                                   const nsGUIEvent& anEvent,
-                                   bool* handled)
-{
-    PluginInstanceParent* i = InstCast(instance);
-    if (!i)
-        return NS_ERROR_FAILURE;
-
-    return i->HandleGUIEvent(anEvent, handled);
-}
-#endif
-
 nsresult
 PluginModuleParent::GetImageContainer(NPP instance,
                              mozilla::layers::ImageContainer** aContainer)
 {
     PluginInstanceParent* i = InstCast(instance);
     return !i ? NS_ERROR_FAILURE : i->GetImageContainer(aContainer);
 }
 
--- a/dom/plugins/ipc/PluginModuleParent.h
+++ b/dom/plugins/ipc/PluginModuleParent.h
@@ -269,20 +269,16 @@ private:
     virtual nsresult NPP_ClearSiteData(const char* site, uint64_t flags,
                                        uint64_t maxAge);
     virtual nsresult NPP_GetSitesWithData(InfallibleTArray<nsCString>& result);
 
 #if defined(XP_MACOSX)
     virtual nsresult IsRemoteDrawingCoreAnimation(NPP instance, bool *aDrawing);
     virtual nsresult ContentsScaleFactorChanged(NPP instance, double aContentsScaleFactor);
 #endif
-#if defined(MOZ_WIDGET_QT) && (MOZ_PLATFORM_MAEMO == 6)
-    virtual nsresult HandleGUIEvent(NPP instance, const nsGUIEvent& anEvent,
-                                    bool* handled);
-#endif
 
 private:
     CrashReporterParent* CrashReporter();
 
 #ifdef MOZ_CRASHREPORTER
     void ProcessFirstMinidump();
     void WriteExtraDataForMinidump(CrashReporter::AnnotationTable& notes);
 #endif
--- a/dom/src/geolocation/Makefile.in
+++ b/dom/src/geolocation/Makefile.in
@@ -11,21 +11,16 @@ include $(DEPTH)/config/autoconf.mk
 
 LOCAL_INCLUDES = \
 		-I$(topsrcdir)/dom/base \
 		-I$(topsrcdir)/dom/ipc \
 		-I$(topsrcdir)/content/base/src \
 		-I$(topsrcdir)/content/events/src \
 		$(NULL)
 
-ifdef MOZ_MAEMO_LIBLOCATION
-LOCAL_INCLUDES  += $(MOZ_PLATFORM_MAEMO_CFLAGS) \
-                   -I$(topsrcdir)/dom/system/unix \
-                   $(NULL)
-endif
 ifdef MOZ_ENABLE_QTMOBILITY
 LOCAL_INCLUDES  += $(MOZ_QT_CFLAGS) \
                    -I$(topsrcdir)/dom/system/unix \
                    $(NULL)
 endif
 
 ifeq ($(MOZ_WIDGET_TOOLKIT),android)
 LOCAL_INCLUDES  += -I$(topsrcdir)/dom/system/android
--- a/dom/src/geolocation/nsGeolocation.cpp
+++ b/dom/src/geolocation/nsGeolocation.cpp
@@ -22,20 +22,16 @@
 #include "mozilla/Services.h"
 #include "mozilla/unused.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/ClearOnShutdown.h"
 #include "PCOMContentPermissionRequestChild.h"
 
 class nsIPrincipal;
 
-#ifdef MOZ_MAEMO_LIBLOCATION
-#include "MaemoLocationProvider.h"
-#endif
-
 #ifdef MOZ_ENABLE_QTMOBILITY
 #include "QTMLocationProvider.h"
 #endif
 
 #ifdef MOZ_WIDGET_ANDROID
 #include "AndroidLocationProvider.h"
 #endif
 
@@ -676,20 +672,16 @@ nsresult nsGeolocationService::Init()
   nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
   if (!obs) {
     return NS_ERROR_FAILURE;
   }
 
   obs->AddObserver(this, "quit-application", false);
   obs->AddObserver(this, "mozsettings-changed", false);
 
-#ifdef MOZ_MAEMO_LIBLOCATION
-  mProvider = new MaemoLocationProvider();
-#endif
-
 #ifdef MOZ_ENABLE_QTMOBILITY
   mProvider = new QTMLocationProvider();
 #endif
 
 #ifdef MOZ_WIDGET_ANDROID
   mProvider = new AndroidLocationProvider();
 #endif
 
deleted file mode 100644
--- a/dom/system/unix/MaemoLocationProvider.cpp
+++ /dev/null
@@ -1,251 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include <stdio.h>
-#include <math.h>
-#include "nsGeoPosition.h"
-#include "MaemoLocationProvider.h"
-#include "nsIClassInfo.h"
-#include "nsDOMClassInfoID.h"
-#include "nsIServiceManager.h"
-#include "nsServiceManagerUtils.h"
-#include "mozilla/Preferences.h"
-
-using namespace mozilla;
-
-NS_IMPL_ISUPPORTS2(MaemoLocationProvider, nsIGeolocationProvider, nsITimerCallback)
-
-MaemoLocationProvider::MaemoLocationProvider() :
-  mLocationChanged(0),
-  mControlError(0),
-  mDeviceDisconnected(0),
-  mControlStopped(0),
-  mHasSeenLocation(false),
-  mHasGPS(true),
-  mGPSControl(nullptr),
-  mGPSDevice(nullptr),
-  mIgnoreMinorChanges(false),
-  mPrevLat(0.0),
-  mPrevLong(0.0),
-  mIgnoreBigHErr(true),
-  mMaxHErr(1000),
-  mIgnoreBigVErr(true),
-  mMaxVErr(100)
-{
-}
-
-MaemoLocationProvider::~MaemoLocationProvider()
-{
-}
-
-void MaemoLocationProvider::DeviceDisconnected(LocationGPSDevice* device, void* self)
-{
-}
-
-void MaemoLocationProvider::ControlStopped(LocationGPSDControl* device, void* self)
-{
-  MaemoLocationProvider* provider = static_cast<MaemoLocationProvider*>(self);
-  provider->StartControl();
-}
-
-void MaemoLocationProvider::ControlError(LocationGPSDControl* control, void* self)
-{
-}
-
-void MaemoLocationProvider::LocationChanged(LocationGPSDevice* device, void* self)
-{
-  if (!device || !device->fix)
-    return;
-
-  guint32 &fields = device->fix->fields;
-  if (!(fields & LOCATION_GPS_DEVICE_LATLONG_SET))
-    return;
-
-  if (!(device->fix->eph && !isnan(device->fix->eph)))
-    return;
-
-  MaemoLocationProvider* provider = static_cast<MaemoLocationProvider*>(self);
-  NS_ENSURE_TRUE_VOID(provider);
-  provider->LocationUpdate(device);
-}
-
-nsresult
-MaemoLocationProvider::LocationUpdate(LocationGPSDevice* aDev)
-{
-  double hErr = aDev->fix->eph/100;
-  if (mIgnoreBigHErr && hErr > (double)mMaxHErr)
-    hErr = (double)mMaxHErr;
-
-  double vErr = aDev->fix->epv/2;
-  if (mIgnoreBigVErr && vErr > (double)mMaxVErr)
-    vErr = (double)mMaxVErr;
-
-  double altitude = 0, speed = 0, track = 0;
-  if (aDev->fix->epv && !isnan(aDev->fix->epv))
-    altitude = aDev->fix->altitude;
-  if (aDev->fix->eps && !isnan(aDev->fix->eps))
-    speed = aDev->fix->speed;
-  if (aDev->fix->epd && !isnan(aDev->fix->epd))
-    track = aDev->fix->track;
-
-#ifdef DEBUG
-  double dist = location_distance_between(mPrevLat, mPrevLong, aDev->fix->latitude, aDev->fix->longitude)*1000;
-  fprintf(stderr, "dist:%.9f, Lat: %.6f, Long:%.6f, HErr:%g, Alt:%.6f, VErr:%g, dir:%g[%g], sp:%g[%g]\n",
-           dist, aDev->fix->latitude, aDev->fix->longitude,
-           hErr, altitude,
-           aDev->fix->epv/2, track, aDev->fix->epd,
-           speed, aDev->fix->eps);
-  mPrevLat = aDev->fix->latitude;
-  mPrevLong = aDev->fix->longitude;
-#endif
-
-  nsRefPtr<nsGeoPosition> somewhere = new nsGeoPosition(aDev->fix->latitude,
-                                                        aDev->fix->longitude,
-                                                        altitude,
-                                                        hErr,
-                                                        vErr,
-                                                        track,
-                                                        speed,
-                                                        PR_Now());
-  Update(somewhere);
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-MaemoLocationProvider::Notify(nsITimer* aTimer)
-{
-  LocationChanged(mGPSDevice, this);
-  return NS_OK;
-}
-
-nsresult
-MaemoLocationProvider::StartControl()
-{
-  if (mGPSControl)
-    return NS_OK;
-
-  mGPSControl = location_gpsd_control_get_default();
-  NS_ENSURE_TRUE(mGPSControl, NS_ERROR_FAILURE);
-
-  mControlError = g_signal_connect(mGPSControl, "error",
-                                   G_CALLBACK(ControlError), this);
-
-  mControlStopped = g_signal_connect(mGPSControl, "gpsd_stopped",
-                                     G_CALLBACK(ControlStopped), this);
-
-  location_gpsd_control_start(mGPSControl);
-  return NS_OK;
-}
-
-nsresult
-MaemoLocationProvider::StartDevice()
-{
-  if (mGPSDevice)
-    return NS_OK;
-
-  mGPSDevice = (LocationGPSDevice*)g_object_new(LOCATION_TYPE_GPS_DEVICE, NULL);
-  NS_ENSURE_TRUE(mGPSDevice, NS_ERROR_FAILURE);
-
-  mLocationChanged    = g_signal_connect(mGPSDevice, "changed",
-                                         G_CALLBACK(LocationChanged), this);
-
-  mDeviceDisconnected = g_signal_connect(mGPSDevice, "disconnected",
-                                         G_CALLBACK(DeviceDisconnected), this);
-  return NS_OK;
-}
-
-NS_IMETHODIMP MaemoLocationProvider::Startup()
-{
-  nsresult rv(NS_OK);
-
-  rv = StartControl();
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  rv = StartDevice();
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  mIgnoreBigHErr =
-    Preferences::GetBool("geo.herror.ignore.big", mIgnoreBigHErr);
-
-  if (mIgnoreBigHErr) {
-    mMaxHErr = Preferences::GetInt("geo.herror.max.value", mMaxHErr);
-  }
-
-  mIgnoreBigVErr =
-    Preferences::GetBool("geo.verror.ignore.big", mIgnoreBigVErr);
-
-  if (mIgnoreBigVErr) {
-    mMaxVErr = Preferences::GetInt("geo.verror.max.value", mMaxVErr);
-  }
-
-  if (mUpdateTimer)
-    return NS_OK;
-
-  // 0 second no timer created
-  int32_t update = Preferences::GetInt("geo.default.update", 0);
-
-  if (!update)
-    return NS_OK;
-
-  mUpdateTimer = do_CreateInstance("@mozilla.org/timer;1", &rv);
-
-  if (NS_FAILED(rv))
-    return NS_ERROR_FAILURE;
-
-  if (update)
-    mUpdateTimer->InitWithCallback(this, update, nsITimer::TYPE_REPEATING_SLACK);
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP MaemoLocationProvider::Watch(nsIGeolocationUpdate *callback)
-{
-  if (mCallback)
-    return NS_OK;
-
-  mCallback = callback;
-  return NS_OK;
-}
-
-NS_IMETHODIMP MaemoLocationProvider::Shutdown()
-{
-  if (mUpdateTimer)
-    mUpdateTimer->Cancel();
-
-  g_signal_handler_disconnect(mGPSDevice, mLocationChanged);
-  g_signal_handler_disconnect(mGPSDevice, mDeviceDisconnected);
-
-  g_signal_handler_disconnect(mGPSDevice, mControlError);
-  g_signal_handler_disconnect(mGPSDevice, mControlStopped);
-
-  mHasSeenLocation = false;
-  mCallback = nullptr;
-
-  if (mGPSControl) {
-    location_gpsd_control_stop(mGPSControl);
-    g_object_unref(mGPSControl);
-    mGPSControl = nullptr;
-  }
-  if (mGPSDevice) {
-    g_object_unref(mGPSDevice);
-    mGPSDevice = nullptr;
-  }
-
-  return NS_OK;
-}
-
-void MaemoLocationProvider::Update(nsIDOMGeoPosition* aPosition)
-{
-  mHasSeenLocation = true;
-  if (mCallback)
-    mCallback->Update(aPosition);
-}
-
-NS_IMETHODIMP
-MaemoLocationProvider::SetHighAccuracy(bool)
-{
-  return NS_OK;
-}
deleted file mode 100644
--- a/dom/system/unix/MaemoLocationProvider.h
+++ /dev/null
@@ -1,85 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "nsCOMPtr.h"
-#include "nsAutoPtr.h"
-#include "nsCOMArray.h"
-#include "nsTArray.h"
-#include "nsITimer.h"
-#include "nsIObserver.h"
-#include "nsIURI.h"
-
-#include "nsWeakPtr.h"
-#include "nsCycleCollectionParticipant.h"
-
-#include "nsIDOMGeoGeolocation.h"
-#include "nsIDOMGeoPosition.h"
-#include "nsIDOMGeoPositionError.h"
-#include "nsIDOMGeoPositionCallback.h"
-#include "nsIDOMGeoPositionErrorCallback.h"
-#include "nsIDOMGeoPositionCoords.h"
-
-#include "nsPIDOMWindow.h"
-
-#include "nsIGeolocationProvider.h"
-
-
-extern "C"
-{
-#include <location/location-gps-device.h>
-#include <location/location-gpsd-control.h>
-#include <location/location-distance-utils.h>
-#include <location/location-misc.h>
-}
-
-class MaemoLocationProvider : public nsIGeolocationProvider,
-                              public nsITimerCallback
-
-{
- public:
-  NS_DECL_ISUPPORTS
-  NS_DECL_NSIGEOLOCATIONPROVIDER
-  NS_DECL_NSITIMERCALLBACK
-
-  MaemoLocationProvider();
-
-  void Update(nsIDOMGeoPosition* aPosition);
-
- private:
-  ~MaemoLocationProvider();
-
-  nsresult StartControl();
-  nsresult StartDevice();
-  nsresult LocationUpdate(LocationGPSDevice* aDev);
-
-  static void DeviceDisconnected(LocationGPSDevice* device, void* self);
-  static void ControlStopped(LocationGPSDControl* device, void* self);
-  static void ControlError(LocationGPSDControl* control, void* self);
-  static void LocationChanged(LocationGPSDevice* device, void* self);
-
-  gulong mLocationChanged;
-  gulong mControlError;
-  gulong mDeviceDisconnected;
-  gulong mControlStopped;
-
-  nsCOMPtr<nsIGeolocationUpdate> mCallback;
-  bool mHasSeenLocation;
-  bool mHasGPS;
-
-  nsCOMPtr<nsITimer> mUpdateTimer;
-  LocationGPSDControl* mGPSControl;
-  LocationGPSDevice* mGPSDevice;
-
-  bool mIgnoreMinorChanges;
-
-  double mPrevLat;
-  double mPrevLong;
-
-  bool mIgnoreBigHErr;
-  int32_t mMaxHErr;
-  bool mIgnoreBigVErr;
-  int32_t mMaxVErr;
-
-};
--- a/dom/system/unix/Makefile.in
+++ b/dom/system/unix/Makefile.in
@@ -5,26 +5,16 @@
 DEPTH       = @DEPTH@
 topsrcdir   = @top_srcdir@
 srcdir      = @srcdir@
 VPATH       = @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 EXPORT_LIBRARY = 1
-ifdef MOZ_MAEMO_LIBLOCATION
-        LOCAL_INCLUDES  += $(MOZ_PLATFORM_MAEMO_CFLAGS) \
-                           -I$(topsrcdir)/dom/src/geolocation \
-                           $(NULL)
-endif
-
-ifdef MOZ_PLATFORM_MAEMO
-LOCAL_INCLUDES  += $(MOZ_DBUS_CFLAGS) \
-                   $(NULL)
-endif
 ifdef MOZ_ENABLE_QTMOBILITY
 LOCAL_INCLUDES  += $(MOZ_QT_CFLAGS) \
                    -I$(topsrcdir)/dom/src/geolocation \
                    $(NULL)
 endif
 
 include $(topsrcdir)/config/rules.mk
 include $(topsrcdir)/ipc/chromium/chromium-config.mk
--- a/dom/system/unix/moz.build
+++ b/dom/system/unix/moz.build
@@ -1,26 +1,16 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 MODULE = 'dom'
 
-if CONFIG['MOZ_MAEMO_LIBLOCATION']:
-    CPP_SOURCES += [
-        'MaemoLocationProvider.cpp',
-    ]
-
-if CONFIG['MOZ_PLATFORM_MAEMO']:
-    CPP_SOURCES += [
-        'nsHapticFeedback.cpp',
-    ]
-
 if CONFIG['MOZ_ENABLE_QTMOBILITY']:
     CPP_SOURCES += [
         'moc_QTMLocationProvider.cpp',
         'QTMLocationProvider.cpp',
     ]
 
 FAIL_ON_WARNINGS = True
 
--- a/dom/workers/RuntimeService.cpp
+++ b/dom/workers/RuntimeService.cpp
@@ -859,23 +859,16 @@ public:
 
     // The CC is shutdown, and this will GC, so make sure we don't try to CC
     // again.
     mWorkerPrivate = nullptr;
     JS_DestroyContext(mLastJSContext);
     mLastJSContext = nullptr;
   }
 
-  // Make this public for now.  Ideally we'd hide the JSRuntime inside.
-  JSRuntime*
-  Runtime() const
-  {
-    return mozilla::CycleCollectedJSRuntime::Runtime();
-  }
-
   void
   DispatchDeferredDeletion(bool aContinuation) MOZ_OVERRIDE
   {
     MOZ_ASSERT(!aContinuation);
 
     // Do it immediately, no need for asynchronous behavior here.
     nsCycleCollector_doDeferredDeletion();
   }
@@ -1115,16 +1108,30 @@ WorkerCrossThreadDispatcher::PostTask(Wo
 
 WorkerPrivate*
 GetWorkerPrivateFromContext(JSContext* aCx)
 {
   NS_ASSERTION(!NS_IsMainThread(), "Wrong thread!");
   return static_cast<WorkerThreadRuntimePrivate*>(JS_GetRuntimePrivate(JS_GetRuntime(aCx)))->mWorkerPrivate;
 }
 
+bool
+IsCurrentThreadRunningChromeWorker()
+{
+  NS_ASSERTION(!NS_IsMainThread(), "Wrong thread!");
+  CycleCollectedJSRuntime* ccrt = nsCycleCollector_currentJSRuntime();
+  if (!ccrt) {
+    return false;
+  }
+
+  JSRuntime* rt = ccrt->Runtime();
+  return static_cast<WorkerThreadRuntimePrivate*>(JS_GetRuntimePrivate(rt))->
+    mWorkerPrivate->UsesSystemPrincipal();
+}
+
 END_WORKERS_NAMESPACE
 
 // This is only touched on the main thread. Initialized in Init() below.
 JSSettings RuntimeService::sDefaultJSSettings;
 
 RuntimeService::RuntimeService()
 : mMutex("RuntimeService::mMutex"), mObserved(false),
   mShuttingDown(false), mNavigatorStringsLoaded(false)
--- a/dom/workers/WorkerPrivate.h
+++ b/dom/workers/WorkerPrivate.h
@@ -963,16 +963,19 @@ private:
 
   static bool
   CheckXHRParamsAllowed(nsPIDOMWindow* aWindow);
 };
 
 WorkerPrivate*
 GetWorkerPrivateFromContext(JSContext* aCx);
 
+bool
+IsCurrentThreadRunningChromeWorker();
+
 enum WorkerStructuredDataType
 {
   DOMWORKER_SCTAG_FILE = SCTAG_DOM_MAX,
   DOMWORKER_SCTAG_BLOB,
 
   DOMWORKER_SCTAG_END
 };
 
--- a/gfx/gl/GLContextProvider.h
+++ b/gfx/gl/GLContextProvider.h
@@ -35,17 +35,17 @@ namespace gl {
 
 #ifdef XP_MACOSX
 #define GL_CONTEXT_PROVIDER_NAME GLContextProviderCGL
 #include "GLContextProviderImpl.h"
 #undef GL_CONTEXT_PROVIDER_NAME
 #define GL_CONTEXT_PROVIDER_DEFAULT GLContextProviderCGL
 #endif
 
-#if defined(ANDROID) || defined(MOZ_PLATFORM_MAEMO) || defined(XP_WIN)
+#if defined(ANDROID) || defined(XP_WIN)
 #define GL_CONTEXT_PROVIDER_NAME GLContextProviderEGL
 #include "GLContextProviderImpl.h"
 #undef GL_CONTEXT_PROVIDER_NAME
 #ifndef GL_CONTEXT_PROVIDER_DEFAULT
 #define GL_CONTEXT_PROVIDER_DEFAULT GLContextProviderEGL
 #endif
 #endif
 
--- a/gfx/gl/GLContextProviderEGL.cpp
+++ b/gfx/gl/GLContextProviderEGL.cpp
@@ -117,17 +117,17 @@ public:
 #include "nsThreadUtils.h"
 
 #include "nsIWidget.h"
 
 #include "gfxCrashReporterUtils.h"
 
 using namespace mozilla::gfx;
 
-#if defined(MOZ_PLATFORM_MAEMO) || defined(MOZ_WIDGET_GONK)
+#if defined(MOZ_WIDGET_GONK)
 static bool gUseBackingSurface = true;
 #else
 static bool gUseBackingSurface = false;
 #endif
 
 #ifdef MOZ_WIDGET_GONK
 extern nsIntRect gScreenBounds;
 #endif
@@ -1985,19 +1985,17 @@ GLContextEGL::CreateEGLPixmapOffscreenCo
         return nullptr;
     }
 
     glContext->HoldSurface(thebesSurface);
 
     return glContext.forget();
 }
 
-// Under EGL, if we're under X11, then we have to create a Pixmap
-// because Maemo's EGL implementation doesn't support pbuffers at all
-// for some reason.  On Android, pbuffers are supported fine, though
+// Under EGL, on Android, pbuffers are supported fine, though
 // often without the ability to texture from them directly.
 already_AddRefed<GLContext>
 GLContextProviderEGL::CreateOffscreen(const gfxIntSize& size,
                                       const SurfaceCaps& caps,
                                       ContextFlags flags)
 {
     if (!sEGLLibrary.EnsureInitialized()) {
         return nullptr;
--- a/gfx/gl/moz.build
+++ b/gfx/gl/moz.build
@@ -8,28 +8,22 @@ MODULE = 'gl'
 
 gl_provider = 'Null'
 
 if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'windows':
     gl_provider = 'WGL'
 elif CONFIG['MOZ_WIDGET_TOOLKIT'] == 'cocoa':
     gl_provider = 'CGL'
 elif CONFIG['MOZ_WIDGET_GTK']:
-    if CONFIG['MOZ_PLATFORM_MAEMO']:
-        gl_provider = 'EGL'
-    else:
-        if CONFIG['MOZ_EGL_XRENDER_COMPOSITE']:
-            gl_provider = 'EGL'
-        else:
-            gl_provider = 'GLX'
-elif CONFIG['MOZ_WIDGET_TOOLKIT'] == 'qt':
-    if CONFIG['MOZ_PLATFORM_MAEMO']:
+    if CONFIG['MOZ_EGL_XRENDER_COMPOSITE']:
         gl_provider = 'EGL'
     else:
         gl_provider = 'GLX'
+elif CONFIG['MOZ_WIDGET_TOOLKIT'] == 'qt':
+    gl_provider = 'GLX'
 elif CONFIG['MOZ_WIDGET_TOOLKIT'] == 'android':
     gl_provider = 'EGL'
 elif CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
     gl_provider = 'EGL'
 
 if CONFIG['MOZ_GL_PROVIDER']:
     gl_provider = CONFIG['MOZ_GL_PROVIDER']
 
--- a/gfx/layers/d3d9/DeviceManagerD3D9.cpp
+++ b/gfx/layers/d3d9/DeviceManagerD3D9.cpp
@@ -243,22 +243,16 @@ DeviceManagerD3D9::Init()
 
   D3DADAPTER_IDENTIFIER9 ident;
   hr = mD3D9->GetAdapterIdentifier(D3DADAPTER_DEFAULT, 0, &ident);
 
   if (FAILED(hr)) {
     return false;
   }
 
-  if (!PL_strncasecmp(ident.Driver, "nvumdshim.dll", strlen(ident.Driver))) {
-    // XXX - This is a device using NVidia Optimus. We have no idea how to do
-    // interop here so let's fail and use BasicLayers. See bug 597320.
-    return false;
-  }
-
   D3DPRESENT_PARAMETERS pp;
   memset(&pp, 0, sizeof(D3DPRESENT_PARAMETERS));
 
   pp.BackBufferWidth = 1;
   pp.BackBufferHeight = 1;
   pp.BackBufferFormat = D3DFMT_A8R8G8B8;
   pp.SwapEffect = D3DSWAPEFFECT_DISCARD;
   pp.Windowed = TRUE;
--- a/gfx/layers/ipc/ISurfaceAllocator.cpp
+++ b/gfx/layers/ipc/ISurfaceAllocator.cpp
@@ -24,26 +24,17 @@
 
 using namespace mozilla::ipc;
 
 namespace mozilla {
 namespace layers {
 
 SharedMemory::SharedMemoryType OptimalShmemType()
 {
-#if defined(MOZ_PLATFORM_MAEMO) && defined(MOZ_HAVE_SHAREDMEMORYSYSV)
-  // Use SysV memory because maemo5 on the N900 only allots 64MB to
-  // /dev/shm, even though it has 1GB(!!) of system memory.  Sys V shm
-  // is allocated from a different pool.  We don't want an arbitrary
-  // cap that's much much lower than available memory on the memory we
-  // use for layers.
-  return SharedMemory::TYPE_SYSV;
-#else
   return SharedMemory::TYPE_BASIC;
-#endif
 }
 
 bool
 IsSurfaceDescriptorValid(const SurfaceDescriptor& aSurface)
 {
   return aSurface.type() != SurfaceDescriptor::T__None &&
          aSurface.type() != SurfaceDescriptor::Tnull_t;
 }
--- a/gfx/thebes/gfxAndroidPlatform.cpp
+++ b/gfx/thebes/gfxAndroidPlatform.cpp
@@ -173,16 +173,17 @@ IsJapaneseLocale()
 }
 
 void
 gfxAndroidPlatform::GetCommonFallbackFonts(const uint32_t aCh,
                                            int32_t aRunScript,
                                            nsTArray<const char*>& aFontList)
 {
     static const char kDroidSansJapanese[] = "Droid Sans Japanese";
+    static const char kMotoyaLMaru[] = "MotoyaLMaru";
 
     if (IS_IN_BMP(aCh)) {
         // try language-specific "Droid Sans *" fonts for certain blocks,
         // as most devices probably have these
         uint8_t block = (aCh >> 8) & 0xff;
         switch (block) {
         case 0x05:
             aFontList.AppendElement("Droid Sans Hebrew");
@@ -203,21 +204,23 @@ gfxAndroidPlatform::GetCommonFallbackFon
         case 0x10: case 0x2d:
             aFontList.AppendElement("Droid Sans Georgian");
             break;
         case 0x12: case 0x13:
             aFontList.AppendElement("Droid Sans Ethiopic");
             break;
         case 0xf9: case 0xfa:
             if (IsJapaneseLocale()) {
+                aFontList.AppendElement(kMotoyaLMaru);
                 aFontList.AppendElement(kDroidSansJapanese);
             }
             break;
         default:
             if (block >= 0x2e && block <= 0x9f && IsJapaneseLocale()) {
+                aFontList.AppendElement(kMotoyaLMaru);
                 aFontList.AppendElement(kDroidSansJapanese);
             }
             break;
         }
     }
     // and try Droid Sans Fallback as a last resort
     aFontList.AppendElement("Droid Sans Fallback");
 }
--- a/gfx/thebes/gfxFont.h
+++ b/gfx/thebes/gfxFont.h
@@ -600,21 +600,22 @@ private:
         // Declarations for nsTHashtable
 
         typedef nsUint32HashKey KeyClass;
         typedef KeyClass::KeyType KeyType;
         typedef KeyClass::KeyTypePointer KeyTypePointer;
 
         FontTableHashEntry(KeyTypePointer aTag)
             : KeyClass(aTag), mBlob() { }
-        // Copying transfers blob association.
-        FontTableHashEntry(FontTableHashEntry& toCopy)
-            : KeyClass(toCopy), mBlob(toCopy.mBlob)
+
+        FontTableHashEntry(FontTableHashEntry&& toMove)
+            : KeyClass(mozilla::Move(toMove))
+            , mBlob(mozilla::Move(toMove.mBlob))
         {
-            toCopy.mBlob = nullptr;
+            toMove.mBlob = nullptr;
         }
 
         ~FontTableHashEntry() { Clear(); }
 
         // FontTable/Blob API
 
         // Transfer (not copy) elements of aTable to a new hb_blob_t and
         // return ownership to the caller.  A weak reference to the blob is
--- a/gfx/thebes/gfxPlatformGtk.h
+++ b/gfx/thebes/gfxPlatformGtk.h
@@ -94,28 +94,17 @@ public:
     static void SetGdkDrawable(gfxASurface *target,
                                GdkDrawable *drawable);
     static GdkDrawable *GetGdkDrawable(gfxASurface *target);
 #endif
 
     static int32_t GetDPI();
 
     bool UseXRender() {
-#if defined(MOZ_X11) && defined(MOZ_PLATFORM_MAEMO)
-        // XRender is not accelerated on the Maemo at the moment, and 
-        // X server pixman is out of our control; it's likely to be 
-        // older than (our) cairo's.   So fall back on software 
-        // rendering for more predictable performance.
-        // This setting will likely not be relevant when we have
-        // GL-accelerated compositing. We know of other platforms 
-        // with bad drivers where we'd like to also use client side 
-        // rendering, but until we have the ability to featuer test 
-        // this, we'll only disable this for maemo.
-        return true;
-#elif defined(MOZ_X11)
+#if defined(MOZ_X11)
         if (GetContentBackend() != mozilla::gfx::BACKEND_NONE &&
             GetContentBackend() != mozilla::gfx::BACKEND_CAIRO)
             return false;
 
         return sUseXRender;
 #else
         return false;
 #endif
--- a/image/src/RasterImage.cpp
+++ b/image/src/RasterImage.cpp
@@ -391,18 +391,16 @@ RasterImage::RasterImage(imgStatusTracke
   mDecodeCount(0),
 #ifdef DEBUG
   mFramesNotified(0),
 #endif
   mDecodingMutex("RasterImage"),
   mDecoder(nullptr),
   mBytesDecoded(0),
   mInDecoder(false),
-  mStatusDiff(ImageStatusDiff::NoChange()),
-  mNotifying(false),
   mHasSize(false),
   mDecodeOnDraw(false),
   mMultipart(false),
   mDiscardable(false),
   mHasSourceData(false),
   mDecoded(false),
   mHasBeenDecoded(false),
   mAnimationFinished(false),
@@ -2893,43 +2891,16 @@ RasterImage::GetFramesNotified(uint32_t 
 
   *aFramesNotified = mFramesNotified;
 
   return NS_OK;
 }
 #endif
 
 nsresult
-RasterImage::RequestDecodeIfNeeded(nsresult aStatus,
-                                   eShutdownIntent aIntent,
-                                   bool aDone,
-                                   bool aWasSize)
-{
-  MOZ_ASSERT(NS_IsMainThread());
-
-  // If we were a size decode and a full decode was requested, now's the time.
-  if (NS_SUCCEEDED(aStatus) &&
-      aIntent != eShutdownIntent_Error &&
-      aDone &&
-      aWasSize &&
-      mWantFullDecode) {
-    mWantFullDecode = false;
-
-    // If we're not meant to be storing source data and we just got the size,
-    // we need to synchronously flush all the data we got to a full decoder.
-    // When that decoder is shut down, we'll also clear our source data.
-    return StoringSourceData() ? RequestDecode()
-                               : SyncDecode();
-  }
-
-  // We don't need a full decode right now, so just return the existing status.
-  return aStatus;
-}
-
-nsresult
 RasterImage::FinishedSomeDecoding(eShutdownIntent aIntent /* = eShutdownIntent_Done */,
                                   DecodeRequest* aRequest /* = nullptr */)
 {
   MOZ_ASSERT(NS_IsMainThread());
 
   mDecodingMutex.AssertCurrentThreadOwns();
 
   nsRefPtr<DecodeRequest> request;
@@ -2987,49 +2958,49 @@ RasterImage::FinishedSomeDecoding(eShutd
       // decoding routines have been finished.
       rv = image->ShutdownDecoder(aIntent);
       if (NS_FAILED(rv)) {
         image->DoError();
       }
     }
   }
 
-  ImageStatusDiff diff =
-    request ? image->mStatusTracker->Difference(request->mStatusTracker)
-            : image->mStatusTracker->DecodeStateAsDifference();
-  image->mStatusTracker->ApplyDifference(diff);
-
-  // Notifications can't go out with the decoding lock held, nor can we call
-  // RequestDecodeIfNeeded, so unlock for the rest of the function.
-  MutexAutoUnlock unlock(mDecodingMutex);
-
-  if (mNotifying) {
-    // Accumulate the status changes. We don't permit recursive notifications
-    // because they cause subtle concurrency bugs, so we'll delay sending out
-    // the notifications until we pop back to the lowest invocation of
-    // FinishedSomeDecoding on the stack.
-    mStatusDiff.Combine(diff);
+  ImageStatusDiff diff;
+  if (request) {
+    diff = image->mStatusTracker->Difference(request->mStatusTracker);
+    image->mStatusTracker->ApplyDifference(diff);
   } else {
-    MOZ_ASSERT(mStatusDiff.IsNoChange(), "Shouldn't have an accumulated change at this point");
-
-    while (!diff.IsNoChange()) {
-      // Tell the observers what happened.
-      mNotifying = true;
-      image->mStatusTracker->SyncNotifyDifference(diff);
-      mNotifying = false;
-
-      // Gather any status changes that may have occurred as a result of sending
-      // out the previous notifications. If there were any, we'll send out
-      // notifications for them next.
-      diff = mStatusDiff;
-      mStatusDiff = ImageStatusDiff::NoChange();
+    diff = image->mStatusTracker->DecodeStateAsDifference();
+  }
+
+  {
+    // Notifications can't go out with the decoding lock held.
+    MutexAutoUnlock unlock(mDecodingMutex);
+
+    // Then, tell the observers what has happened.
+    image->mStatusTracker->SyncNotifyDifference(diff);
+
+    // If we were a size decode and a full decode was requested, now's the time.
+    if (NS_SUCCEEDED(rv) && aIntent != eShutdownIntent_Error && done &&
+        wasSize && image->mWantFullDecode) {
+      image->mWantFullDecode = false;
+
+      // If we're not meant to be storing source data and we just got the size,
+      // we need to synchronously flush all the data we got to a full decoder.
+      // When that decoder is shut down, we'll also clear our source data.
+      if (!image->StoringSourceData()) {
+        rv = image->SyncDecode();
+      } else {
+        rv = image->RequestDecode();
+      }
     }
+
   }
 
-  return RequestDecodeIfNeeded(rv, aIntent, done, wasSize);
+  return rv;
 }
 
 NS_IMPL_ISUPPORTS1(RasterImage::DecodePool,
                               nsIObserver)
 
 /* static */ RasterImage::DecodePool*
 RasterImage::DecodePool::Singleton()
 {
--- a/image/src/RasterImage.h
+++ b/image/src/RasterImage.h
@@ -641,20 +641,16 @@ private: // data
   // Decoder and friends
   nsRefPtr<Decoder>          mDecoder;
   nsRefPtr<DecodeRequest>    mDecodeRequest;
   uint32_t                   mBytesDecoded;
 
   bool                       mInDecoder;
   // END LOCKED MEMBER VARIABLES
 
-  // Notification state. Used to avoid recursive notifications.
-  ImageStatusDiff            mStatusDiff;
-  bool                       mNotifying:1;
-
   // Boolean flags (clustered together to conserve space):
   bool                       mHasSize:1;       // Has SetSize() been called?
   bool                       mDecodeOnDraw:1;  // Decoding on draw?
   bool                       mMultipart:1;     // Multipart?
   bool                       mDiscardable:1;   // Is container discardable?
   bool                       mHasSourceData:1; // Do we have source data?
 
   // Do we have the frames in decoded form?
@@ -671,20 +667,16 @@ private: // data
 
   bool                       mInUpdateImageContainer:1;
 
   // Whether, once we are done doing a size decode, we should immediately kick
   // off a full decode.
   bool                       mWantFullDecode:1;
 
   // Decoding
-  nsresult RequestDecodeIfNeeded(nsresult aStatus,
-                                 eShutdownIntent aIntent,
-                                 bool aDone,
-                                 bool aWasSize);
   nsresult WantDecodedFrames();
   nsresult SyncDecode();
   nsresult InitDecoder(bool aDoSizeDecode, bool aIsSynchronous = false);
   nsresult WriteToDecoder(const char *aBuffer, uint32_t aCount);
   nsresult DecodeSomeData(uint32_t aMaxBytes);
   bool     IsDecodeFinished();
   TimeStamp mDrawStartTime;
 
--- a/image/src/VectorImage.cpp
+++ b/image/src/VectorImage.cpp
@@ -24,16 +24,17 @@
 #include "nsPresContext.h"
 #include "nsRect.h"
 #include "nsServiceManagerUtils.h"
 #include "nsStubDocumentObserver.h"
 #include "nsSVGEffects.h" // for nsSVGRenderingObserver
 #include "nsSVGUtils.h"  // for nsSVGUtils::ConvertToSurfaceSize
 #include "Orientation.h"
 #include "SVGDocumentWrapper.h"
+#include "nsIDOMEventListener.h"
 
 namespace mozilla {
 
 using namespace dom;
 using namespace layers;
 
 namespace image {
 
--- a/js/public/HashTable.h
+++ b/js/public/HashTable.h
@@ -133,28 +133,28 @@ class HashMap
     typedef typename Impl::AddPtr AddPtr;
     AddPtr lookupForAdd(const Lookup &l) const {
         return impl.lookupForAdd(l);
     }
 
     template<typename KeyInput, typename ValueInput>
     bool add(AddPtr &p, const KeyInput &k, const ValueInput &v) {
         Entry e(k, v);
-        return impl.add(p, mozilla::Move(e));
+        return impl.add(p, mozilla::OldMove(e));
     }
 
     bool add(AddPtr &p, const Key &k) {
         Entry e(k, Value());
-        return impl.add(p, mozilla::Move(e));
+        return impl.add(p, mozilla::OldMove(e));
     }
 
     template<typename KeyInput, typename ValueInput>
     bool relookupOrAdd(AddPtr &p, const KeyInput &k, const ValueInput &v) {
         Entry e(k, v);
-        return impl.relookupOrAdd(p, k, mozilla::Move(e));
+        return impl.relookupOrAdd(p, k, mozilla::OldMove(e));
     }
 
     // |all()| returns a Range containing |count()| elements. E.g.:
     //
     //   typedef HashMap<int,char> HM;
     //   HM h;
     //   for (HM::Range r = h.all(); !r.empty(); r.popFront())
     //     char c = r.front().value;
@@ -226,17 +226,17 @@ class HashMap
         }
         return add(p, k, v);
     }
 
     // Like put, but assert that the given key is not already present.
     template<typename KeyInput, typename ValueInput>
     bool putNew(const KeyInput &k, const ValueInput &v) {
         Entry e(k, v);
-        return impl.putNew(k, mozilla::Move(e));
+        return impl.putNew(k, mozilla::OldMove(e));
     }
 
     // Add (k,defaultValue) if |k| is not found. Return a false-y Ptr on oom.
     Ptr lookupWithDefault(const Key &k, const Value &defaultValue) {
         AddPtr p = lookupForAdd(k);
         if (p)
             return p;
         (void)add(p, k, defaultValue);  // p is left false-y on oom.
@@ -253,18 +253,18 @@ class HashMap
     void rekey(const Lookup &old_key, const Key &new_key) {
         if (old_key != new_key) {
             if (Ptr p = lookup(old_key))
                 impl.rekeyAndMaybeRehash(p, new_key, new_key);
         }
     }
 
     // HashMap is movable
-    HashMap(mozilla::MoveRef<HashMap> rhs) : impl(mozilla::Move(rhs->impl)) {}
-    void operator=(mozilla::MoveRef<HashMap> rhs) { impl = mozilla::Move(rhs->impl); }
+    HashMap(mozilla::MoveRef<HashMap> rhs) : impl(mozilla::OldMove(rhs->impl)) {}
+    void operator=(mozilla::MoveRef<HashMap> rhs) { impl = mozilla::OldMove(rhs->impl); }
 
   private:
     // HashMap is not copyable or assignable
     HashMap(const HashMap &hm) MOZ_DELETE;
     HashMap &operator=(const HashMap &hm) MOZ_DELETE;
 
     friend class Impl::Enum;
 };
@@ -452,18 +452,18 @@ class HashSet
     void rekey(const Lookup &old_key, const T &new_key) {
         if (old_key != new_key) {
             if (Ptr p = lookup(old_key))
                 impl.rekeyAndMaybeRehash(p, new_key, new_key);
         }
     }
 
     // HashSet is movable
-    HashSet(mozilla::MoveRef<HashSet> rhs) : impl(mozilla::Move(rhs->impl)) {}
-    void operator=(mozilla::MoveRef<HashSet> rhs) { impl = mozilla::Move(rhs->impl); }
+    HashSet(mozilla::MoveRef<HashSet> rhs) : impl(mozilla::OldMove(rhs->impl)) {}
+    void operator=(mozilla::MoveRef<HashSet> rhs) { impl = mozilla::OldMove(rhs->impl); }
 
   private:
     // HashSet is not copyable or assignable
     HashSet(const HashSet &hs) MOZ_DELETE;
     HashSet &operator=(const HashSet &hs) MOZ_DELETE;
 
     friend class Impl::Enum;
 };
@@ -580,17 +580,17 @@ class HashMapEntry
     HashMapEntry(const HashMapEntry &) MOZ_DELETE;
     void operator=(const HashMapEntry &) MOZ_DELETE;
 
   public:
     template<typename KeyInput, typename ValueInput>
     HashMapEntry(const KeyInput &k, const ValueInput &v) : key(k), value(v) {}
 
     HashMapEntry(mozilla::MoveRef<HashMapEntry> rhs)
-      : key(mozilla::Move(rhs->key)), value(mozilla::Move(rhs->value)) { }
+      : key(mozilla::OldMove(rhs->key)), value(mozilla::OldMove(rhs->value)) { }
 
     typedef Key KeyType;
     typedef Value ValueType;
 
     const Key key;
     Value value;
 };
 
@@ -1164,17 +1164,17 @@ class HashTable : private AllocPolicy
         removedCount = 0;
         gen++;
         table = newTable;
 
         // Copy only live entries, leaving removed ones behind.
         for (Entry *src = oldTable, *end = src + oldCap; src < end; ++src) {
             if (src->isLive()) {
                 HashNumber hn = src->getKeyHash();
-                findFreeEntry(hn).setLive(hn, mozilla::Move(src->get()));
+                findFreeEntry(hn).setLive(hn, mozilla::OldMove(src->get()));
                 src->destroy();
             }
         }
 
         // All entries have been destroyed, no need to destroyTable.
         this->free_(oldTable);
         return Rehashed;
     }
@@ -1462,20 +1462,20 @@ class HashTable : private AllocPolicy
         checkUnderloaded();
     }
 
     void rekeyWithoutRehash(Ptr p, const Lookup &l, const Key &k)
     {
         JS_ASSERT(table);
         mozilla::ReentrancyGuard g(*this);
         JS_ASSERT(p.found());
-        typename HashTableEntry<T>::NonConstT t(mozilla::Move(*p));
+        typename HashTableEntry<T>::NonConstT t(mozilla::OldMove(*p));
         HashPolicy::setKey(t, const_cast<Key &>(k));
         remove(*p.entry_);
-        putNewInfallible(l, mozilla::Move(t));
+        putNewInfallible(l, mozilla::OldMove(t));
     }
 
     void rekeyAndMaybeRehash(Ptr p, const Lookup &l, const Key &k)
     {
         rekeyWithoutRehash(p, l, k);
         checkOverRemoved();
     }
 
--- a/js/public/MemoryMetrics.h
+++ b/js/public/MemoryMetrics.h
@@ -272,18 +272,18 @@ struct RuntimeSizes
 struct ZoneStats : js::ZoneStatsPod
 {
     ZoneStats() {
         strings.init();
     }
 
     ZoneStats(mozilla::MoveRef<ZoneStats> other)
         : ZoneStatsPod(other),
-          strings(mozilla::Move(other->strings)),
-          notableStrings(mozilla::Move(other->notableStrings))
+          strings(mozilla::OldMove(other->strings)),
+          notableStrings(mozilla::OldMove(other->notableStrings))
     {}
 
     // Add other's numbers to this object's numbers.  Both objects'
     // notableStrings vectors must be empty at this point, because we can't
     // merge them.  (A NotableStringInfo contains only a prefix of the string,
     // so we can't tell whether two NotableStringInfo objects correspond to the
     // same string.)
     void add(const ZoneStats &other) {
--- a/js/src/build/autoconf/arch.m4
+++ b/js/src/build/autoconf/arch.m4
@@ -32,26 +32,16 @@ if test -z "$MOZ_ARCH"; then
         MOZ_ARCH=armv7-a
         MOZ_FPU=vfp
         MOZ_FLOAT_ABI=softfp
         ;;
     arm-Darwin)
         MOZ_ARCH=toolchain-default
         MOZ_THUMB=yes
         ;;
-    arm-*)
-        if test -n "$MOZ_PLATFORM_MAEMO"; then
-            MOZ_THUMB=no
-            MOZ_ARCH=armv7-a
-            MOZ_FLOAT_ABI=softfp
-        fi
-        if test "$MOZ_PLATFORM_MAEMO" = 6; then
-            MOZ_THUMB=yes
-        fi
-        ;;
     esac
 fi
 
 if test "$MOZ_ARCH" = "armv6" -a "$OS_TARGET" = "Android"; then
    MOZ_FPU=vfp
 fi
 
 MOZ_ARG_WITH_STRING(thumb,
--- a/js/src/build/autoconf/compiler-opts.m4
+++ b/js/src/build/autoconf/compiler-opts.m4
@@ -73,16 +73,95 @@ if test -z "$_MOZ_USE_RTTI"; then
         case "$target" in
         *-mingw*)
             CXXFLAGS="$CXXFLAGS -GR-"
         esac
     fi
 fi
 ])
 
+dnl ========================================================
+dnl =
+dnl = Debugging Options
+dnl =
+dnl ========================================================
+AC_DEFUN([MOZ_DEBUGGING_OPTS],
+[
+dnl Debug info is ON by default.
+if test -z "$MOZ_DEBUG_FLAGS"; then
+  MOZ_DEBUG_FLAGS="-g"
+fi
+
+MOZ_ARG_ENABLE_STRING(debug,
+[  --enable-debug[=DBG]    Enable building with developer debug info
+                           (using compiler flags DBG)],
+[ if test "$enableval" != "no"; then
+    MOZ_DEBUG=1
+    if test -n "$enableval" -a "$enableval" != "yes"; then
+        MOZ_DEBUG_FLAGS=`echo $enableval | sed -e 's|\\\ | |g'`
+        _MOZ_DEBUG_FLAGS_SET=1
+    fi
+  else
+    MOZ_DEBUG=
+  fi ],
+  MOZ_DEBUG=)
+
+MOZ_DEBUG_ENABLE_DEFS="-DDEBUG -D_DEBUG -DTRACING"
+MOZ_ARG_WITH_STRING(debug-label,
+[  --with-debug-label=LABELS
+                          Define DEBUG_<value> for each comma-separated
+                          value given.],
+[ for option in `echo $withval | sed 's/,/ /g'`; do
+    MOZ_DEBUG_ENABLE_DEFS="$MOZ_DEBUG_ENABLE_DEFS -DDEBUG_${option}"
+done])
+
+MOZ_DEBUG_DISABLE_DEFS="-DNDEBUG -DTRIMMED"
+
+if test -n "$MOZ_DEBUG"; then
+    AC_MSG_CHECKING([for valid debug flags])
+    _SAVE_CFLAGS=$CFLAGS
+    CFLAGS="$CFLAGS $MOZ_DEBUG_FLAGS"
+    AC_TRY_COMPILE([#include <stdio.h>],
+        [printf("Hello World\n");],
+        _results=yes,
+        _results=no)
+    AC_MSG_RESULT([$_results])
+    if test "$_results" = "no"; then
+        AC_MSG_ERROR([These compiler flags are invalid: $MOZ_DEBUG_FLAGS])
+    fi
+    CFLAGS=$_SAVE_CFLAGS
+fi
+
+dnl ========================================================
+dnl = Enable generation of debug symbols
+dnl ========================================================
+MOZ_ARG_ENABLE_STRING(debug-symbols,
+[  --enable-debug-symbols[=DBG]
+                          Enable debugging symbols (using compiler flags DBG)],
+[ if test "$enableval" != "no"; then
+      MOZ_DEBUG_SYMBOLS=1
+      if test -n "$enableval" -a "$enableval" != "yes"; then
+          if test -z "$_MOZ_DEBUG_FLAGS_SET"; then
+              MOZ_DEBUG_FLAGS=`echo $enableval | sed -e 's|\\\ | |g'`
+          else
+              AC_MSG_ERROR([--enable-debug-symbols flags cannot be used with --enable-debug flags])
+          fi
+      fi
+  else
+      MOZ_DEBUG_SYMBOLS=
+  fi ],
+  MOZ_DEBUG_SYMBOLS=1)
+
+if test -n "$MOZ_DEBUG" -o -n "$MOZ_DEBUG_SYMBOLS"; then
+    AC_DEFINE(MOZ_DEBUG_SYMBOLS)
+    export MOZ_DEBUG_SYMBOLS
+fi
+
+])
+
 dnl A high level macro for selecting compiler options.
 AC_DEFUN([MOZ_COMPILER_OPTS],
 [
   if test -z "$MOZILLA_OFFICIAL"; then
     DEVELOPER_OPTIONS=1
   fi
   MOZ_ARG_ENABLE_BOOL(release,
   [  --enable-release        Build with more conservative, release engineering-oriented options.
--- a/js/src/builtin/MapObject.cpp
+++ b/js/src/builtin/MapObject.cpp
@@ -20,17 +20,17 @@
 #include "jsobjinlines.h"
 
 #include "gc/Barrier-inl.h"
 
 using namespace js;
 
 using mozilla::DoubleIsInt32;
 using mozilla::IsNaN;
-using mozilla::Move;
+using mozilla::OldMove;
 using mozilla::MoveRef;
 
 
 /*** OrderedHashTable ****************************************************************************/
 
 /*
  * Define two collection templates, js::OrderedHashMap and js::OrderedHashSet.
  * They are like js::HashMap and js::HashSet except that:
@@ -605,17 +605,17 @@ class OrderedHashTable
     void rehashInPlace() {
         for (uint32_t i = 0, N = hashBuckets(); i < N; i++)
             hashTable[i] = NULL;
         Data *wp = data, *end = data + dataLength;
         for (Data *rp = data; rp != end; rp++) {
             if (!Ops::isEmpty(Ops::getKey(rp->element))) {
                 HashNumber h = prepareHash(Ops::getKey(rp->element)) >> hashShift;
                 if (rp != wp)
-                    wp->element = Move(rp->element);
+                    wp->element = OldMove(rp->element);
                 wp->chain = hashTable[h];
                 hashTable[h] = wp;
                 wp++;
             }
         }
         MOZ_ASSERT(wp == data + liveCount);
 
         while (wp != end)
@@ -652,17 +652,17 @@ class OrderedHashTable
             alloc.free_(newHashTable);
             return false;
         }
 
         Data *wp = newData;
         for (Data *p = data, *end = data + dataLength; p != end; p++) {
             if (!Ops::isEmpty(Ops::getKey(p->element))) {
                 HashNumber h = prepareHash(Ops::getKey(p->element)) >> newHashShift;
-                new (wp) Data(Move(p->element), newHashTable[h]);
+                new (wp) Data(OldMove(p->element), newHashTable[h]);
                 newHashTable[h] = wp;
                 wp++;
             }
         }
         MOZ_ASSERT(wp == newData + liveCount);
 
         alloc.free_(hashTable);
         freeData(data, dataLength);
@@ -693,24 +693,24 @@ class OrderedHashMap
     {
         template <class, class, class> friend class detail::OrderedHashTable;
         void operator=(const Entry &rhs) {
             const_cast<Key &>(key) = rhs.key;
             value = rhs.value;
         }
 
         void operator=(MoveRef<Entry> rhs) {
-            const_cast<Key &>(key) = Move(rhs->key);
-            value = Move(rhs->value);
+            const_cast<Key &>(key) = OldMove(rhs->key);
+            value = OldMove(rhs->value);
         }
 
       public:
         Entry() : key(), value() {}
         Entry(const Key &k, const Value &v) : key(k), value(v) {}
-        Entry(MoveRef<Entry> rhs) : key(Move(rhs->key)), value(Move(rhs->value)) {}
+        Entry(MoveRef<Entry> rhs) : key(OldMove(rhs->key)), value(OldMove(rhs->value)) {}
 
         const Key key;
         Value value;
     };
 
   private:
     struct MapOps : OrderedHashPolicy
     {
--- a/js/src/builtin/TypeRepresentation.cpp
+++ b/js/src/builtin/TypeRepresentation.cpp
@@ -185,16 +185,26 @@ ArrayTypeRepresentation::ArrayTypeRepres
 {
 }
 
 static inline size_t alignTo(size_t address, size_t align) {
     JS_ASSERT(IsPowerOfTwo(align));
     return (address + align - 1) & -align;
 }
 
+StructField::StructField(size_t index,
+                         jsid &id,
+                         TypeRepresentation *typeRepr,
+                         size_t offset)
+  : index(index),
+    id(id),
+    typeRepr(typeRepr),
+    offset(offset)
+{}
+
 StructTypeRepresentation::StructTypeRepresentation()
   : TypeRepresentation(Struct, 0, 1),
     fieldCount_(0) // see ::init() below!
 {
 }
 
 bool
 StructTypeRepresentation::init(JSContext *cx,
--- a/js/src/builtin/TypeRepresentation.h
+++ b/js/src/builtin/TypeRepresentation.h
@@ -245,22 +245,17 @@ struct StructField {
     size_t index;
     HeapId id;
     TypeRepresentation *typeRepr;
     size_t offset;
 
     explicit StructField(size_t index,
                          jsid &id,
                          TypeRepresentation *typeRepr,
-                         size_t offset)
-      : index(index),
-        id(id),
-        typeRepr(typeRepr),
-        offset(offset)
-    {}
+                         size_t offset);
 };
 
 class StructTypeRepresentation : public TypeRepresentation {
   private:
     // so TypeRepresentation can call appendStringStruct() etc
     friend class TypeRepresentation;
 
     size_t fieldCount_;
--- a/js/src/config/config.mk
+++ b/js/src/config/config.mk
@@ -489,18 +489,18 @@ HOST_CMMFLAGS += -fobjc-exceptions
 OS_COMPILE_CMFLAGS += -fobjc-exceptions
 OS_COMPILE_CMMFLAGS += -fobjc-exceptions
 ifeq ($(MOZ_WIDGET_TOOLKIT),uikit)
 OS_COMPILE_CMFLAGS += -fobjc-abi-version=2 -fobjc-legacy-dispatch
 OS_COMPILE_CMMFLAGS += -fobjc-abi-version=2 -fobjc-legacy-dispatch
 endif
 endif
 
-COMPILE_CFLAGS	= $(VISIBILITY_FLAGS) $(DEFINES) $(INCLUDES) $(DSO_CFLAGS) $(DSO_PIC_CFLAGS) $(CFLAGS) $(RTL_FLAGS) $(OS_CPPFLAGS) $(OS_COMPILE_CFLAGS)
-COMPILE_CXXFLAGS = $(STL_FLAGS) $(VISIBILITY_FLAGS) $(DEFINES) $(INCLUDES) $(DSO_CFLAGS) $(DSO_PIC_CFLAGS) $(CXXFLAGS) $(RTL_FLAGS) $(OS_CPPFLAGS) $(OS_COMPILE_CXXFLAGS)
+COMPILE_CFLAGS	= $(VISIBILITY_FLAGS) $(DEFINES) $(INCLUDES) $(DSO_CFLAGS) $(DSO_PIC_CFLAGS) $(RTL_FLAGS) $(OS_CPPFLAGS) $(OS_COMPILE_CFLAGS) $(CFLAGS)
+COMPILE_CXXFLAGS = $(STL_FLAGS) $(VISIBILITY_FLAGS) $(DEFINES) $(INCLUDES) $(DSO_CFLAGS) $(DSO_PIC_CFLAGS) $(RTL_FLAGS) $(OS_CPPFLAGS) $(OS_COMPILE_CXXFLAGS) $(CXXFLAGS)
 COMPILE_CMFLAGS = $(OS_COMPILE_CMFLAGS)
 COMPILE_CMMFLAGS = $(OS_COMPILE_CMMFLAGS)
 
 ifndef CROSS_COMPILE
 HOST_CFLAGS += $(RTL_FLAGS)
 endif
 
 #
--- a/js/src/config/rules.mk
+++ b/js/src/config/rules.mk
@@ -678,19 +678,16 @@ SUBMAKEFILES += $(addsuffix /Makefile, $
 
 # The root makefile doesn't want to do a plain export/libs, because
 # of the tiers and because of libxul. Suppress the default rules in favor
 # of something else. Makefiles which use this var *must* provide a sensible
 # default rule before including rules.mk
 ifndef SUPPRESS_DEFAULT_RULES
 ifndef TIERS
 default all::
-ifneq (,$(strip $(STATIC_DIRS)))
-	$(foreach dir,$(STATIC_DIRS),$(call SUBMAKE,,$(dir),1))
-endif
 	$(MAKE) export
 	$(MAKE) libs
 	$(MAKE) tools
 
 # Do depend as well
 alldep::
 	$(MAKE) export
 	$(MAKE) depend
@@ -825,20 +822,31 @@ endif # NO_PROFILE_GUIDED_OPTIMIZE
 ##############################################
 
 checkout:
 	$(MAKE) -C $(topsrcdir) -f client.mk checkout
 
 clean clobber realclean clobber_all:: $(SUBMAKEFILES)
 	-$(RM) $(ALL_TRASH)
 	-$(RM) -r $(ALL_TRASH_DIRS)
-	$(foreach dir,$(PARALLEL_DIRS) $(DIRS) $(STATIC_DIRS) $(TOOL_DIRS),-$(call SUBMAKE,$@,$(dir)))
+
+ifdef TIERS
+clean clobber realclean clobber_all distclean::
+	$(foreach dir, \
+		$(foreach tier, $(TIERS), $(tier_$(tier)_staticdirs) $(tier_$(tier)_dirs)), \
+		-$(call SUBMAKE,$@,$(dir)))
+else
+clean clobber realclean clobber_all distclean::
+	$(foreach dir,$(PARALLEL_DIRS) $(DIRS) $(TOOL_DIRS),-$(call SUBMAKE,$@,$(dir)))
 
 distclean:: $(SUBMAKEFILES)
-	$(foreach dir,$(PARALLEL_DIRS) $(DIRS) $(STATIC_DIRS) $(TOOL_DIRS),-$(call SUBMAKE,$@,$(dir)))
+	$(foreach dir,$(PARALLEL_DIRS) $(DIRS) $(TOOL_DIRS),-$(call SUBMAKE,$@,$(dir)))
+endif
+
+distclean::
 	-$(RM) -r $(ALL_TRASH_DIRS)
 	-$(RM) $(ALL_TRASH)  \
 	Makefile .HSancillary \
 	$(wildcard *.$(OBJ_SUFFIX)) $(wildcard *.ho) $(wildcard host_*.o*) \
 	$(wildcard *.$(LIB_SUFFIX)) $(wildcard *$(DLL_SUFFIX)) \
 	$(wildcard *.$(IMPORT_LIB_SUFFIX))
 ifeq ($(OS_ARCH),OS2)
 	-$(RM) $(PROGRAM:.exe=.map)
--- a/js/src/config/system-headers
+++ b/js/src/config/system-headers
@@ -1054,42 +1054,27 @@ libsn/sn-monitor.h
 libsn/sn-util.h
 #endif
 #if MOZ_NATIVE_HUNSPELL==1
 hunspell.hxx
 #endif
 #if MOZ_NATIVE_BZ2==1
 bzlib.h
 #endif
-#if MOZ_PLATFORM_MAEMO==5
-hildon-uri.h
-hildon-mime.h
-hildon-file-chooser-dialog.h
-libosso.h
-osso-mem.h
-#endif
 #ifdef MOZ_ENABLE_GIO
 gio/gio.h
 #endif
-#ifdef MOZ_ENABLE_LIBCONIC
-conic/conicconnection.h
-conic/conicconnectionevent.h
-conic/conicstatisticsevent.h
-#endif
 #if MOZ_NATIVE_LIBEVENT==1
 event.h
 #else
 sys/event.h
 #endif
 #ifdef MOZ_ENABLE_LIBPROXY
 proxy.h
 #endif
-#if MOZ_PLATFORM_MAEMO==6
-contentaction/contentaction.h
-#endif
 #ifdef MOZ_ENABLE_CONTENTMANAGER
 SelectSingleContentItemPage.h
 SelectMultipleContentItemsPage.h
 QtSparql/qsparqlconnection.h
 QtSparql/qsparqlquery.h
 QtSparql/qsparqlresult.h
 #endif
 
--- a/js/src/configure.in
+++ b/js/src/configure.in
@@ -2053,98 +2053,16 @@ if test "$ENABLE_ION"; then
 fi
 
 AC_SUBST(ENABLE_YARR_JIT)
 
 if test "$ENABLE_YARR_JIT"; then
     AC_DEFINE(ENABLE_YARR_JIT)
 fi
 
-dnl ========================================================
-dnl =
-dnl = Debugging Options
-dnl =
-dnl = These must come before MOZ_COMPILER_OPTS so that MOZ_COMPILER_OPTS
-dnl = sees any debug flags set by the user.
-dnl =
-dnl ========================================================
-MOZ_ARG_HEADER(Debugging)
-
-dnl ========================================================
-dnl = Debug info is ON by default.
-dnl ========================================================
-if test -z "$MOZ_DEBUG_FLAGS"; then
-  MOZ_DEBUG_FLAGS="-g"
-fi
-
-MOZ_ARG_ENABLE_STRING(debug,
-[  --enable-debug[=DBG]    Enable building with developer debug info
-                           (using compiler flags DBG)],
-[ if test "$enableval" != "no"; then
-    MOZ_DEBUG=1
-    if test -n "$enableval" -a "$enableval" != "yes"; then
-        MOZ_DEBUG_FLAGS=`echo $enableval | sed -e 's|\\\ | |g'`
-        _MOZ_DEBUG_FLAGS_SET=1
-    fi
-  else
-    MOZ_DEBUG=
-  fi ],
-  MOZ_DEBUG=)
-
-MOZ_DEBUG_ENABLE_DEFS="-DDEBUG -D_DEBUG -DTRACING"
-MOZ_ARG_WITH_STRING(debug-label,
-[  --with-debug-label=LABELS
-                          Define DEBUG_<value> for each comma-separated
-                          value given.],
-[ for option in `echo $withval | sed 's/,/ /g'`; do
-    MOZ_DEBUG_ENABLE_DEFS="$MOZ_DEBUG_ENABLE_DEFS -DDEBUG_${option}"
-done])
-
-MOZ_DEBUG_DISABLE_DEFS="-DNDEBUG -DTRIMMED"
-
-if test -n "$MOZ_DEBUG"; then
-    AC_MSG_CHECKING([for valid debug flags])
-    _SAVE_CFLAGS=$CFLAGS
-    CFLAGS="$CFLAGS $MOZ_DEBUG_FLAGS"
-    AC_TRY_COMPILE([#include <stdio.h>],
-        [printf("Hello World\n");],
-        _results=yes,
-        _results=no)
-    AC_MSG_RESULT([$_results])
-    if test "$_results" = "no"; then
-        AC_MSG_ERROR([These compiler flags are invalid: $MOZ_DEBUG_FLAGS])
-    fi
-    CFLAGS=$_SAVE_CFLAGS
-fi
-
-dnl ========================================================
-dnl = Enable generation of debug symbols
-dnl ========================================================
-MOZ_ARG_ENABLE_STRING(debug-symbols,
-[  --enable-debug-symbols[=DBG]
-                          Enable debugging symbols (using compiler flags DBG)],
-[ if test "$enableval" != "no"; then
-      MOZ_DEBUG_SYMBOLS=1
-      if test -n "$enableval" -a "$enableval" != "yes"; then
-          if test -z "$_MOZ_DEBUG_FLAGS_SET"; then
-              MOZ_DEBUG_FLAGS=`echo $enableval | sed -e 's|\\\ | |g'`
-          else
-              AC_MSG_ERROR([--enable-debug-symbols flags cannot be used with --enable-debug flags])
-          fi
-      fi
-  else
-      MOZ_DEBUG_SYMBOLS=
-  fi ],
-  MOZ_DEBUG_SYMBOLS=1)
-
-if test -n "$MOZ_DEBUG" -o -n "$MOZ_DEBUG_SYMBOLS"; then
-    AC_DEFINE(MOZ_DEBUG_SYMBOLS)
-    export MOZ_DEBUG_SYMBOLS
-fi
-
 MOZ_COMPILER_OPTS
 if test -z "$SKIP_COMPILER_CHECKS"; then
 dnl Checks for typedefs, structures, and compiler characteristics.
 dnl ========================================================
 AC_HEADER_STDC
 AC_C_CONST
 AC_TYPE_MODE_T
 AC_TYPE_OFF_T
rename from js/src/devtools/rootAnalysis/suppressedPoints.js
rename to js/src/devtools/rootAnalysis/CFG.js
--- a/js/src/devtools/rootAnalysis/suppressedPoints.js
+++ b/js/src/devtools/rootAnalysis/CFG.js
@@ -45,41 +45,110 @@ function isMatchingDestructor(constructo
 
     var destructExp = edge.PEdgeCallInstance.Exp;
     if (destructExp.Kind != "Var")
         return false;
 
     return sameVariable(constructExp.Variable, destructExp.Variable);
 }
 
+// Return all calls within the RAII scope of the constructor matched by
+// isConstructor()
 function allRAIIGuardedCallPoints(body, isConstructor)
 {
     if (!("PEdge" in body))
         return [];
 
     var points = [];
-    var successors = getSuccessors(body);
 
     for (var edge of body.PEdge) {
         if (edge.Kind != "Call")
             continue;
         var callee = edge.Exp[0];
         if (callee.Kind != "Var")
             continue;
         var variable = callee.Variable;
         assert(variable.Kind == "Func");
         if (!isConstructor(variable.Name[0]))
             continue;
         if (edge.PEdgeCallInstance.Exp.Kind != "Var")
             continue;
 
-        Array.prototype.push.apply(points, pointsInRAIIScope(body, edge, successors));
+        Array.prototype.push.apply(points, pointsInRAIIScope(body, edge));
     }
 
     return points;
 }
 
-// Compute the points within a function body where GC is suppressed.
-function computeSuppressedPoints(body)
+// Test whether the given edge is the constructor corresponding to the given
+// destructor edge
+function isMatchingConstructor(destructor, edge)
+{
+    if (edge.Kind != "Call")
+        return false;
+    var callee = edge.Exp[0];
+    if (callee.Kind != "Var")
+        return false;
+    var variable = callee.Variable;
+    if (variable.Kind != "Func")
+        return false;
+    var name = variable.Name[0];
+    var destructorName = destructor.Exp[0].Variable.Name[0];
+    var match = destructorName.match(/^(.*?::)~(\w+)\(/);
+    if (!match) {
+        printErr("Unhandled destructor syntax: " + destructorName);
+        return false;
+    }
+    var constructorSubstring = match[1] + match[2];
+    if (name.indexOf(constructorSubstring) == -1)
+        return false;
+
+    var destructExp = destructor.PEdgeCallInstance.Exp;
+    assert(destructExp.Kind == "Var");
+
+    var constructExp = edge.PEdgeCallInstance.Exp;
+    if (constructExp.Kind != "Var")
+        return false;
+
+    return sameVariable(constructExp.Variable, destructExp.Variable);
+}
+
+function findMatchingConstructor(destructorEdge, body)
 {
-    for (var [pbody, id] of allRAIIGuardedCallPoints(body, isSuppressConstructor))
-        pbody.suppressed[id] = true;
+    var worklist = [destructorEdge];
+    var predecessors = getPredecessors(body);
+    while(worklist.length > 0) {
+        var edge = worklist.pop();
+        if (isMatchingConstructor(destructorEdge, edge))
+            return edge;
+        if (edge.Index[0] in predecessors) {
+            for (var e of predecessors[edge.Index[0]])
+                worklist.push(e);
+        }
+    }
+    printErr("Could not find matching constructor!");
+    debugger;
 }
+
+function pointsInRAIIScope(body, constructorEdge) {
+    var seen = {};
+    var worklist = [constructorEdge.Index[1]];
+    var points = [];
+    while (worklist.length) {
+        var point = worklist.pop();
+        if (point in seen)
+            continue;
+        seen[point] = true;
+        points.push([body, point]);
+        var successors = getSuccessors(body);
+        if (!(point in successors))
+            continue;
+        for (var nedge of successors[point]) {
+            if (isMatchingDestructor(constructorEdge, nedge))
+                continue;
+            if (nedge.Kind == "Loop")
+                Array.prototype.push.apply(points, findAllPoints(nedge.BlockId));
+            worklist.push(nedge.Index[1]);
+        }
+    }
+
+    return points;
+}
--- a/js/src/devtools/rootAnalysis/analyze.py
+++ b/js/src/devtools/rootAnalysis/analyze.py
@@ -92,16 +92,17 @@ def generate_hazards(config, outfilename
     with open(outfilename, 'w') as output:
         command = ['cat'] + [ 'rootingHazards.%s' % (i+1,) for i in range(config['jobs']) ]
         print_command(command, outfile=outfilename)
         subprocess.call(command, stdout=output)
 
 JOBS = { 'dbs':
              (('%(ANALYSIS_SCRIPTDIR)s/run_complete',
                '--foreground',
+               '--no-logs',
                '--build-root=%(objdir)s',
                '--wrap-dir=%(sixgill)s/scripts/wrap_gcc',
                '--work-dir=work',
                '-b', '%(sixgill_bin)s',
                '--buildcommand=%(buildcommand)s',
                '.'),
               ()),
 
@@ -156,16 +157,17 @@ def run_job(name, config):
 
         command = list(cmdspec)
         outfile = 0
         for (i, name) in out_indexes(cmdspec):
             command[i] = '%s.tmp' % name
             temp_map[command[i]] = outfiles[outfile]
             outfile += 1
 
+        sys.stdout.flush()
         with open(temp, 'w') as output:
             subprocess.check_call(command, stdout=output, env=env(config))
         for (temp, final) in temp_map.items():
             try:
                 os.rename(temp, final)
             except OSError:
                 print("Error renaming %s -> %s" % (temp, final))
                 raise
--- a/js/src/devtools/rootAnalysis/analyzeRoots.js
+++ b/js/src/devtools/rootAnalysis/analyzeRoots.js
@@ -1,15 +1,15 @@
 /* -*- Mode: Javascript; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 
 "use strict";
 
 loadRelativeToScript('utility.js');
 loadRelativeToScript('annotations.js');
-loadRelativeToScript('suppressedPoints.js');
+loadRelativeToScript('CFG.js');
 
 var sourceRoot = (environment['SOURCE'] || '') + '/'
 
 var functionBodies;
 
 if (typeof scriptArgs[0] != 'string' || typeof scriptArgs[1] != 'string')
     throw "Usage: analyzeRoots.js <gcFunctions.lst> <gcEdges.txt> <suppressedFunctions.lst> <gcTypes.txt> [start end [tmpfile]]";
 
@@ -238,29 +238,16 @@ function edgeCanGC(edge)
         var fullFieldName = csuName + "." + field.Name[0];
         return fieldCallCannotGC(csuName, fullFieldName) ? null : fullFieldName;
     }
     assert(callee.Exp[0].Kind == "Var");
     var calleeName = callee.Exp[0].Variable.Name[0];
     return indirectCallCannotGC(functionName, calleeName) ? null : "*" + calleeName;
 }
 
-function computePredecessors(body)
-{
-    body.predecessors = [];
-    if (!("PEdge" in body))
-        return;
-    for (var edge of body.PEdge) {
-        var target = edge.Index[1];
-        if (!(target in body.predecessors))
-            body.predecessors[target] = [];
-        body.predecessors[target].push(edge);
-    }
-}
-
 function variableUseFollowsGC(suppressed, variable, worklist)
 {
     // Scan through all edges following an unrooted variable use, using an
     // explicit worklist. A worklist contains a following edge together with a
     // description of where one of its predecessors GC'd (if any).
 
     while (worklist.length) {
         var entry = worklist.pop();
@@ -568,15 +555,17 @@ var end = Math.min(minStream + each * ba
 for (var nameIndex = start; nameIndex <= end; nameIndex++) {
     var name = xdb.read_key(nameIndex);
     var functionName = name.readString();
     var data = xdb.read_entry(name);
     functionBodies = JSON.parse(data.readString());
 
     for (var body of functionBodies)
         body.suppressed = [];
-    for (var body of functionBodies)
-        computeSuppressedPoints(body);
+    for (var body of functionBodies) {
+        for (var [pbody, id] of allRAIIGuardedCallPoints(body, isSuppressConstructor))
+            pbody.suppressed[id] = true;
+    }
     processBodies(functionName);
 
     xdb.free_string(name);
     xdb.free_string(data);
 }
--- a/js/src/devtools/rootAnalysis/annotations.js
+++ b/js/src/devtools/rootAnalysis/annotations.js
@@ -61,20 +61,20 @@ var ignoreClasses = {
 // a function pointer field named FIELD.
 var ignoreCallees = {
     "js::Class.trace" : true,
     "js::Class.finalize" : true,
     "JSRuntime.destroyPrincipals" : true,
     "nsISupports.AddRef" : true,
     "nsISupports.Release" : true, // makes me a bit nervous; this is a bug but can happen
     "nsAXPCNativeCallContext.GetJSContext" : true,
-    "js::ion::MDefinition.op" : true, // macro generated virtuals just return a constant
-    "js::ion::MDefinition.opName" : true, // macro generated virtuals just return a constant
-    "js::ion::LInstruction.getDef" : true, // virtual but no implementation can GC
-    "js::ion::IonCache.kind" : true, // macro generated virtuals just return a constant
+    "js::jit::MDefinition.op" : true, // macro generated virtuals just return a constant
+    "js::jit::MDefinition.opName" : true, // macro generated virtuals just return a constant
+    "js::jit::LInstruction.getDef" : true, // virtual but no implementation can GC
+    "js::jit::IonCache.kind" : true, // macro generated virtuals just return a constant
     "icu_50::UObject.__deleting_dtor" : true, // destructors in ICU code can't cause GC
     "mozilla::CycleCollectedJSRuntime.DescribeCustomObjects" : true, // During tracing, cannot GC.
     "mozilla::CycleCollectedJSRuntime.NoteCustomGCThingXPCOMChildren" : true, // During tracing, cannot GC.
 };
 
 function fieldCallCannotGC(csu, fullfield)
 {
     if (csu in ignoreClasses)
@@ -100,16 +100,18 @@ function ignoreEdgeUse(edge, variable)
     if (edge.Kind == "Call") {
         var callee = edge.Exp[0];
         if (callee.Kind == "Var") {
             var name = callee.Variable.Name[0];
             if (/~Anchor/.test(name))
                 return true;
             if (/~DebugOnly/.test(name))
                 return true;
+            if (/~ScopedThreadSafeStringInspector/.test(name))
+                return true;
         }
     }
 
     return false;
 }
 
 function ignoreEdgeAddressTaken(edge)
 {
--- a/js/src/devtools/rootAnalysis/computeCallgraph.js
+++ b/js/src/devtools/rootAnalysis/computeCallgraph.js
@@ -1,15 +1,15 @@
 /* -*- Mode: Javascript; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 
 "use strict";
 
 loadRelativeToScript('utility.js');
 loadRelativeToScript('annotations.js');
-loadRelativeToScript('suppressedPoints.js');
+loadRelativeToScript('CFG.js');
 
 var subclasses = {};
 var superclasses = {};
 var classFunctions = {};
 
 function addClassEntry(index, name, other)
 {
     if (!(name in index)) {
@@ -225,18 +225,20 @@ var minStream = xdb.min_data_stream();
 var maxStream = xdb.max_data_stream();
 
 for (var nameIndex = minStream; nameIndex <= maxStream; nameIndex++) {
     var name = xdb.read_key(nameIndex);
     var data = xdb.read_entry(name);
     functionBodies = JSON.parse(data.readString());
     for (var body of functionBodies)
         body.suppressed = [];
-    for (var body of functionBodies)
-        computeSuppressedPoints(body);
+    for (var body of functionBodies) {
+        for (var [pbody, id] of allRAIIGuardedCallPoints(body, isSuppressConstructor))
+            pbody.suppressed[id] = true;
+    }
 
     seenCallees = {};
     seenSuppressedCallees = {};
 
     for (var body of functionBodies)
         processBody(name.readString(), body);
 
     xdb.free_string(name);
--- a/js/src/devtools/rootAnalysis/run_complete
+++ b/js/src/devtools/rootAnalysis/run_complete
@@ -22,16 +22,17 @@
 # machines) and watching a shared poll_file for jobs. if the output directory
 # for this script already exists then an incremental analysis will be performed
 # and the reports will only reflect the changes since the earlier run.
 
 use strict;
 use IO::Handle;
 use File::Basename qw(dirname);
 use Getopt::Long;
+use Cwd;
 
 #################################
 # environment specific settings #
 #################################
 
 my $WORKDIR;
 my $SIXGILL_BIN;
 
@@ -50,18 +51,20 @@ my $ann_file = "";
 # optional output directory to do a diff against.
 my $old_dir = "";
 
 # run in the foreground
 my $foreground;
 
 my $builder = "make -j4";
 
+my $suppress_logs;
 GetOptions("build-root|b=s" => \$build_dir,
            "poll-file=s" => \$poll_file,
+           "no-logs!" => \$suppress_logs,
            "work-dir=s" => \$WORKDIR,
            "sixgill-binaries|binaries|b=s" => \$SIXGILL_BIN,
            "wrap-dir=s" => \$wrap_dir,
            "annotations-file|annotations|a=s" => \$ann_file,
            "old-dir|old=s" => \$old_dir,
            "foreground!" => \$foreground,
            "buildcommand=s" => \$builder,
            )
@@ -98,16 +101,23 @@ sub clean_project {
     system("make clean");
 }
 
 # code to build the project from $build_dir.
 sub build_project {
     return system($builder) >> 8;
 }
 
+our %kill_on_exit;
+END {
+    for my $pid (keys %kill_on_exit) {
+        kill($pid);
+    }
+}
+
 # commands to start the various xgill binaries. timeouts can be specified
 # for the backend analyses here, and a memory limit can be specified for
 # xmanager if desired (and USE_COUNT_ALLOCATOR is defined in util/alloc.h).
 my $xmanager = "$SIXGILL_BIN/xmanager";
 my $xsource = "$SIXGILL_BIN/xsource";
 my $xmemlocal = "$SIXGILL_BIN/xmemlocal -timeout=20";
 my $xinfer = "$SIXGILL_BIN/xinfer -timeout=60";
 my $xcheck = "$SIXGILL_BIN/xcheck -timeout=30";
@@ -138,36 +148,37 @@ if (not $foreground) {
 
 # if the result directory does not already exist, mark for a clean build.
 my $do_clean = 0;
 if (not (-d $result_dir)) {
     $do_clean = 1;
     mkdir $result_dir;
 }
 
-open(OUT, ">> $result_dir/complete.log");
-OUT->autoflush(1);  # don't buffer writes to the main log.
+if (!$suppress_logs) {
+    my $log_file = "$result_dir/complete.log";
+    open(OUT, ">>", $log_file) or die "append to $log_file: $!";
+    OUT->autoflush(1);  # don't buffer writes to the main log.
 
-# redirect stdout and stderr to the log.
-STDOUT->fdopen(\*OUT, "w");
-STDERR->fdopen(\*OUT, "w");
+    # redirect stdout and stderr to the log.
+    STDOUT->fdopen(\*OUT, "w");
+    STDERR->fdopen(\*OUT, "w");
+}
 
 # pids to wait on before exiting. these are collating worker output.
 my @waitpids;
 
 chdir $result_dir;
 
 # to do a partial run, comment out the commands here you don't want to do.
 
 my $status = run_build();
 
 # end of run commands.
 
-close(OUT);
-
 for my $pid (@waitpids) {
     waitpid($pid, 0);
     $status ||= $? >> 8;
 }
 
 print "Exiting run_complete with status $status\n";
 exit $status;
 
@@ -192,30 +203,33 @@ sub run_build
     print "build started: ";
     print scalar(localtime());
     print "\n";
 
     # fork off a process to run the build.
     defined(my $pid = fork) or die;
 
     # log file for the manager.
-    my $log_file = "$result_dir/build_manager.log";
+    my $manager_log_file = "$result_dir/build_manager.log";
 
     if (!$pid) {
         # this is the child process, fork another process to run a manager.
         defined(my $pid = fork) or die;
-        exec("$xmanager -terminate-on-assert > $log_file 2>&1") if (!$pid);
+        exec("$xmanager -terminate-on-assert > $manager_log_file 2>&1") if (!$pid);
+        $kill_on_exit{$pid} = 1;
 
-        # open new streams to redirect stdout and stderr.
-        open(LOGOUT, "> $result_dir/build.log");
-        open(LOGERR, "> $result_dir/build_err.log");
-        STDOUT->fdopen(\*LOGOUT, "w");
-        STDERR->fdopen(\*LOGERR, "w");
+        if (!$suppress_logs) {
+            # open new streams to redirect stdout and stderr.
+            open(LOGOUT, "> $result_dir/build.log");
+            open(LOGERR, "> $result_dir/build_err.log");
+            STDOUT->fdopen(\*LOGOUT, "w");
+            STDERR->fdopen(\*LOGERR, "w");
+        }
 
-        my $address = get_manager_address($log_file);
+        my $address = get_manager_address($manager_log_file);
 
         # write the configuration file for the wrapper script.
         my $config_file = "$WORKDIR/xgill.config";
         open(CONFIG, ">", $config_file) or die "create $config_file: $!";
         print CONFIG "$prefix_dir\n";
         print CONFIG Cwd::abs_path("$result_dir/build_xgill.log")."\n";
         print CONFIG "$address\n";
         print CONFIG "-fplugin-arg-xgill-annfile=$ann_file\n"
@@ -234,21 +248,23 @@ sub run_build
         my $exit_status = build_project();
 
         # signal the manager that it's over.
         system("$xsource -remote=$address -end-manager");
 
         # wait for the manager to clean up and terminate.
         print "Waiting for manager to finish (build status $exit_status)...\n";
         waitpid($pid, 0);
+        my $manager_status = $?;
+        delete $kill_on_exit{$pid};
 
         # build is finished, the complete run can resume.
         # return value only useful if --foreground
-        print "Exiting with status " . ($? || $exit_status) . "\n";
-        exit($? || $exit_status);
+        print "Exiting with status " . ($manager_status || $exit_status) . "\n";
+        exit($manager_status || $exit_status);
     }
 
     # this is the complete process, wait for the build to finish.
     waitpid($pid, 0);
     my $status = $? >> 8;
     print "build finished (status $status): ";
     print scalar(localtime());
     print "\n";
new file mode 100644
--- /dev/null
+++ b/js/src/jit-test/tests/auto-regress/bug909441.js
@@ -0,0 +1,20 @@
+// |jit-test| error: too much recursion
+function f(code) {
+    try {
+        g = Function(code)
+    } catch (e) {}
+    g()
+}
+f("\
+    Object.defineProperty(this,\"x\",{\
+        get: function(){\
+            evaluate(\"Array(x)\",{\
+                newContext:true,\
+                catchTermination:(function(){})\
+            })\
+        }\
+    })\
+");
+f("x");
+f(")");
+f("x");
new file mode 100644
--- /dev/null
+++ b/js/src/jit-test/tests/debug/Script-isInCatchScope.js
@@ -0,0 +1,64 @@
+// Test if isInCatchScope properly detects catch blocks.
+
+let g = newGlobal('new-compartment');
+let dbg = new Debugger(g);
+
+function test(string, mustBeCaught) {
+    let index = 0;
+    dbg.onExceptionUnwind = function (frame) {
+        let willBeCaught = false;
+        do {
+            if (frame.script.isInCatchScope(frame.offset)) {
+                willBeCaught = true;
+                break;
+            }
+            frame = frame.older;
+        } while (frame != null);
+        assertEq(willBeCaught, mustBeCaught[index++]);
+    };
+
+    try {
+        g.eval(string);
+    } catch (ex) {}
+    assertEq(index, mustBeCaught.length);
+}
+
+// Should correctly detect catch blocks
+test("throw new Error();", [false]);
+test("try { throw new Error(); } catch (e) {}", [true]);
+test("try { throw new Error(); } finally {}", [false, false]);
+test("try { throw new Error(); } catch (e) {} finally {}", [true]);
+
+// Source of the exception shouldn't matter
+test("(null)();", [false]);
+test("try { (null)(); } catch (e) {}", [true]);
+test("try { (null)(); } finally {}", [false, false]);
+test("try { (null)(); } catch (e) {} finally {}", [true]);
+
+// Should correctly detect catch blocks in functions
+test("function f() { throw new Error(); } f();", [false, false]);
+test("function f() { try { throw new Error(); } catch (e) {} } f();", [true]);
+test("function f() { try { throw new Error(); } finally {} } f();", [false, false, false]);
+test("function f() { try { throw new Error(); } catch (e) {} finally {} } f();", [true]);
+
+// Should correctly detect catch blocks in evals
+test("eval('throw new Error();')", [false, false]);
+test("eval('try { throw new Error(); } catch (e) {}');", [true]);
+test("eval('try { throw new Error(); } finally {}');", [false, false, false]);
+test("eval('try { throw new Error(); } catch (e) {} finally {}');", [true]);
+
+// Should correctly detect rethrows
+test("try { throw new Error(); } catch (e) { throw e; }", [true, false]);
+test("try { try { throw new Error(); } catch (e) { throw e; } } catch (e) {}", [true, true]);
+test("try { try { throw new Error(); } finally {} } catch (e) {}", [true, true]);
+test("function f() { try { throw new Error(); } catch (e) { throw e; } } f();", [true, false, false]);
+test("function f() { try { try { throw new Error(); } catch (e) { throw e; } } catch (e) {} } f();", [true, true]);
+test("function f() { try { try { throw new Error(); } finally {} } catch (e) {} } f();", [true, true]);
+test("eval('try { throw new Error(); } catch (e) { throw e; }')", [true, false, false]);
+test("eval('try { try { throw new Error(); } catch (e) { throw e; } } catch (e) {}')", [true, true]);
+
+// Should correctly detect catch blocks across frame boundaries
+test("function f() { throw new Error(); } try { f(); } catch (e) {}", [true, true]);
+test("function f() { throw new Error(); } try { f(); } catch (e) { throw e; }", [true, true, false]);
+test("try { eval('throw new Error()'); } catch (e) {}", [true, true]);
+test("try { eval('throw new Error()'); } catch (e) { throw e; }", [true, true, false]);
new file mode 100644
--- /dev/null
+++ b/js/src/jit-test/tests/ion/bug908867.js
@@ -0,0 +1,39 @@
+x = ParallelArray()
+y = x.shape
+Object.defineProperty(this, "z", {
+    get: function() {
+        return x.flatten()
+    }
+})
+Object.defineProperty(y, 5, {
+    value: this
+});
+y[8] = z
+valueOf = (function() {
+    function f() {
+        (.9 % 1) > f
+    }
+    return f
+})(this, {})
+x.shape.join()
+
+
+assertArraySeqParResultsEq(range(0, 1024), "filter", function(e, i) { return (i % (1.1)) != 0; });
+function range(n, m) {
+  var result = [];
+  for (var i = n; i < m; i++)
+    result.push(i);
+  return result;
+}
+function assertArraySeqParResultsEq(arr, op, func) {
+  arr[op].apply(arr, [func]);
+}
+
+
+function foo(v) {
+  if (v < -200) return 0;
+  if (v > 200) return 0;
+  return v % 1;
+}
+assertEq(foo(0.9), 0.9);
+assertEq(foo(0.9), 0.9);
--- a/js/src/jit/AsmJS.cpp
+++ b/js/src/jit/AsmJS.cpp
@@ -39,17 +39,17 @@ using namespace js::jit;
 
 using mozilla::AddToHash;
 using mozilla::ArrayLength;
 using mozilla::DebugOnly;
 using mozilla::HashGeneric;
 using mozilla::IsNaN;
 using mozilla::IsNegativeZero;
 using mozilla::Maybe;
-using mozilla::Move;
+using mozilla::OldMove;
 using mozilla::MoveRef;
 
 static const size_t LIFO_ALLOC_PRIMARY_CHUNK_SIZE = 1 << 12;
 
 /*****************************************************************************/
 // ParseNode utilities
 
 static inline ParseNode *
@@ -659,31 +659,31 @@ class Signature
   public:
     Signature(ExclusiveContext *cx)
       : argTypes_(cx) {}
     Signature(ExclusiveContext *cx, RetType retType)
       : argTypes_(cx), retType_(retType) {}
     Signature(MoveRef<VarTypeVector> argTypes, RetType retType)
       : argTypes_(argTypes), retType_(retType) {}
     Signature(MoveRef<Signature> rhs)
-      : argTypes_(Move(rhs->argTypes_)), retType_(rhs->retType_) {}
+      : argTypes_(OldMove(rhs->argTypes_)), retType_(rhs->retType_) {}
 
     bool copy(const Signature &rhs) {
         if (!argTypes_.resize(rhs.argTypes_.length()))
             return false;
         for (unsigned i = 0; i < argTypes_.length(); i++)
             argTypes_[i] = rhs.argTypes_[i];
         retType_ = rhs.retType_;
         return true;
     }
 
     bool appendArg(VarType type) { return argTypes_.append(type); }
     VarType arg(unsigned i) const { return argTypes_[i]; }
     const VarTypeVector &args() const { return argTypes_; }
-    MoveRef<VarTypeVector> extractArgs() { return Move(argTypes_); }
+    MoveRef<VarTypeVector> extractArgs() { return OldMove(argTypes_); }
 
     RetType retType() const { return retType_; }
 };
 
 static
 bool operator==(const Signature &lhs, const Signature &rhs)
 {
     if (lhs.retType() != rhs.retType())
@@ -1072,18 +1072,18 @@ class MOZ_STACK_CLASS ModuleCompiler
         FuncPtrVector elems_;
 
       public:
         FuncPtrTable(ExclusiveContext *cx, MoveRef<Signature> sig, uint32_t mask, uint32_t gdo)
           : sig_(sig), mask_(mask), globalDataOffset_(gdo), elems_(cx)
         {}
 
         FuncPtrTable(MoveRef<FuncPtrTable> rhs)
-          : sig_(Move(rhs->sig_)), mask_(rhs->mask_), globalDataOffset_(rhs->globalDataOffset_),
-            elems_(Move(rhs->elems_))
+          : sig_(OldMove(rhs->sig_)), mask_(rhs->mask_), globalDataOffset_(rhs->globalDataOffset_),
+            elems_(OldMove(rhs->elems_))
         {}
 
         Signature &sig() { return sig_; }
         const Signature &sig() const { return sig_; }
         unsigned mask() const { return mask_; }
         unsigned globalDataOffset() const { return globalDataOffset_; }
 
         void initElems(MoveRef<FuncPtrVector> elems) { elems_ = elems; JS_ASSERT(!elems_.empty()); }
@@ -1097,17 +1097,17 @@ class MOZ_STACK_CLASS ModuleCompiler
     {
         PropertyName *name_;
         Signature sig_;
 
       public:
         ExitDescriptor(PropertyName *name, MoveRef<Signature> sig)
           : name_(name), sig_(sig) {}
         ExitDescriptor(MoveRef<ExitDescriptor> rhs)
-          : name_(rhs->name_), sig_(Move(rhs->sig_))
+          : name_(rhs->name_), sig_(OldMove(rhs->sig_))
         {}
         const Signature &sig() const {
             return sig_;
         }
 
         // ExitDescriptor is a HashPolicy:
         typedef ExitDescriptor Lookup;
         static HashNumber hash(const ExitDescriptor &d) {
@@ -1396,17 +1396,17 @@ class MOZ_STACK_CLASS ModuleCompiler
             return false;
         global->u.funcPtrTableIndex_ = funcPtrTables_.length();
         if (!globals_.putNew(name, global))
             return false;
         uint32_t globalDataOffset;
         if (!module_->addFuncPtrTable(/* numElems = */ mask + 1, &globalDataOffset))
             return false;
         FuncPtrTable tmpTable(cx_, sig, mask, globalDataOffset);
-        if (!funcPtrTables_.append(Move(tmpTable)))
+        if (!funcPtrTables_.append(OldMove(tmpTable)))
             return false;
         *table = &funcPtrTables_.back();
         return true;
     }
     bool addFFI(PropertyName *varName, PropertyName *field) {
         Global *global = moduleLifo_.new_<Global>(Global::FFI);
         if (!global)
             return false;
@@ -1447,28 +1447,28 @@ class MOZ_STACK_CLASS ModuleCompiler
         AsmJSModule::ArgCoercionVector argCoercions;
         const VarTypeVector &args = func->sig().args();
         if (!argCoercions.resize(args.length()))
             return false;
         for (unsigned i = 0; i < args.length(); i++)
             argCoercions[i] = args[i].toCoercion();
         AsmJSModule::ReturnType retType = func->sig().retType().toModuleReturnType();
         return module_->addExportedFunction(func->name(), maybeFieldName,
-                                            Move(argCoercions), retType);
+                                            OldMove(argCoercions), retType);
     }
     bool addExit(unsigned ffiIndex, PropertyName *name, MoveRef<Signature> sig, unsigned *exitIndex) {
         ExitDescriptor exitDescriptor(name, sig);
         ExitMap::AddPtr p = exits_.lookupForAdd(exitDescriptor);
         if (p) {
             *exitIndex = p->value;
             return true;
         }
         if (!module_->addExit(ffiIndex, exitIndex))
             return false;
-        return exits_.add(p, Move(exitDescriptor), *exitIndex);
+        return exits_.add(p, OldMove(exitDescriptor), *exitIndex);
     }
     bool addGlobalAccess(AsmJSGlobalAccess access) {
         return globalAccesses_.append(access);
     }
 
     bool collectAccesses(MIRGenerator &gen) {
         if (!module_->addHeapAccesses(gen.heapAccesses()))
             return false;
@@ -2503,17 +2503,17 @@ class FunctionCompiler
     template <class Key, class Map>
     bool addBreakOrContinue(Key key, Map *map)
     {
         if (!curBlock_)
             return true;
         typename Map::AddPtr p = map->lookupForAdd(key);
         if (!p) {
             BlockVector empty(m().cx());
-            if (!map->add(p, key, Move(empty)))
+            if (!map->add(p, key, OldMove(empty)))
                 return false;
         }
         if (!p->value.append(curBlock_))
             return false;
         curBlock_ = NULL;
         return true;
     }
 
@@ -3380,17 +3380,17 @@ CheckInternalCall(FunctionCompiler &f, P
                   RetType retType, MDefinition **def, Type *type)
 {
     FunctionCompiler::Call call(f, retType);
 
     if (!CheckCallArgs(f, callNode, CheckIsVarType, &call))
         return false;
 
     ModuleCompiler::Func *callee;
-    if (!CheckFunctionSignature(f.m(), callNode, Move(call.sig()), calleeName, &callee))
+    if (!CheckFunctionSignature(f.m(), callNode, OldMove(call.sig()), calleeName, &callee))
         return false;
 
     if (!f.internalCall(*callee, call, def))
         return false;
 
     *type = retType.toType();
     return true;
 }
@@ -3456,17 +3456,17 @@ CheckFuncPtrCall(FunctionCompiler &f, Pa
         return f.failf(indexNode, "%s is not a subtype of intish", indexType.toChars());
 
     FunctionCompiler::Call call(f, retType);
 
     if (!CheckCallArgs(f, callNode, CheckIsVarType, &call))
         return false;
 
     ModuleCompiler::FuncPtrTable *table;
-    if (!CheckFuncPtrTableAgainstExisting(f.m(), tableNode, name, Move(call.sig()), mask, &table))
+    if (!CheckFuncPtrTableAgainstExisting(f.m(), tableNode, name, OldMove(call.sig()), mask, &table))
         return false;
 
     if (!f.funcPtrCall(*table, indexDef, call, def))
         return false;
 
     *type = retType.toType();
     return true;
 }
@@ -3485,17 +3485,17 @@ CheckFFICall(FunctionCompiler &f, ParseN
 {
     PropertyName *calleeName = CallCallee(callNode)->name();
 
     FunctionCompiler::Call call(f, retType);
     if (!CheckCallArgs(f, callNode, CheckIsExternType, &call))
         return false;
 
     unsigned exitIndex;
-    if (!f.m().addExit(ffiIndex, calleeName, Move(call.sig()), &exitIndex))
+    if (!f.m().addExit(ffiIndex, calleeName, OldMove(call.sig()), &exitIndex))
         return false;
 
     if (!f.ffiCall(exitIndex, call, retType.toMIRType(), def))
         return false;
 
     *type = retType.toType();
     return true;
 }
@@ -4669,19 +4669,19 @@ CheckFunction(ModuleCompiler &m, LifoAll
 
     RetType retType;
     if (!CheckFinalReturn(f, lastNonEmptyStmt, &retType))
         return false;
 
     if (!CheckReturnType(f, lastNonEmptyStmt, retType))
         return false;
 
-    Signature sig(Move(argTypes), retType);
+    Signature sig(OldMove(argTypes), retType);
     ModuleCompiler::Func *func;
-    if (!CheckFunctionSignature(m, fn, Move(sig), FunctionName(fn), &func))
+    if (!CheckFunctionSignature(m, fn, OldMove(sig), FunctionName(fn), &func))
         return false;
 
     if (func->defined())
         return m.failName(fn, "function '%s' already defined", FunctionName(fn));
 
     func->define(fn->pn_pos.begin);
     func->accumulateCompileTime((PRMJ_Now() - before) / PRMJ_USEC_PER_MSEC);
 
@@ -5052,20 +5052,20 @@ CheckFuncPtrTable(ModuleCompiler &m, Par
             return false;
     }
 
     Signature sig(m.cx());
     if (!sig.copy(*firstSig))
         return false;
 
     ModuleCompiler::FuncPtrTable *table;
-    if (!CheckFuncPtrTableAgainstExisting(m, var, var->name(), Move(sig), mask, &table))
+    if (!CheckFuncPtrTableAgainstExisting(m, var, var->name(), OldMove(sig), mask, &table))
         return false;
 
-    table->initElems(Move(elems));
+    table->initElems(OldMove(elems));
     return true;
 }
 
 static bool
 CheckFuncPtrTables(ModuleCompiler &m)
 {
     while (true) {
         ParseNode *varStmt;
--- a/js/src/jit/AsmJSModule.h
+++ b/js/src/jit/AsmJSModule.h
@@ -223,17 +223,17 @@ class AsmJSModule
             if (maybeFieldName_)
                 MarkStringUnbarriered(trc, &maybeFieldName_, "asm.js export field");
         }
 
       public:
         ExportedFunction(mozilla::MoveRef<ExportedFunction> rhs) {
             name_ = rhs->name_;
             maybeFieldName_ = rhs->maybeFieldName_;
-            argCoercions_ = mozilla::Move(rhs->argCoercions_);
+            argCoercions_ = mozilla::OldMove(rhs->argCoercions_);
             pod = rhs->pod;
         }
 
         void initCodeOffset(unsigned off) {
             JS_ASSERT(pod.codeOffset_ == UINT32_MAX);
             pod.codeOffset_ = off;
         }
 
@@ -283,22 +283,22 @@ class AsmJSModule
 
 #if defined(JS_ION_PERF)
     struct ProfiledBlocksFunction : public ProfiledFunction
     {
         jit::PerfSpewer::BasicBlocksVector blocks;
 
         ProfiledBlocksFunction(JSAtom *name, unsigned start, unsigned end,
                                jit::PerfSpewer::BasicBlocksVector &blocksVector)
-          : ProfiledFunction(name, start, end), blocks(mozilla::Move(blocksVector))
+          : ProfiledFunction(name, start, end), blocks(mozilla::OldMove(blocksVector))
         { }
 
         ProfiledBlocksFunction(const ProfiledBlocksFunction &copy)
           : ProfiledFunction(copy.name, copy.startCodeOffset, copy.endCodeOffset),
-            blocks(mozilla::Move(copy.blocks))
+            blocks(mozilla::OldMove(copy.blocks))
         { }
     };
 #endif
 
   private:
     typedef Vector<ExportedFunction, 0, SystemAllocPolicy> ExportedFunctionVector;
     typedef Vector<Global, 0, SystemAllocPolicy> GlobalVector;
     typedef Vector<Exit, 0, SystemAllocPolicy> ExitVector;
@@ -452,17 +452,17 @@ class AsmJSModule
         return functionCounts_.append(counts);
     }
 
     bool addExportedFunction(PropertyName *name, PropertyName *maybeFieldName,
                              mozilla::MoveRef<ArgCoercionVector> argCoercions,
                              ReturnType returnType)
     {
         ExportedFunction func(name, maybeFieldName, argCoercions, returnType);
-        return exports_.append(mozilla::Move(func));
+        return exports_.append(mozilla::OldMove(func));
     }
     unsigned numExportedFunctions() const {
         return exports_.length();
     }
     const ExportedFunction &exportedFunction(unsigned i) const {
         return exports_[i];
     }
     ExportedFunction &exportedFunction(unsigned i) {
--- a/js/src/jit/RangeAnalysis.cpp
+++ b/js/src/jit/RangeAnalysis.cpp
@@ -1070,17 +1070,23 @@ MMod::computeRange()
 
     // Math.abs(lhs % rhs) == Math.abs(lhs) % Math.abs(rhs).
     // First, the absolute value of the result will always be less than the
     // absolute value of rhs. (And if rhs is zero, the result is NaN).
     int64_t a = Abs<int64_t>(rhs.lower());
     int64_t b = Abs<int64_t>(rhs.upper());
     if (a == 0 && b == 0)
         return;
-    int64_t rhsAbsBound = Max(a-1, b-1);
+    int64_t rhsAbsBound = Max(a, b);
+
+    // If the value is known to be integer, less-than abs(rhs) is equivalent
+    // to less-than-or-equal abs(rhs)-1. This is important for being able to
+    // say that the result of x%256 is an 8-bit unsigned number.
+    if (!lhs.isDecimal() && !rhs.isDecimal())
+        --rhsAbsBound;
 
     // Next, the absolute value of the result will never be greater than the
     // absolute value of lhs.
     int64_t lhsAbsBound = Max(Abs<int64_t>(lhs.lower()), Abs<int64_t>(lhs.upper()));
 
     // This gives us two upper bounds, so we can take the best one.
     int64_t absBound = Min(lhsAbsBound, rhsAbsBound);
 
--- a/js/src/jsmemorymetrics.cpp
+++ b/js/src/jsmemorymetrics.cpp
@@ -20,17 +20,17 @@
 #include "vm/Runtime.h"
 #include "vm/Shape.h"
 #include "vm/String.h"
 #include "vm/WrapperObject.h"
 
 #include "vm/ObjectImpl-inl.h"
 
 using mozilla::DebugOnly;
-using mozilla::Move;
+using mozilla::OldMove;
 using mozilla::MoveRef;
 using mozilla::PodEqual;
 
 using namespace js;
 
 using JS::RuntimeStats;
 using JS::ObjectPrivateVisitor;
 using JS::ZoneStats;
@@ -434,17 +434,17 @@ FindNotableStrings(ZoneStats &zStats)
         StringInfo &info = r.front().value;
 
         // If this string is too small, or if we can't grow the notableStrings
         // vector, skip this string.
         if (info.totalSizeOf() < NotableStringInfo::notableSize() ||
             !zStats.notableStrings.growBy(1))
             continue;
 
-        zStats.notableStrings.back() = Move(NotableStringInfo(str, info));
+        zStats.notableStrings.back() = OldMove(NotableStringInfo(str, info));
 
         // We're moving this string from a non-notable to a notable bucket, so
         // subtract it out of the non-notable tallies.
         MOZ_ASSERT(zStats.gcHeapStringsShort >= info.sizeOfShortStringGCThings);
         MOZ_ASSERT(zStats.gcHeapStringsNormal >= info.sizeOfNormalStringGCThings);
         MOZ_ASSERT(zStats.stringCharsNonNotable >= info.sizeOfAllStringChars);
         zStats.gcHeapStringsShort -= info.sizeOfShortStringGCThings;
         zStats.gcHeapStringsNormal -= info.sizeOfNormalStringGCThings;
--- a/js/src/shell/jsheaptools.cpp
+++ b/js/src/shell/jsheaptools.cpp
@@ -18,17 +18,17 @@
 #include "jsobj.h"
 #include "jsprf.h"
 #include "jsutil.h"
 
 #include "jsobjinlines.h"
 
 using namespace js;
 
-using mozilla::Move;
+using mozilla::OldMove;
 using mozilla::MoveRef;
 
 #ifdef DEBUG
 
 
 /*** class HeapReverser **************************************************************************/
 
 /*
@@ -72,17 +72,17 @@ class HeapReverser : public JSTracer, pu
           : kind(kind), incoming(), marked(false) { }
 
         /*
          * Move constructor and move assignment. These allow us to store our
          * incoming edge Vector in the hash table: Vectors support moves, but
          * not assignments or copy construction.
          */
         Node(MoveRef<Node> rhs)
-          : kind(rhs->kind), incoming(Move(rhs->incoming)), marked(rhs->marked) { }
+          : kind(rhs->kind), incoming(OldMove(rhs->incoming)), marked(rhs->marked) { }
         Node &operator=(MoveRef<Node> rhs) {
             this->~Node();
             new(this) Node(rhs);
             return *this;
         }
 
         void trace(JSTracer *trc) {
             for (Edge *e = incoming.begin(); e != incoming.end(); e++)
@@ -268,26 +268,26 @@ HeapReverser::traverseEdge(void *cell, J
     if (!a) {
         /*
          * We've never visited this cell before. Add it to the map (thus
          * marking it as visited), and put it on the work stack, to be
          * visited from the main loop.
          */
         Node n(kind);
         uint32_t generation = map.generation();
-        if (!map.add(a, cell, Move(n)) ||
+        if (!map.add(a, cell, OldMove(n)) ||
             !work.append(Child(cell, kind)))
             return false;
         /* If the map has been resized, re-check the pointer. */
         if (map.generation() != generation)
             a = map.lookupForAdd(cell);
     }
 
     /* Add this edge to the reversed map. */
-    return a->value.incoming.append(Move(e));
+    return a->value.incoming.append(OldMove(e));
 }
 
 bool
 HeapReverser::reverseHeap()
 {
     traversalStatus = true;
 
     /* Prime the work stack with the roots of collection. */
--- a/js/src/vm/Debugger.cpp
+++ b/js/src/vm/Debugger.cpp