Merge mozilla-central and ux
authorGijs Kruitbosch <gijskruitbosch@gmail.com>
Tue, 24 Sep 2013 14:55:03 +0200
changeset 170353 ea4363ac93eaf1f7e2a0920f4916ce699a2d28e2
parent 162187 1fda74e33e0610130db0e14f8812933f69143d81 (diff)
parent 170352 92b0f1d2249cf2f67c247d387057b5d25549f7ff (current diff)
child 170354 f74f64b2e35b1d266fa905014c5e2ded49b40aa5
push id3224
push userlsblakk@mozilla.com
push dateTue, 04 Feb 2014 01:06:49 +0000
treeherdermozilla-beta@60c04d0987f1 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone27.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Merge mozilla-central and ux
browser/base/content/browser-appmenu.inc
browser/base/content/browser.js
browser/base/content/test/general/Makefile.in
browser/base/content/test/general/browser_addon_bar.js
browser/base/content/test/general/browser_addon_bar_aomlistener.js
browser/base/content/test/general/browser_addon_bar_close_button.js
browser/base/content/test/general/browser_addon_bar_shortcut.js
browser/base/content/test/general/browser_bug598923.js
browser/base/content/test/general/browser_bug599325.js
browser/base/content/test/general/browser_bug616836.js
browser/base/content/test/general/browser_customize.js
browser/base/content/test/general/browser_disablechrome.js
browser/base/content/test/general/disablechrome.html
browser/base/content/test/general/head.js
browser/themes/linux/places/pageStarred.png
browser/themes/linux/places/starPage.png
browser/themes/osx/Toolbar-lion.png
browser/themes/osx/Toolbar-lion@2x.png
browser/themes/osx/social/share-button-active.png
browser/themes/osx/social/share-button-active@2x.png
browser/themes/osx/social/share-button.png
browser/themes/osx/social/share-button@2x.png
browser/themes/osx/tabbrowser/tab-bottom-hover-active.png
browser/themes/osx/tabbrowser/tab-bottom-normal-active.png
browser/themes/osx/tabbrowser/tab-bottom-selected-active.png
browser/themes/osx/tabbrowser/tab-top-hover-active.png
browser/themes/osx/tabbrowser/tab-top-hover-active@2x.png
browser/themes/osx/tabbrowser/tab-top-normal-active.png
browser/themes/osx/tabbrowser/tab-top-normal-active@2x.png
browser/themes/osx/tabbrowser/tab-top-selected-active.png
browser/themes/osx/tabbrowser/tab-top-selected-active@2x.png
browser/themes/windows/appmenu-dropmarker.png
browser/themes/windows/appmenu-icons.png
browser/themes/windows/jar.mn
browser/themes/windows/places/editBookmark.png
browser/themes/windows/privatebrowsing-dark.png
browser/themes/windows/privatebrowsing-light.png
browser/themes/windows/social/share-button-active.png
browser/themes/windows/social/share-button.png
modules/libpref/src/init/all.js
toolkit/themes/linux/global/icons/notloading_16.png
toolkit/themes/osx/global/icons/notloading_16.png
toolkit/themes/windows/global/icons/notloading_16.png
widget/cocoa/nsChildView.h
widget/cocoa/nsChildView.mm
--- a/accessible/src/atk/AccessibleWrap.cpp
+++ b/accessible/src/atk/AccessibleWrap.cpp
@@ -18,16 +18,17 @@
 #include "nsMaiHyperlink.h"
 #include "nsString.h"
 #include "nsAutoPtr.h"
 #include "prprf.h"
 #include "nsStateMap.h"
 #include "Relation.h"
 #include "RootAccessible.h"
 #include "States.h"
+#include "nsISimpleEnumerator.h"
 
 #include "mozilla/Util.h"
 #include "nsXPCOMStrings.h"
 #include "nsComponentManagerUtils.h"
 #include "nsIPersistentProperties2.h"
 
 using namespace mozilla;
 using namespace mozilla::a11y;
--- a/accessible/src/base/TextAttrs.cpp
+++ b/accessible/src/base/TextAttrs.cpp
@@ -9,16 +9,17 @@
 #include "nsAccUtils.h"
 #include "nsCoreUtils.h"
 #include "StyleInfo.h"
 
 #include "gfxFont.h"
 #include "nsFontMetrics.h"
 #include "nsLayoutUtils.h"
 #include "HyperTextAccessible.h"
+#include "mozilla/AppUnits.h"
 
 using namespace mozilla;
 using namespace mozilla::a11y;
 
 ////////////////////////////////////////////////////////////////////////////////
 // TextAttrsMgr
 ////////////////////////////////////////////////////////////////////////////////
 
@@ -499,17 +500,17 @@ TextAttrsMgr::FontSizeTextAttr::
   //
   // Note: according to IA2, "The conversion doesn't have to be exact.
   // The intent is to give the user a feel for the size of the text."
   //
   // ATK does not specify a unit and will likely follow IA2 here.
   //
   // XXX todo: consider sharing this code with layout module? (bug 474621)
   float px =
-    NSAppUnitsToFloatPixels(aValue, nsDeviceContext::AppUnitsPerCSSPixel());
+    NSAppUnitsToFloatPixels(aValue, mozilla::AppUnitsPerCSSPixel());
   // Each pt is 4/3 of a CSS pixel.
   int pts = NS_lround(px*3/4);
 
   nsAutoString value;
   value.AppendInt(pts);
   value.Append(NS_LITERAL_STRING("pt"));
 
   nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::font_size, value);
--- a/accessible/src/generic/Accessible.h
+++ b/accessible/src/generic/Accessible.h
@@ -13,17 +13,17 @@
 
 #include "nsIAccessible.h"
 #include "nsIAccessibleHyperLink.h"
 #include "nsIAccessibleSelectable.h"
 #include "nsIAccessibleValue.h"
 #include "nsIAccessibleStates.h"
 
 #include "nsIContent.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 #include "nsTArray.h"
 #include "nsRefPtrHashtable.h"
 
 struct nsRoleMapEntry;
 
 struct nsRect;
 class nsIFrame;
 class nsIAtom;
--- a/accessible/src/generic/DocAccessible.cpp
+++ b/accessible/src/generic/DocAccessible.cpp
@@ -69,20 +69,21 @@ static const uint32_t kRelationAttrsLen 
 
 ////////////////////////////////////////////////////////////////////////////////
 // Constructor/desctructor
 
 DocAccessible::
   DocAccessible(nsIDocument* aDocument, nsIContent* aRootContent,
                   nsIPresShell* aPresShell) :
   HyperTextAccessibleWrap(aRootContent, this),
-  mDocumentNode(aDocument), mScrollPositionChangedTicks(0),
   // XXX aaronl should we use an algorithm for the initial cache size?
   mAccessibleCache(kDefaultCacheSize),
   mNodeToAccessibleMap(kDefaultCacheSize),
+  mDocumentNode(aDocument),
+  mScrollPositionChangedTicks(0),
   mLoadState(eTreeConstructionPending), mDocFlags(0), mLoadEventType(0),
   mVirtualCursor(nullptr),
   mPresShell(aPresShell)
 {
   mGenericTypes |= eDocument;
   mStateFlags |= eNotNodeMapEntry;
 
   MOZ_ASSERT(mPresShell, "should have been given a pres shell");
--- a/accessible/src/jsat/AccessFu.jsm
+++ b/accessible/src/jsat/AccessFu.jsm
@@ -493,120 +493,57 @@ var Output = {
 
       return braille;
     }
   },
 
   speechHelper: {
     EARCONS: ['chrome://global/content/accessibility/tick.wav'],
 
-    delayedActions: [],
-
-    earconsToLoad: -1, // -1: not inited, 1 or more: initing, 0: inited
-
     earconBuffers: {},
 
-    webaudioEnabled: false,
+    inited: false,
 
     webspeechEnabled: false,
 
-    doDelayedActionsIfLoaded: function doDelayedActionsIfLoaded(aToLoadCount) {
-      if (aToLoadCount === 0) {
-        this.outputActions(this.delayedActions);
-        this.delayedActions = [];
-        return true;
-      }
-
-      return false;
-    },
-
     init: function init() {
-      if (this.earconsToLoad === 0) {
-        // Already inited.
-        return;
-      }
-
       let window = Utils.win;
-      this.webaudioEnabled = !!window.AudioContext;
       this.webspeechEnabled = !!window.speechSynthesis;
 
-      this.earconsToLoad = this.webaudioEnabled ? this.EARCONS.length : 0;
-
-      if (this.doDelayedActionsIfLoaded(this.earconsToLoad)) {
-        // Nothing to load
-        return;
+      for (let earcon of this.EARCONS) {
+        let earconName = /.*\/(.*)\..*$/.exec(earcon)[1];
+        this.earconBuffers[earconName] = new WeakMap();
+        this.earconBuffers[earconName].set(window, new window.Audio(earcon));
       }
 
-      this.audioContext = new window.AudioContext();
-
-      for (let earcon of this.EARCONS) {
-        let xhr = new window.XMLHttpRequest();
-        xhr.open('GET', earcon);
-        xhr.responseType = 'arraybuffer';
-        xhr.onerror = () => {
-          Logger.error('Error getting earcon:', xhr.statusText);
-          this.doDelayedActionsIfLoaded(--this.earconsToLoad);
-        };
-        xhr.onload = () => {
-          this.audioContext.decodeAudioData(
-            xhr.response,
-            (audioBuffer) => {
-              try {
-                let earconName = /.*\/(.*)\..*$/.exec(earcon)[1];
-                this.earconBuffers[earconName] = new WeakMap();
-                this.earconBuffers[earconName].set(window, audioBuffer);
-                this.doDelayedActionsIfLoaded(--this.earconsToLoad);
-              } catch (x) {
-                Logger.logException(x);
-              }
-            },
-            () => {
-              this.doDelayedActionsIfLoaded(--this.earconsToLoad);
-              Logger.error('Error decoding earcon');
-            });
-        };
-        xhr.send();
-      }
+      this.inited = true;
     },
 
     output: function output(aActions) {
-      if (this.earconsToLoad !== 0) {
-        // We did not load the earcons yet.
-        this.delayedActions.push.apply(this.delayedActions, aActions);
-        if (this.earconsToLoad < 0) {
-          // Loading did not start yet, start it.
-          this.init();
-        }
-        return;
+      if (!this.inited) {
+        this.init();
       }
 
-      this.outputActions(aActions);
-    },
-
-    outputActions: function outputActions(aActions) {
       for (let action of aActions) {
         let window = Utils.win;
         Logger.info('tts.' + action.method,
                     '"' + action.data + '"',
                     JSON.stringify(action.options));
 
         if (!action.options.enqueue && this.webspeechEnabled) {
           window.speechSynthesis.cancel();
         }
 
         if (action.method === 'speak' && this.webspeechEnabled) {
           window.speechSynthesis.speak(
             new window.SpeechSynthesisUtterance(action.data));
-        } else if (action.method === 'playEarcon' && this.webaudioEnabled) {
+        } else if (action.method === 'playEarcon') {
           let audioBufferWeakMap = this.earconBuffers[action.data];
           if (audioBufferWeakMap) {
-            let node = this.audioContext.createBufferSource();
-            node.connect(this.audioContext.destination);
-            node.buffer = audioBufferWeakMap.get(window);
-            node.start(0);
+            audioBufferWeakMap.get(window).cloneNode(false).play();
           }
         }
       }
     }
   },
 
   start: function start() {
     Cu.import('resource://gre/modules/Geometry.jsm');
@@ -793,16 +730,19 @@ var Input = {
         this.sendContextMenuMessage();
         break;
       case 'swiperight1':
         this.moveCursor('moveNext', 'Simple', 'gestures');
         break;
       case 'swipeleft1':
         this.moveCursor('movePrevious', 'Simple', 'gesture');
         break;
+      case 'exploreend1':
+        this.activateCurrent(null, true);
+        break;
       case 'swiperight2':
         this.sendScrollMessage(-1, true);
         break;
       case 'swipedown2':
         this.sendScrollMessage(-1);
         break;
       case 'swipeleft2':
         this.sendScrollMessage(1, true);
@@ -933,22 +873,23 @@ var Input = {
     }
 
     let mm = Utils.getMessageManager(Utils.CurrentBrowser);
     let type = this.editState.editing ? 'AccessFu:MoveCaret' :
                                         'AccessFu:MoveByGranularity';
     mm.sendAsyncMessage(type, aDetails);
   },
 
-  activateCurrent: function activateCurrent(aData) {
+  activateCurrent: function activateCurrent(aData, aActivateIfKey = false) {
     let mm = Utils.getMessageManager(Utils.CurrentBrowser);
     let offset = aData && typeof aData.keyIndex === 'number' ?
                  aData.keyIndex - Output.brailleState.startOffset : -1;
 
-    mm.sendAsyncMessage('AccessFu:Activate', {offset: offset});
+    mm.sendAsyncMessage('AccessFu:Activate',
+                        {offset: offset, activateIfKey: aActivateIfKey});
   },
 
   sendContextMenuMessage: function sendContextMenuMessage() {
     let mm = Utils.getMessageManager(Utils.CurrentBrowser);
     mm.sendAsyncMessage('AccessFu:ContextMenu', {});
   },
 
   activateContextMenu: function activateContextMenu(aDetails) {
--- a/accessible/src/jsat/TouchAdapter.jsm
+++ b/accessible/src/jsat/TouchAdapter.jsm
@@ -423,20 +423,20 @@ TouchPoint.prototype = {
       }
 
       this.finish();
 
       return swipeGesture;
     }
 
     // To be considered an explore...
-    if (!this.done &&
-        duration > TouchAdapter.SWIPE_MAX_DURATION &&
+    if (duration > TouchAdapter.SWIPE_MAX_DURATION &&
         (this.distanceTraveled / this.dpi) > TouchAdapter.TAP_MAX_RADIUS) {
-      return {type: 'explore', x: this.x, y: this.y};
+      return {type: this.done ? 'exploreend' : 'explore',
+              x: this.x, y: this.y};
     }
 
     return null;
   },
 
   get directDistanceTraveled() {
     return this.getDistanceToCoord(this.startX, this.startY);
   }
--- a/accessible/src/jsat/TraversalRules.jsm
+++ b/accessible/src/jsat/TraversalRules.jsm
@@ -26,16 +26,17 @@ const ROLE_RADIOBUTTON = Ci.nsIAccessibl
 const ROLE_COMBOBOX = Ci.nsIAccessibleRole.ROLE_COMBOBOX;
 const ROLE_PROGRESSBAR = Ci.nsIAccessibleRole.ROLE_PROGRESSBAR;
 const ROLE_BUTTONDROPDOWN = Ci.nsIAccessibleRole.ROLE_BUTTONDROPDOWN;
 const ROLE_BUTTONMENU = Ci.nsIAccessibleRole.ROLE_BUTTONMENU;
 const ROLE_CHECK_MENU_ITEM = Ci.nsIAccessibleRole.ROLE_CHECK_MENU_ITEM;
 const ROLE_PASSWORD_TEXT = Ci.nsIAccessibleRole.ROLE_PASSWORD_TEXT;
 const ROLE_RADIO_MENU_ITEM = Ci.nsIAccessibleRole.ROLE_RADIO_MENU_ITEM;
 const ROLE_TOGGLE_BUTTON = Ci.nsIAccessibleRole.ROLE_TOGGLE_BUTTON;
+const ROLE_KEY = Ci.nsIAccessibleRole.ROLE_KEY;
 const ROLE_ENTRY = Ci.nsIAccessibleRole.ROLE_ENTRY;
 const ROLE_LIST = Ci.nsIAccessibleRole.ROLE_LIST;
 const ROLE_DEFINITION_LIST = Ci.nsIAccessibleRole.ROLE_DEFINITION_LIST;
 const ROLE_LISTITEM = Ci.nsIAccessibleRole.ROLE_LISTITEM;
 const ROLE_BUTTONDROPDOWNGRID = Ci.nsIAccessibleRole.ROLE_BUTTONDROPDOWNGRID;
 const ROLE_LISTBOX = Ci.nsIAccessibleRole.ROLE_LISTBOX;
 const ROLE_SLIDER = Ci.nsIAccessibleRole.ROLE_SLIDER;
 const ROLE_HEADING = Ci.nsIAccessibleRole.ROLE_HEADING;
@@ -99,16 +100,17 @@ var gSimpleTraversalRoles =
    ROLE_PROGRESSBAR,
    ROLE_BUTTONDROPDOWN,
    ROLE_BUTTONMENU,
    ROLE_CHECK_MENU_ITEM,
    ROLE_PASSWORD_TEXT,
    ROLE_RADIO_MENU_ITEM,
    ROLE_TOGGLE_BUTTON,
    ROLE_ENTRY,
+   ROLE_KEY,
    ROLE_HEADER,
    ROLE_HEADING,
    // Used for traversing in to child OOP frames.
    ROLE_INTERNAL_FRAME];
 
 this.TraversalRules = {
   Simple: new BaseTraversalRule(
     gSimpleTraversalRoles,
--- a/accessible/src/jsat/content-script.js
+++ b/accessible/src/jsat/content-script.js
@@ -159,16 +159,22 @@ function forwardToChild(aMessage, aListe
   }
   mm.sendAsyncMessage(aMessage.name, newJSON);
   return true;
 }
 
 function activateCurrent(aMessage) {
   Logger.debug('activateCurrent');
   function activateAccessible(aAccessible) {
+    if (aMessage.json.activateIfKey &&
+        aAccessible.role != Ci.nsIAccessibleRole.ROLE_KEY) {
+      // Only activate keys, don't do anything on other objects.
+      return;
+    }
+
     if (aAccessible.actionCount > 0) {
       aAccessible.doAction(0);
     } else {
       // XXX Some mobile widget sets do not expose actions properly
       // (via ARIA roles, etc.), so we need to generate a click.
       // Could possibly be made simpler in the future. Maybe core
       // engine could expose nsCoreUtiles::DispatchMouseEvent()?
       let docAcc = Utils.AccRetrieval.getAccessibleFor(content.document);
--- a/accessible/src/windows/msaa/AccessibleWrap.cpp
+++ b/accessible/src/windows/msaa/AccessibleWrap.cpp
@@ -39,16 +39,17 @@
 #include "mozilla/Preferences.h"
 
 #include "Accessible2_i.c"
 #include "AccessibleRole.h"
 #include "AccessibleStates.h"
 #include "oleacc.h"
 #include "nsIAccessibleTypes.h"
 #include "nsIPersistentProperties2.h"
+#include "nsISimpleEnumerator.h"
 
 using namespace mozilla;
 using namespace mozilla::a11y;
 
 const uint32_t USE_ROLE_STRING = 0;
 
 /* For documentation of the accessibility architecture,
  * see http://lxr.mozilla.org/seamonkey/source/accessible/accessible-docs.html
--- a/b2g/components/Keyboard.jsm
+++ b/b2g/components/Keyboard.jsm
@@ -26,17 +26,17 @@ this.Keyboard = {
     'GetText', 'SendKey', 'GetContext',
     'SetComposition', 'EndComposition'
   ],
 
   get messageManager() {
     if (this._messageManager && !Cu.isDeadWrapper(this._messageManager))
       return this._messageManager;
 
-    throw Error('no message manager set');
+    return null;
   },
 
   set messageManager(mm) {
     this._messageManager = mm;
   },
 
   sendAsyncMessage: function(name, data) {
     try {
@@ -87,16 +87,20 @@ this.Keyboard = {
       }
     }
   },
 
   receiveMessage: function keyboardReceiveMessage(msg) {
     // If we get a 'Keyboard:XXX' message, check that the sender has the
     // keyboard permission.
     if (msg.name.indexOf("Keyboard:") != -1) {
+      if (!this.messageManager) {
+        return;
+      }
+
       let mm;
       try {
         mm = msg.target.QueryInterface(Ci.nsIFrameLoaderOwner)
                        .frameLoader.messageManager;
       } catch(e) {
         mm = msg.target;
       }
 
--- a/b2g/components/MozKeyboard.js
+++ b/b2g/components/MozKeyboard.js
@@ -194,67 +194,116 @@ MozKeyboard.prototype = {
 
   observe: function mozKeyboardObserve(subject, topic, data) {
     let wId = subject.QueryInterface(Ci.nsISupportsPRUint64).data;
     if (wId == this.innerWindowID)
       this.uninit();
   }
 };
 
+const TESTING_ENABLED_PREF = "dom.mozInputMethod.testing";
+
+/*
+ * A WeakMap to map input method iframe window to its active status.
+ */
+let WindowMap = {
+  // WeakMap of <window, boolean> pairs.
+  _map: null,
+
+  /*
+   * Check if the given window is active.
+   */
+  isActive: function(win) {
+    if (!this._map || !win) {
+      return false;
+    }
+    return this._map.get(win, false);
+  },
+
+  /*
+   * Set the active status of the given window.
+   */
+  setActive: function(win, isActive) {
+    if (!win) {
+      return;
+    }
+    if (!this._map) {
+      this._map = new WeakMap();
+    }
+    this._map.set(win, isActive);
+  }
+};
+
 /**
  * ==============================================
  * InputMethodManager
  * ==============================================
  */
-function MozInputMethodManager() { }
+function MozInputMethodManager(win) {
+  this._window = win;
+}
 
 MozInputMethodManager.prototype = {
   _supportsSwitching: false,
+  _window: null,
 
   classID: Components.ID("{7e9d7280-ef86-11e2-b778-0800200c9a66}"),
 
   QueryInterface: XPCOMUtils.generateQI([
     Ci.nsIInputMethodManager
   ]),
 
   classInfo: XPCOMUtils.generateCI({
     "classID": Components.ID("{7e9d7280-ef86-11e2-b778-0800200c9a66}"),
     "contractID": "@mozilla.org/b2g-imm;1",
     "interfaces": [Ci.nsIInputMethodManager],
     "flags": Ci.nsIClassInfo.DOM_OBJECT,
     "classDescription": "B2G Input Method Manager"
   }),
 
   showAll: function() {
+    if (!WindowMap.isActive(this._window)) {
+      return;
+    }
     cpmm.sendAsyncMessage('Keyboard:ShowInputMethodPicker', {});
   },
 
   next: function() {
+    if (!WindowMap.isActive(this._window)) {
+      return;
+    }
     cpmm.sendAsyncMessage('Keyboard:SwitchToNextInputMethod', {});
   },
 
   supportsSwitching: function() {
+    if (!WindowMap.isActive(this._window)) {
+      return false;
+    }
     return this._supportsSwitching;
   },
 
   hide: function() {
+    if (!WindowMap.isActive(this._window)) {
+      return;
+    }
     cpmm.sendAsyncMessage('Keyboard:RemoveFocus', {});
   }
 };
 
 /**
  * ==============================================
  * InputMethod
  * ==============================================
  */
 function MozInputMethod() { }
 
 MozInputMethod.prototype = {
   _inputcontext: null,
   _layouts: {},
+  _window: null,
 
   classID: Components.ID("{4607330d-e7d2-40a4-9eb8-43967eae0142}"),
 
   QueryInterface: XPCOMUtils.generateQI([
     Ci.nsIInputMethod,
     Ci.nsIDOMGlobalPropertyInitializer,
     Ci.nsIObserver
   ]),
@@ -263,55 +312,63 @@ MozInputMethod.prototype = {
     "classID": Components.ID("{4607330d-e7d2-40a4-9eb8-43967eae0142}"),
     "contractID": "@mozilla.org/b2g-inputmethod;1",
     "interfaces": [Ci.nsIInputMethod],
     "flags": Ci.nsIClassInfo.DOM_OBJECT,
     "classDescription": "B2G Input Method"
   }),
 
   init: function mozInputMethodInit(win) {
-    let principal = win.document.nodePrincipal;
-    let perm = Services.perms
-               .testExactPermissionFromPrincipal(principal, "keyboard");
-    if (perm != Ci.nsIPermissionManager.ALLOW_ACTION) {
-      dump("No permission to use the keyboard API for " +
-           principal.origin + "\n");
-      return null;
+    // Check if we're in testing mode.
+    let isTesting = false;
+    try {
+      isTesting = Services.prefs.getBoolPref(TESTING_ENABLED_PREF);
+    } catch (e) {}
+
+    // Don't bypass the permission check if not in testing mode.
+    if (!isTesting) {
+      let principal = win.document.nodePrincipal;
+      let perm = Services.perms
+                 .testExactPermissionFromPrincipal(principal, "keyboard");
+      if (perm != Ci.nsIPermissionManager.ALLOW_ACTION) {
+        dump("No permission to use the keyboard API for " +
+             principal.origin + "\n");
+        return null;
+      }
     }
 
     this._window = win;
-    this._mgmt = new MozInputMethodManager();
+    this._mgmt = new MozInputMethodManager(win);
     this.innerWindowID = win.QueryInterface(Ci.nsIInterfaceRequestor)
                             .getInterface(Ci.nsIDOMWindowUtils)
                             .currentInnerWindowID;
 
     Services.obs.addObserver(this, "inner-window-destroyed", false);
     cpmm.addMessageListener('Keyboard:FocusChange', this);
     cpmm.addMessageListener('Keyboard:SelectionChange', this);
     cpmm.addMessageListener('Keyboard:GetContext:Result:OK', this);
     cpmm.addMessageListener('Keyboard:LayoutsChange', this);
-
-    // If there already is an active context, then this will trigger
-    // a GetContext:Result:OK event, and we can initialize ourselves.
-    // Otherwise silently ignored.
-    cpmm.sendAsyncMessage("Keyboard:GetContext", {});
   },
 
   uninit: function mozInputMethodUninit() {
     Services.obs.removeObserver(this, "inner-window-destroyed");
     cpmm.removeMessageListener('Keyboard:FocusChange', this);
     cpmm.removeMessageListener('Keyboard:SelectionChange', this);
     cpmm.removeMessageListener('Keyboard:GetContext:Result:OK', this);
     cpmm.removeMessageListener('Keyboard:LayoutsChange', this);
 
     this._window = null;
     this._mgmt = null;
   },
 
   receiveMessage: function mozInputMethodReceiveMsg(msg) {
+    if (!WindowMap.isActive(this._window)) {
+      return;
+    }
+
     let json = msg.json;
 
     switch(msg.name) {
       case 'Keyboard:FocusChange':
         if (json.type !== 'blur') {
           // XXX Bug 904339 could receive 'text' event twice
           this.setInputContext(json);
         }
@@ -333,21 +390,28 @@ MozInputMethod.prototype = {
 
   observe: function mozInputMethodObserve(subject, topic, data) {
     let wId = subject.QueryInterface(Ci.nsISupportsPRUint64).data;
     if (wId == this.innerWindowID)
       this.uninit();
   },
 
   get mgmt() {
+    if (!WindowMap.isActive(this._window)) {
+      return null;
+    }
+
     return this._mgmt;
   },
 
   get inputcontext() {
-     return this._inputcontext;
+    if (!WindowMap.isActive(this._window)) {
+      return null;
+    }
+    return this._inputcontext;
   },
 
   set oninputcontextchange(handler) {
     this.__DOM_IMPL__.setEventHandler("oninputcontextchange", handler);
   },
 
   get oninputcontextchange() {
     return this.__DOM_IMPL__.getEventHandler("oninputcontextchange");
@@ -367,16 +431,37 @@ MozInputMethod.prototype = {
 
       this._inputcontext = new MozInputContext(data);
       this._inputcontext.init(this._window);
     }
 
     let event = new this._window.Event("inputcontextchange",
                                        ObjectWrapper.wrap({}, this._window));
     this.__DOM_IMPL__.dispatchEvent(event);
+  },
+
+  setActive: function mozInputMethodSetActive(isActive) {
+    if (WindowMap.isActive(this._window) === isActive) {
+      return;
+    }
+
+    WindowMap.setActive(this._window, isActive);
+
+    if (isActive) {
+      // Activate current input method.
+      // If there is already an active context, then this will trigger
+      // a GetContext:Result:OK event, and we can initialize ourselves.
+      // Otherwise silently ignored.
+      cpmm.sendAsyncMessage("Keyboard:GetContext", {});
+    } else {
+      // Deactive current input method.
+      if (this._inputcontext) {
+        this.setInputContext(null);
+      }
+    }
   }
 };
 
  /**
  * ==============================================
  * InputContext
  * ==============================================
  */
@@ -395,16 +480,17 @@ function MozInputContext(ctx) {
   };
 
   this._contextId = ctx.contextId;
 }
 
 MozInputContext.prototype = {
   __proto__: DOMRequestIpcHelper.prototype,
 
+  _window: null,
   _context: null,
   _contextId: -1,
 
   classID: Components.ID("{1e38633d-d08b-4867-9944-afa5c648adb6}"),
 
   QueryInterface: XPCOMUtils.generateQI([
     Ci.nsIB2GInputContext,
     Ci.nsIObserver
@@ -447,16 +533,18 @@ MozInputContext.prototype = {
     // this object. After destroying all methods will throw because we
     // cannot create new promises anymore, but we still hold
     // (outdated) information in the context. So let's clear that out.
     for (var k in this._context) {
       if (this._context.hasOwnProperty(k)) {
         this._context[k] = null;
       }
     }
+
+    this._window = null;
   },
 
   receiveMessage: function ic_receiveMessage(msg) {
     if (!msg || !msg.json) {
       dump('InputContext received message without data\n');
       return;
     }
 
@@ -553,18 +641,17 @@ MozInputContext.prototype = {
   },
 
   get lang() {
     return this._context.lang;
   },
 
   getText: function ic_getText(offset, length) {
     let self = this;
-    return this.createPromise(function(resolve, reject) {
-      let resolverId = self.getPromiseResolverId({ resolve: resolve, reject: reject });
+    return this._sendPromise(function(resolverId) {
       cpmm.sendAsyncMessage('Keyboard:GetText', {
         contextId: self._contextId,
         requestId: resolverId,
         offset: offset,
         length: length
       });
     });
   },
@@ -582,18 +669,17 @@ MozInputContext.prototype = {
   },
 
   get textAfterCursor() {
     return this._context.textAfterCursor;
   },
 
   setSelectionRange: function ic_setSelectionRange(start, length) {
     let self = this;
-    return this.createPromise(function(resolve, reject) {
-      let resolverId = self.getPromiseResolverId({ resolve: resolve, reject: reject });
+    return this._sendPromise(function(resolverId) {
       cpmm.sendAsyncMessage("Keyboard:SetSelectionRange", {
         contextId: self._contextId,
         requestId: resolverId,
         selectionStart: start,
         selectionEnd: start + length
       });
     });
   },
@@ -611,67 +697,76 @@ MozInputContext.prototype = {
   },
 
   set onselectionchange(handler) {
     this.__DOM_IMPL__.setEventHandler("onselectionchange");
   },
 
   replaceSurroundingText: function ic_replaceSurrText(text, offset, length) {
     let self = this;
-    return this.createPromise(function(resolve, reject) {
-      let resolverId = self.getPromiseResolverId({ resolve: resolve, reject: reject });
+    return this._sendPromise(function(resolverId) {
       cpmm.sendAsyncMessage('Keyboard:ReplaceSurroundingText', {
         contextId: self._contextId,
         requestId: resolverId,
         text: text,
         beforeLength: offset || 0,
         afterLength: length || 0
       });
     });
   },
 
   deleteSurroundingText: function ic_deleteSurrText(offset, length) {
     return this.replaceSurroundingText(null, offset, length);
   },
 
   sendKey: function ic_sendKey(keyCode, charCode, modifiers) {
     let self = this;
-    return this.createPromise(function(resolve, reject) {
-      let resolverId = self.getPromiseResolverId({ resolve: resolve, reject: reject });
+    return this._sendPromise(function(resolverId) {
       cpmm.sendAsyncMessage('Keyboard:SendKey', {
         contextId: self._contextId,
         requestId: resolverId,
         keyCode: keyCode,
         charCode: charCode,
         modifiers: modifiers
       });
     });
   },
 
   setComposition: function ic_setComposition(text, cursor, clauses) {
     let self = this;
-    return this.createPromise(function(resolve, reject) {
-      let resolverId = self.getPromiseResolverId({ resolve: resolve, reject: reject });
+    return this._sendPromise(function(resolverId) {
       cpmm.sendAsyncMessage('Keyboard:SetComposition', {
         contextId: self._contextId,
         requestId: resolverId,
         text: text,
         cursor: cursor || text.length,
         clauses: clauses || null
       });
     });
   },
 
   endComposition: function ic_endComposition(text) {
     let self = this;
-    return this.createPromise(function(resolve, reject) {
-      let resolverId = self.getPromiseResolverId({ resolve: resolve, reject: reject });
+    return this._sendPromise(function(resolverId) {
       cpmm.sendAsyncMessage('Keyboard:EndComposition', {
         contextId: self._contextId,
         requestId: resolverId,
         text: text || ''
       });
     });
+  },
+
+  _sendPromise: function(callback) {
+    let self = this;
+    return this.createPromise(function(resolve, reject) {
+      let resolverId = self.getPromiseResolverId({ resolve: resolve, reject: reject });
+      if (!WindowMap.isActive(self._window)) {
+        self.removePromiseResolver(resolverId);
+        reject('Input method is not active.');
+        return;
+      }
+      callback(resolverId);
+    });
   }
 };
 
 this.NSGetFactory = XPCOMUtils.generateNSGetFactory(
   [MozKeyboard, MozInputMethod]);
--- a/b2g/config/gaia.json
+++ b/b2g/config/gaia.json
@@ -1,4 +1,4 @@
 {
-    "revision": "c062ff36671ed3b1249428ad098dc70615e5e612", 
+    "revision": "7c63d2f71b0b68f085e01cb09f355b259ade2dd1", 
     "repo_path": "/integration/gaia-central"
 }
--- a/b2g/installer/package-manifest.in
+++ b/b2g/installer/package-manifest.in
@@ -373,16 +373,18 @@
 @BINPATH@/components/passwordmgr.manifest
 @BINPATH@/components/nsLoginInfo.js
 @BINPATH@/components/nsLoginManager.js
 @BINPATH@/components/nsLoginManagerPrompter.js
 #ifdef MOZ_WEBRTC
 @BINPATH@/components/PeerConnection.js
 @BINPATH@/components/PeerConnection.manifest
 #endif
+@BINPATH@/components/HttpDataUsage.manifest
+@BINPATH@/components/HttpDataUsage.js
 @BINPATH@/components/SiteSpecificUserAgent.js
 @BINPATH@/components/SiteSpecificUserAgent.manifest
 @BINPATH@/components/storage-Legacy.js
 @BINPATH@/components/storage-mozStorage.js
 @BINPATH@/components/crypto-SDR.js
 @BINPATH@/components/jsconsole-clhandler.manifest
 @BINPATH@/components/jsconsole-clhandler.js
 @BINPATH@/components/nsHelperAppDlg.manifest
--- a/browser/base/content/browser-gestureSupport.js
+++ b/browser/base/content/browser-gestureSupport.js
@@ -544,39 +544,42 @@ let gHistorySwipeAnimation = {
   init: function HSA_init() {
     if (!this._isSupported())
       return;
 
     this.active = false;
     this.isLTR = document.documentElement.mozMatchesSelector(
                                             ":-moz-locale-dir(ltr)");
     this._trackedSnapshots = [];
+    this._startingIndex = -1;
     this._historyIndex = -1;
     this._boxWidth = -1;
     this._maxSnapshots = this._getMaxSnapshots();
     this._lastSwipeDir = "";
 
     // We only want to activate history swipe animations if we store snapshots.
     // If we don't store any, we handle horizontal swipes without animations.
     if (this._maxSnapshots > 0) {
       this.active = true;
       gBrowser.addEventListener("pagehide", this, false);
       gBrowser.addEventListener("pageshow", this, false);
       gBrowser.addEventListener("popstate", this, false);
+      gBrowser.addEventListener("DOMModalDialogClosed", this, false);
       gBrowser.tabContainer.addEventListener("TabClose", this, false);
     }
   },
 
   /**
    * Uninitializes the support for history swipe animations.
    */
   uninit: function HSA_uninit() {
     gBrowser.removeEventListener("pagehide", this, false);
     gBrowser.removeEventListener("pageshow", this, false);
     gBrowser.removeEventListener("popstate", this, false);
+    gBrowser.removeEventListener("DOMModalDialogClosed", this, false);
     gBrowser.tabContainer.removeEventListener("TabClose", this, false);
 
     this.active = false;
     this.isLTR = false;
   },
 
   /**
    * Starts the swipe animation and handles fast swiping (i.e. a swipe animation
@@ -586,17 +589,18 @@ let gHistorySwipeAnimation = {
     if (this.isAnimationRunning()) {
       gBrowser.stop();
       this._lastSwipeDir = "RELOAD"; // just ensure that != ""
       this._canGoBack = this.canGoBack();
       this._canGoForward = this.canGoForward();
       this._handleFastSwiping();
     }
     else {
-      this._historyIndex = gBrowser.webNavigation.sessionHistory.index;
+      this._startingIndex = gBrowser.webNavigation.sessionHistory.index;
+      this._historyIndex = this._startingIndex;
       this._canGoBack = this.canGoBack();
       this._canGoForward = this.canGoForward();
       if (this.active) {
         this._takeSnapshot();
         this._installPrevAndNextSnapshots();
         this._addBoxes();
         this._lastSwipeDir = "";
       }
@@ -617,75 +621,81 @@ let gHistorySwipeAnimation = {
    * @param aVal
    *        A floating point value that represents the progress of the
    *        swipe gesture.
    */
   updateAnimation: function HSA_updateAnimation(aVal) {
     if (!this.isAnimationRunning())
       return;
 
+    // We use the following value to decrease the bounce effect when swiping
+    // back/forward past the browsing history. This value was determined
+    // experimentally.
+    let dampValue = 4;
     if ((aVal >= 0 && this.isLTR) ||
         (aVal <= 0 && !this.isLTR)) {
-      if (aVal > 1)
-        aVal = 1; // Cap value to avoid sliding the page further than allowed.
-
+      let tempDampValue = 1;
       if (this._canGoBack)
         this._prevBox.collapsed = false;
-      else
+      else {
+        tempDampValue = dampValue;
         this._prevBox.collapsed = true;
+      }
 
       // The current page is pushed to the right (LTR) or left (RTL),
       // the intention is to go back.
       // If there is a page to go back to, it should show in the background.
-      this._positionBox(this._curBox, aVal);
+      this._positionBox(this._curBox, aVal / tempDampValue);
 
       // The forward page should be pushed offscreen all the way to the right.
       this._positionBox(this._nextBox, 1);
     }
     else {
       if (aVal < -1)
         aVal = -1; // Cap value to avoid sliding the page further than allowed.
 
       // The intention is to go forward. If there is a page to go forward to,
       // it should slide in from the right (LTR) or left (RTL).
       // Otherwise, the current page should slide to the left (LTR) or
       // right (RTL) and the backdrop should appear in the background.
       // For the backdrop to be visible in that case, the previous page needs
       // to be hidden (if it exists).
       if (this._canGoForward) {
+        this._nextBox.collapsed = false;
         let offset = this.isLTR ? 1 : -1;
         this._positionBox(this._curBox, 0);
-        this._positionBox(this._nextBox, offset + aVal); // aVal is negative
+        this._positionBox(this._nextBox, offset + aVal);
       }
       else {
         this._prevBox.collapsed = true;
-        this._positionBox(this._curBox, aVal);
+        this._positionBox(this._curBox, aVal / dampValue);
       }
     }
   },
 
   /**
    * Event handler for events relevant to the history swipe animation.
    *
    * @param aEvent
    *        An event to process.
    */
   handleEvent: function HSA_handleEvent(aEvent) {
     switch (aEvent.type) {
       case "TabClose":
         let browser = gBrowser.getBrowserForTab(aEvent.target);
         this._removeTrackedSnapshot(-1, browser);
         break;
+      case "DOMModalDialogClosed":
+        this.stopAnimation();
+        break;
       case "pageshow":
       case "popstate":
-        if (this.isAnimationRunning()) {
-          if (aEvent.target != gBrowser.selectedBrowser.contentDocument)
-            break;
-          this.stopAnimation();
-        }
+        if (aEvent.target != gBrowser.selectedBrowser.contentDocument)
+          break;
+        this.stopAnimation();
         this._historyIndex = gBrowser.webNavigation.sessionHistory.index;
         break;
       case "pagehide":
         if (aEvent.target == gBrowser.selectedBrowser.contentDocument) {
           // Take a snapshot of a page whenever it's about to be navigated away
           // from.
           this._takeSnapshot();
         }
@@ -743,17 +753,17 @@ let gHistorySwipeAnimation = {
   },
 
   /**
    * Used to notify the history swipe animation that the OS sent a swipe end
    * event and that we should navigate to the page that the user swiped to, if
    * any. This will also result in the animation overlay to be torn down.
    */
   swipeEndEventReceived: function HSA_swipeEndEventReceived() {
-    if (this._lastSwipeDir != "")
+    if (this._lastSwipeDir != "" && this._historyIndex != this._startingIndex)
       this._navigateToHistoryIndex();
     else
       this.stopAnimation();
   },
 
   /**
    * Checks whether a particular index exists in the browser history or not.
    *
@@ -771,19 +781,20 @@ let gHistorySwipeAnimation = {
     return true;
   },
 
   /**
    * Navigates to the index in history that is currently being tracked by
    * |this|.
    */
   _navigateToHistoryIndex: function HSA__navigateToHistoryIndex() {
-    if (this._doesIndexExistInHistory(this._historyIndex)) {
+    if (this._doesIndexExistInHistory(this._historyIndex))
       gBrowser.webNavigation.gotoIndex(this._historyIndex);
-    }
+    else
+      this.stopAnimation();
   },
 
   /**
    * Checks to see if history swipe animations are supported by this
    * platform/configuration.
    *
    * return true if supported, false otherwise.
    */
@@ -999,22 +1010,27 @@ let gHistorySwipeAnimation = {
     if (!aBlob)
       return null;
 
     // Return aBlob if it's still a canvas and not a compressed blob yet.
     if (aBlob instanceof HTMLCanvasElement)
       return aBlob;
 
     let img = new Image();
-    let url = URL.createObjectURL(aBlob);
-    img.onload = function() {
-      URL.revokeObjectURL(url);
-    };
-    img.src = url;
-    return img;
+    let url = "";
+    try {
+      url = URL.createObjectURL(aBlob);
+      img.onload = function() {
+        URL.revokeObjectURL(url);
+      };
+    }
+    finally {
+      img.src = url;
+      return img;
+    }
   },
 
   /**
    * Sets the snapshot of the current page to the snapshot passed as parameter,
    * or to the one previously stored for the current index in history if the
    * parameter is null.
    *
    * @param aCanvas
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -907,17 +907,17 @@ var gBrowserInit = {
           defaultWidth = (screen.availWidth / 2) - 20;
           defaultHeight = screen.availHeight - 10;
         }
         else {
           defaultWidth = screen.availWidth * .75;
           defaultHeight = screen.availHeight * .75;
         }
 
-#ifdef MOZ_WIDGET_GTK2
+#if MOZ_WIDGET_GTK == 2
         // On X, we're not currently able to account for the size of the window
         // border.  Use 28px as a guess (titlebar + bottom window border)
         defaultHeight -= 28;
 #endif
       }
       document.documentElement.setAttribute("width", defaultWidth);
       document.documentElement.setAttribute("height", defaultHeight);
     }
--- a/browser/components/preferences/in-content/applications.js
+++ b/browser/components/preferences/in-content/applications.js
@@ -61,17 +61,17 @@ const PREF_AUDIO_FEED_SELECTED_READER = 
 
 // The nsHandlerInfoAction enumeration values in nsIHandlerInfo identify
 // the actions the application can take with content of various types.
 // But since nsIHandlerInfo doesn't support plugins, there's no value
 // identifying the "use plugin" action, so we use this constant instead.
 const kActionUsePlugin = 5;
 
 /*
-#ifdef MOZ_WIDGET_GTK2
+#if MOZ_WIDGET_GTK == 2
 */
 const ICON_URL_APP      = "moz-icon://dummy.exe?size=16";
 /*
 #else
 */
 const ICON_URL_APP      = "chrome://browser/skin/preferences/application.png";
 /*
 #endif
--- a/browser/devtools/debugger/debugger-view.js
+++ b/browser/devtools/debugger/debugger-view.js
@@ -31,16 +31,19 @@ const SEARCH_VARIABLE_FLAG = "*";
 const DEFAULT_EDITOR_CONFIG = {
   mode: SourceEditor.MODES.TEXT,
   readOnly: true,
   showLineNumbers: true,
   showAnnotationRuler: true,
   showOverviewRuler: true
 };
 
+//For telemetry
+Cu.import("resource://gre/modules/Services.jsm")
+
 /**
  * Object defining the debugger view components.
  */
 let DebuggerView = {
   /**
    * Initializes the debugger view.
    *
    * @return object
@@ -271,16 +274,23 @@ let DebuggerView = {
    * @return object
    *         A promise that is resolved after the source text has been set.
    */
   _setEditorSource: function(aSource, aFlags={}) {
     // Avoid setting the same source text in the editor again.
     if (this._editorSource.url == aSource.url && !aFlags.force) {
       return this._editorSource.promise;
     }
+    let transportType = DebuggerController.client.localTransport
+      ? "_LOCAL"
+      : "_REMOTE";
+    //Telemetry probe
+    let histogramId = "DEVTOOLS_DEBUGGER_DISPLAY_SOURCE" + transportType + "_MS";
+    let histogram = Services.telemetry.getHistogramById(histogramId);
+    let startTime = +new Date();
 
     let deferred = promise.defer();
 
     this._setEditorText(L10N.getStr("loadingText"));
     this._editorSource = { url: aSource.url, promise: deferred.promise };
 
     DebuggerController.SourceScripts.getText(aSource).then(([, aText]) => {
       // Avoid setting an unexpected source. This may happen when switching
@@ -291,16 +301,18 @@ let DebuggerView = {
 
       this._setEditorText(aText);
       this._setEditorMode(aSource.url, aSource.contentType, aText);
 
       // Synchronize any other components with the currently displayed source.
       DebuggerView.Sources.selectedValue = aSource.url;
       DebuggerController.Breakpoints.updateEditorBreakpoints();
 
+      histogram.add(+new Date() - startTime);
+
       // Resolve and notify that a source file was shown.
       window.emit(EVENTS.SOURCE_SHOWN, aSource);
       deferred.resolve([aSource, aText]);
     },
     ([, aError]) => {
       let msg = L10N.getStr("errorLoadingText") + DevToolsUtils.safeErrorString(aError);
       this._setEditorText(msg);
       Cu.reportError(msg);
--- a/browser/devtools/inspector/inspector-panel.js
+++ b/browser/devtools/inspector/inspector-panel.js
@@ -725,16 +725,25 @@ InspectorPanel.prototype = {
       this.markup.deleteNode(this.selection.nodeFront);
     } else {
       // remove the node from content
       this.walker.removeNode(this.selection.nodeFront);
     }
   },
 
   /**
+   * Trigger a high-priority layout change for things that need to be
+   * updated immediately
+   */
+  immediateLayoutChange: function Inspector_immediateLayoutChange()
+  {
+    this.emit("layout-change");
+  },
+
+  /**
    * Schedule a low-priority change event for things like paint
    * and resize.
    */
   scheduleLayoutChange: function Inspector_scheduleLayoutChange()
   {
     if (this._timer) {
       return null;
     }
--- a/browser/devtools/inspector/test/browser_inspector_changes.js
+++ b/browser/devtools/inspector/test/browser_inspector_changes.js
@@ -12,83 +12,138 @@ function test() {
   function createDocument()
   {
     doc.body.innerHTML = '<div id="testdiv">Test div!</div>';
     doc.title = "Inspector Change Test";
     openInspector(runInspectorTests);
   }
 
 
-  function getInspectorProp(aName)
+  function getInspectorComputedProp(aName)
   {
     let computedview = inspector.sidebar.getWindowForTab("computedview").computedview.view;
     for each (let view in computedview.propertyViews) {
       if (view.name == aName) {
         return view;
       }
     }
     return null;
   }
+  function getInspectorRuleProp(aName)
+  {
+    let ruleview = inspector.sidebar.getWindowForTab("ruleview").ruleview.view;
+    let inlineStyles = ruleview._elementStyle.rules[0];
+
+    for each (let prop in inlineStyles.textProps) {
+      if (prop.name == aName) {
+        return prop;
+      }
+    }
+    return null;
+  }
 
   function runInspectorTests(aInspector)
   {
     inspector = aInspector;
     inspector.sidebar.once("computedview-ready", function() {
       info("Computed View ready");
       inspector.sidebar.select("computedview");
 
       testDiv = doc.getElementById("testdiv");
 
       testDiv.style.fontSize = "10px";
 
       // Start up the style inspector panel...
-      inspector.once("computed-view-refreshed", stylePanelTests);
+      inspector.once("computed-view-refreshed", computedStylePanelTests);
 
       inspector.selection.setNode(testDiv);
     });
   }
 
-  function stylePanelTests()
+  function computedStylePanelTests()
   {
     let computedview = inspector.sidebar.getWindowForTab("computedview").computedview;
     ok(computedview, "Style Panel has a cssHtmlTree");
 
-    let propView = getInspectorProp("font-size");
+    let propView = getInspectorComputedProp("font-size");
     is(propView.value, "10px", "Style inspector should be showing the correct font size.");
 
-    inspector.once("computed-view-refreshed", stylePanelAfterChange);
+    inspector.once("computed-view-refreshed", computedStylePanelAfterChange);
 
-    testDiv.style.fontSize = "15px";
-    inspector.emit("layout-change");
+    testDiv.style.cssText = "font-size: 15px; color: red;";
   }
 
-  function stylePanelAfterChange()
+  function computedStylePanelAfterChange()
   {
-    let propView = getInspectorProp("font-size");
+    let propView = getInspectorComputedProp("font-size");
     is(propView.value, "15px", "Style inspector should be showing the new font size.");
 
-    stylePanelNotActive();
+    let propView = getInspectorComputedProp("color");
+    is(propView.value, "#F00", "Style inspector should be showing the new color.");
+
+    computedStylePanelNotActive();
   }
 
-  function stylePanelNotActive()
+  function computedStylePanelNotActive()
   {
     // Tests changes made while the style panel is not active.
     inspector.sidebar.select("ruleview");
+    testDiv.style.fontSize = "20px";
+    testDiv.style.color = "blue";
+    testDiv.style.textAlign = "center";
+    inspector.once("computed-view-refreshed", computedStylePanelAfterSwitch);
+    inspector.sidebar.select("computedview");
+  }
 
-    executeSoon(function() {
-      inspector.once("computed-view-refreshed", stylePanelAfterSwitch);
-      testDiv.style.fontSize = "20px";
-      inspector.sidebar.select("computedview");
-    });
+  function computedStylePanelAfterSwitch()
+  {
+    let propView = getInspectorComputedProp("font-size");
+    is(propView.value, "20px", "Style inspector should be showing the new font size.");
+
+    let propView = getInspectorComputedProp("color");
+    is(propView.value, "#00F", "Style inspector should be showing the new color.");
+
+    let propView = getInspectorComputedProp("text-align");
+    is(propView.value, "center", "Style inspector should be showing the new text align.");
+
+    rulePanelTests();
   }
 
-  function stylePanelAfterSwitch()
+  function rulePanelTests()
   {
-    let propView = getInspectorProp("font-size");
-    is(propView.value, "20px", "Style inspector should be showing the newest font size.");
+    inspector.sidebar.select("ruleview");
+    let ruleview = inspector.sidebar.getWindowForTab("ruleview").ruleview;
+    ok(ruleview, "Style Panel has a ruleview");
+
+    let propView = getInspectorRuleProp("text-align");
+    is(propView.value, "center", "Style inspector should be showing the new text align.");
+
+    testDiv.style.textAlign = "right";
+    testDiv.style.color = "lightgoldenrodyellow";
+    testDiv.style.fontSize = "3em";
+    testDiv.style.textTransform = "uppercase";
+
+
+    inspector.once("rule-view-refreshed", rulePanelAfterChange);
+
+  }
+
+  function rulePanelAfterChange()
+  {
+    let propView = getInspectorRuleProp("text-align");
+    is(propView.value, "right", "Style inspector should be showing the new text align.");
+
+    let propView = getInspectorRuleProp("color");
+    is(propView.value, "#FAFAD2", "Style inspector should be showing the new color.")
+
+    let propView = getInspectorRuleProp("font-size");
+    is(propView.value, "3em", "Style inspector should be showing the new font size.");
+
+    let propView = getInspectorRuleProp("text-transform");
+    is(propView.value, "uppercase", "Style inspector should be showing the new text transform.");
 
     finishTest();
   }
 
   function finishTest()
   {
     gBrowser.removeCurrentTab();
     finish();
--- a/browser/devtools/markupview/markup-view.js
+++ b/browser/devtools/markupview/markup-view.js
@@ -392,16 +392,17 @@ MarkupView.prototype = {
   },
 
 
   /**
    * Mutation observer used for included nodes.
    */
   _mutationObserver: function MT__mutationObserver(aMutations)
   {
+    let requiresLayoutChange = false;
     for (let mutation of aMutations) {
       let type = mutation.type;
       let target = mutation.target;
 
       if (mutation.type === "documentUnload") {
         // Treat this as a childList change of the child (maybe the protocol
         // should do this).
         type = "childList";
@@ -414,24 +415,33 @@ MarkupView.prototype = {
       let container = this._containers.get(target);
       if (!container) {
         // Container might not exist if this came from a load event for a node
         // we're not viewing.
         continue;
       }
       if (type === "attributes" || type === "characterData") {
         container.update(false);
+
+        // Auto refresh style properties on selected node when they change.
+        if (type === "attributes" && container.selected) {
+          requiresLayoutChange = true;
+        }
       } else if (type === "childList") {
         container.childrenDirty = true;
         // Update the children to take care of changes in the DOM
         // Passing true as the last parameter asks for mutation flashing of the
         // new nodes
         this._updateChildren(container, {flash: true});
       }
     }
+
+    if (requiresLayoutChange) {
+      this._inspector.immediateLayoutChange();
+    }
     this._waitForChildren().then(() => {
       this._flashMutatedNodes(aMutations);
       this._inspector.emit("markupmutation");
     });
   },
 
   /**
    * Given a list of mutations returned by the mutation observer, flash the
--- a/browser/devtools/styleinspector/rule-view.js
+++ b/browser/devtools/styleinspector/rule-view.js
@@ -1278,23 +1278,23 @@ CssRuleView.prototype = {
 
   /**
    * Update the rules for the currently highlighted element.
    */
   nodeChanged: function CssRuleView_nodeChanged()
   {
     // Ignore refreshes during editing or when no element is selected.
     if (this.isEditing || !this._elementStyle) {
-      return promise.resolve(null);
+      return;
     }
 
     this._clearRules();
 
     // Repopulate the element style.
-    return this._populate();
+    this._populate();
   },
 
   _populate: function() {
     let elementStyle = this._elementStyle;
     return this._elementStyle.populate().then(() => {
       if (this._elementStyle != elementStyle) {
         return promise.reject("element changed");
       }
--- a/browser/devtools/styleinspector/test/browser_ruleview_update.js
+++ b/browser/devtools/styleinspector/test/browser_ruleview_update.js
@@ -2,16 +2,17 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 let doc;
 
 let inspector;
 let ruleView;
 let testElement;
+let rule;
 
 function startTest(aInspector, aRuleView)
 {
   inspector = aInspector;
   ruleView = aRuleView;
   let style = '' +
     '#testid {' +
     '  background-color: blue;' +
@@ -38,109 +39,134 @@ function testRuleChanges()
 {
   let selectors = ruleView.doc.querySelectorAll(".ruleview-selector");
   is(selectors.length, 3, "Three rules visible.");
   is(selectors[0].textContent.indexOf("element"), 0, "First item is inline style.");
   is(selectors[1].textContent.indexOf("#testid"), 0, "Second item is id rule.");
   is(selectors[2].textContent.indexOf(".testclass"), 0, "Third item is class rule.");
 
   // Change the id and refresh.
+  inspector.once("rule-view-refreshed", testRuleChange1);
   testElement.setAttribute("id", "differentid");
-  promiseDone(ruleView.nodeChanged().then(() => {
-    let selectors = ruleView.doc.querySelectorAll(".ruleview-selector");
-    is(selectors.length, 2, "Two rules visible.");
-    is(selectors[0].textContent.indexOf("element"), 0, "First item is inline style.");
-    is(selectors[1].textContent.indexOf(".testclass"), 0, "Second item is class rule.");
+}
+
+function testRuleChange1()
+{
+  let selectors = ruleView.doc.querySelectorAll(".ruleview-selector");
+  is(selectors.length, 2, "Two rules visible.");
+  is(selectors[0].textContent.indexOf("element"), 0, "First item is inline style.");
+  is(selectors[1].textContent.indexOf(".testclass"), 0, "Second item is class rule.");
 
-    testElement.setAttribute("id", "testid");
-    return ruleView.nodeChanged();
-  }).then(() => {
-    // Put the id back.
-    let selectors = ruleView.doc.querySelectorAll(".ruleview-selector");
-    is(selectors.length, 3, "Three rules visible.");
-    is(selectors[0].textContent.indexOf("element"), 0, "First item is inline style.");
-    is(selectors[1].textContent.indexOf("#testid"), 0, "Second item is id rule.");
-    is(selectors[2].textContent.indexOf(".testclass"), 0, "Third item is class rule.");
+  inspector.once("rule-view-refreshed", testRuleChange2);
+  testElement.setAttribute("id", "testid");
+}
+function testRuleChange2()
+{
+  let selectors = ruleView.doc.querySelectorAll(".ruleview-selector");
+  is(selectors.length, 3, "Three rules visible.");
+  is(selectors[0].textContent.indexOf("element"), 0, "First item is inline style.");
+  is(selectors[1].textContent.indexOf("#testid"), 0, "Second item is id rule.");
+  is(selectors[2].textContent.indexOf(".testclass"), 0, "Third item is class rule.");
 
-    testPropertyChanges();
-  }));
+  testPropertyChanges();
 }
 
 function validateTextProp(aProp, aEnabled, aName, aValue, aDesc)
 {
   is(aProp.enabled, aEnabled, aDesc + ": enabled.");
   is(aProp.name, aName, aDesc + ": name.");
   is(aProp.value, aValue, aDesc + ": value.");
 
   is(aProp.editor.enable.hasAttribute("checked"), aEnabled, aDesc + ": enabled checkbox.");
   is(aProp.editor.nameSpan.textContent, aName, aDesc + ": name span.");
   is(aProp.editor.valueSpan.textContent, aValue, aDesc + ": value span.");
 }
 
 function testPropertyChanges()
 {
+  rule = ruleView._elementStyle.rules[0];
+  let ruleEditor = ruleView._elementStyle.rules[0].editor;
+  inspector.once("rule-view-refreshed", testPropertyChange0);
+
   // Add a second margin-top value, just to make things interesting.
-  let rule = ruleView._elementStyle.rules[0];
-  let ruleEditor = ruleView._elementStyle.rules[0].editor;
   ruleEditor.addProperty("margin-top", "5px", "");
-  promiseDone(expectRuleChange(rule).then(() => {
-    // Set the element style back to a 1px margin-top.
-    testElement.setAttribute("style", "margin-top: 1px; padding-top: 5px");
-    return ruleView.nodeChanged();
-  }).then(() => {
-    is(rule.editor.element.querySelectorAll(".ruleview-property").length, 3, "Correct number of properties");
-    validateTextProp(rule.textProps[0], true, "margin-top", "1px", "First margin property re-enabled");
-    validateTextProp(rule.textProps[2], false, "margin-top", "5px", "Second margin property disabled");
+}
+
+function testPropertyChange0()
+{
+  validateTextProp(rule.textProps[0], false, "margin-top", "1px", "Original margin property active");
 
-    // Now set it back to 5px, the 5px value should be re-enabled.
-    testElement.setAttribute("style", "margin-top: 5px; padding-top: 5px;");
-    return ruleView.nodeChanged();
+  inspector.once("rule-view-refreshed", testPropertyChange1);
+  testElement.setAttribute("style", "margin-top: 1px; padding-top: 5px");
+}
+function testPropertyChange1()
+{
+  is(rule.editor.element.querySelectorAll(".ruleview-property").length, 3, "Correct number of properties");
+  validateTextProp(rule.textProps[0], true, "margin-top", "1px", "First margin property re-enabled");
+  validateTextProp(rule.textProps[2], false, "margin-top", "5px", "Second margin property disabled");
+
+  inspector.once("rule-view-refreshed", testPropertyChange2);
 
-  }).then(() => {
-    is(rule.editor.element.querySelectorAll(".ruleview-property").length, 3, "Correct number of properties");
-    validateTextProp(rule.textProps[0], false, "margin-top", "1px", "First margin property re-enabled");
-    validateTextProp(rule.textProps[2], true, "margin-top", "5px", "Second margin property disabled");
+  // Now set it back to 5px, the 5px value should be re-enabled.
+  testElement.setAttribute("style", "margin-top: 5px; padding-top: 5px;");
+}
+function testPropertyChange2()
+{
+  is(rule.editor.element.querySelectorAll(".ruleview-property").length, 3, "Correct number of properties");
+  validateTextProp(rule.textProps[0], false, "margin-top", "1px", "First margin property re-enabled");
+  validateTextProp(rule.textProps[2], true, "margin-top", "5px", "Second margin property disabled");
+
+  inspector.once("rule-view-refreshed", testPropertyChange3);
 
-    // Set the margin property to a value that doesn't exist in the editor.
-    // Should reuse the currently-enabled element (the second one.)
-    testElement.setAttribute("style", "margin-top: 15px; padding-top: 5px;");
-    return ruleView.nodeChanged();
-  }).then(() => {
-    is(rule.editor.element.querySelectorAll(".ruleview-property").length, 3, "Correct number of properties");
-    validateTextProp(rule.textProps[0], false, "margin-top", "1px", "First margin property re-enabled");
-    validateTextProp(rule.textProps[2], true, "margin-top", "15px", "Second margin property disabled");
+  // Set the margin property to a value that doesn't exist in the editor.
+  // Should reuse the currently-enabled element (the second one.)
+  testElement.setAttribute("style", "margin-top: 15px; padding-top: 5px;");
+}
+function testPropertyChange3()
+{
+  is(rule.editor.element.querySelectorAll(".ruleview-property").length, 3, "Correct number of properties");
+  validateTextProp(rule.textProps[0], false, "margin-top", "1px", "First margin property re-enabled");
+  validateTextProp(rule.textProps[2], true, "margin-top", "15px", "Second margin property disabled");
 
-    // Remove the padding-top attribute.  Should disable the padding property but not remove it.
-    testElement.setAttribute("style", "margin-top: 5px;");
-    return ruleView.nodeChanged();
-  }).then(() => {
-    is(rule.editor.element.querySelectorAll(".ruleview-property").length, 3, "Correct number of properties");
-    validateTextProp(rule.textProps[1], false, "padding-top", "5px", "Padding property disabled");
+  inspector.once("rule-view-refreshed", testPropertyChange4);
+
+  // Remove the padding-top attribute.  Should disable the padding property but not remove it.
+  testElement.setAttribute("style", "margin-top: 5px;");
+}
+function testPropertyChange4()
+{
+  is(rule.editor.element.querySelectorAll(".ruleview-property").length, 3, "Correct number of properties");
+  validateTextProp(rule.textProps[1], false, "padding-top", "5px", "Padding property disabled");
 
-    // Put the padding-top attribute back in, should re-enable the padding property.
-    testElement.setAttribute("style", "margin-top: 5px; padding-top: 25px");
-    return ruleView.nodeChanged();
-  }).then(() => {
-    is(rule.editor.element.querySelectorAll(".ruleview-property").length, 3, "Correct number of properties");
-    validateTextProp(rule.textProps[1], true, "padding-top", "25px", "Padding property enabled");
+  inspector.once("rule-view-refreshed", testPropertyChange5);
+
+  // Put the padding-top attribute back in, should re-enable the padding property.
+  testElement.setAttribute("style", "margin-top: 5px; padding-top: 25px");
+}
+function testPropertyChange5()
+{
+  is(rule.editor.element.querySelectorAll(".ruleview-property").length, 3, "Correct number of properties");
+  validateTextProp(rule.textProps[1], true, "padding-top", "25px", "Padding property enabled");
 
-    // Add an entirely new property.
-    testElement.setAttribute("style", "margin-top: 5px; padding-top: 25px; padding-left: 20px;");
-    return ruleView.nodeChanged();
-  }).then(() => {
-    is(rule.editor.element.querySelectorAll(".ruleview-property").length, 4, "Added a property");
-    validateTextProp(rule.textProps[3], true, "padding-left", "20px", "Padding property enabled");
+  inspector.once("rule-view-refreshed", testPropertyChange6);
 
-    finishTest();
-  }));
+  // Add an entirely new property
+  testElement.setAttribute("style", "margin-top: 5px; padding-top: 25px; padding-left: 20px;");
+}
+function testPropertyChange6()
+{
+  is(rule.editor.element.querySelectorAll(".ruleview-property").length, 4, "Added a property");
+  validateTextProp(rule.textProps[3], true, "padding-left", "20px", "Padding property enabled");
+
+  finishTest();
 }
 
 function finishTest()
 {
-  inspector = ruleView = null;
+  inspector = ruleView = rule = null;
   doc = null;
   gBrowser.removeCurrentTab();
   finish();
 }
 
 function test()
 {
   waitForExplicitFinish();
--- a/browser/devtools/webconsole/test/browser_webconsole_bug_598357_jsterm_output.js
+++ b/browser/devtools/webconsole/test/browser_webconsole_bug_598357_jsterm_output.js
@@ -219,22 +219,20 @@ function testGen() {
       executeSoon(subtestNext);
     }
   };
 
   HUD.jsterm.on("variablesview-open", variablesViewShown);
 
   eventHandlers.push(variablesViewShown);
 
-  // Send the mousedown, mouseup and click events to check if the variables
-  // view opens.
-  EventUtils.sendMouseEvent({ type: "mousedown" }, messageBody, window);
-  EventUtils.sendMouseEvent({ type: "click" }, messageBody, window);
+  EventUtils.synthesizeMouse(messageBody, 2, 2, {}, HUD.iframeWindow);
 
   if (showsVariablesView) {
+    info("messageBody tagName '" + messageBody.tagName +  "' className '" + messageBody.className + "'");
     yield undefined; // wait for the panel to open if we need to.
   }
 
   testNext();
 
   yield undefined;
 }
 
--- a/browser/installer/package-manifest.in
+++ b/browser/installer/package-manifest.in
@@ -539,16 +539,19 @@
 @BINPATH@/components/AppProtocolHandler.js
 @BINPATH@/components/AppProtocolHandler.manifest
 
 #ifdef MOZ_WEBRTC
 @BINPATH@/components/PeerConnection.js
 @BINPATH@/components/PeerConnection.manifest
 #endif
 
+@BINPATH@/components/HttpDataUsage.manifest
+@BINPATH@/components/HttpDataUsage.js
+
 @BINPATH@/chrome/marionette@JAREXT@
 @BINPATH@/chrome/marionette.manifest
 @BINPATH@/components/MarionetteComponents.manifest
 @BINPATH@/components/marionettecomponent.js
 
 #ifdef MOZ_WEBSPEECH
 @BINPATH@/components/dom_webspeechsynth.xpt
 #endif
--- a/browser/locales/en-US/chrome/browser/devtools/app-manager.dtd
+++ b/browser/locales/en-US/chrome/browser/devtools/app-manager.dtd
@@ -71,15 +71,15 @@
 <!ENTITY projects.updateAppTooltip "Execute validation checks and update the app to the connected device">
 <!ENTITY projects.debugApp "Debug">
 <!ENTITY projects.debugAppTooltip "Open Developer Tools connected to this app">
 <!ENTITY projects.hostedManifestPlaceHolder2 "http://example.com/app/manifest.webapp">
 <!ENTITY projects.noProjects "No projects. Add a new packaged app below (local directory) or a hosted app (link to a manifest file).">
 
 <!ENTITY help.title "App Manager">
 <!ENTITY help.close "Close">
-<!ENTITY help.intro "This tool will help you build and install web apps on compatible devices (i.e Firefox OS). The <strong>Apps</strong> tab will assist you in the validation and installation process of your app. The <strong>Device</strong> tab will give you information about the connected device. Use the bottom toolbar to connect to a device or start the simulator.">
+<!ENTITY help.intro "This tool will help you build and install web apps on compatible devices (i.e. Firefox OS). The <strong>Apps</strong> tab will assist you in the validation and installation process of your app. The <strong>Device</strong> tab will give you information about the connected device. Use the bottom toolbar to connect to a device or start the simulator.">
 <!ENTITY help.usefullLinks "Useful links:">
 <!ENTITY help.appMgrDoc "Documentation: Using the App Manager">
 <!ENTITY help.configuringDevice "How to setup your Firefox OS device">
 <!ENTITY help.troubleShooting "Troubleshooting">
 <!ENTITY help.simulatorAddon "Install Simulator Add-on">
 <!ENTITY help.adbHelperAddon "Install Adb Helper Add-on">
--- a/browser/metro/base/tests/mochitest/browser_urlbar.js
+++ b/browser/metro/base/tests/mochitest/browser_urlbar.js
@@ -87,29 +87,28 @@ function removeMockSearchDefault(aTimeou
 }
 
 /*=============================================================================
   Test cases
 =============================================================================*/
 
 function test() {
   waitForExplicitFinish();
-  Task.spawn(function(){
-    yield addTab("about:blank");
-  }).then(runTests);
+  runTests();
 }
 
 function setUp() {
   if (!gEdit)
     gEdit = document.getElementById("urlbar-edit");
+
+  yield addTab("about:blank");
   yield showNavBar();
 }
 
 function tearDown() {
-  yield removeMockSearchDefault();
   Browser.closeTab(Browser.selectedTab, { forceClose: true });
 }
 
 gTests.push({
   desc: "search engines update",
   setUp: setUp,
   tearDown: tearDown,
   run: function testSearchEngine() {
@@ -267,25 +266,27 @@ gTests.push({
 
     let closed = yield waitForCondition(() => !gEdit.popup.popupOpen);
     ok(closed, "tap search option: popup closes, page loads");
     ok(!gEdit.isEditing, "tap search option: not in editing mode");
 
     let searchSubmission = gEngine.getSubmission(search, null);
     let trimmedSubmission = gEdit.trimValue(searchSubmission.uri.spec);
     is(gEdit.value, trimmedSubmission, "tap search option: search conducted");
+
+    yield removeMockSearchDefault();
   }
 });
 
 gTests.push({
   desc: "bug 897131 - url bar update after content tap + edge swipe",
-  setUp: setUp,
   tearDown: tearDown,
   run: function testUrlbarTyping() {
     let tab = yield addTab("about:mozilla");
+    yield showNavBar();
 
     sendElementTap(window, gEdit);
     ok(gEdit.isEditing, "focus urlbar: in editing mode");
     ok(!gEdit.popup.popupOpen, "focus urlbar: popup not open yet");
 
     EventUtils.sendString("about:blank", window);
     let opened = yield waitForCondition(() => gEdit.popup.popupOpen);
     ok(opened, "type in urlbar: popup opens");
@@ -300,8 +301,67 @@ gTests.push({
     event.initEvent("MozEdgeUICompleted", true, false);
     window.dispatchEvent(event);
 
     ok(ContextUI.navbarVisible, "navbar visible");
     is(gEdit.value, "about:mozilla", "url bar text refreshed");
   }
 });
 
+gTests.push({
+  desc: "Bug 916383 - Invisible autocomplete items selectable by keyboard when 'your results' not shown",
+  tearDown: tearDown,
+  run: function testBug916383() {
+    yield addTab("about:start");
+    yield showNavBar();
+
+    sendElementTap(window, gEdit);
+
+    let bookmarkItem = Browser.selectedBrowser.contentWindow.BookmarksStartView._grid.querySelector("richgriditem");
+    // Get the first bookmark item label to make sure it will show up in 'your results'
+    let label = bookmarkItem.getAttribute("label");
+
+    EventUtils.sendString(label, window);
+
+    let opened = yield waitForCondition(() => gEdit.popup.popupOpen);
+    yield waitForCondition(() => gEdit.popup._results.itemCount > 0);
+
+    ok(!gEdit.popup._resultsContainer.hidden, "'Your results' are visible");
+    ok(gEdit.popup._results.itemCount > 0, "'Your results' are populated");
+
+    // Append a string to make sure it doesn't match anything in 'your results'
+    EventUtils.sendString("zzzzzzzzzzzzzzzzzz", window);
+
+    yield waitForCondition(() => gEdit.popup._resultsContainer.hidden);
+
+    ok(gEdit.popup._resultsContainer.hidden, "'Your results' are hidden");
+    ok(gEdit.popup._results.itemCount === 0, "'Your results' are empty");
+
+    EventUtils.synthesizeKey("VK_DOWN", {}, window);
+    is(gEdit.popup._searches.selectedIndex, 0, "key select search: first search selected");
+  }
+});
+
+gTests.push({
+  desc: "Bug 891667 - Use up arrow too",
+  tearDown: tearDown,
+  run: function testBug891667() {
+    yield addTab("about:start");
+    yield showNavBar();
+
+    sendElementTap(window, gEdit);
+
+    let bookmarkItem = Browser.selectedBrowser.contentWindow.BookmarksStartView._grid.querySelector("richgriditem");
+    // Get the first bookmark item label to make sure it will show up in 'your results'
+    let label = bookmarkItem.getAttribute("label");
+
+    EventUtils.sendString(label, window);
+
+    yield waitForCondition(() => gEdit.popup.popupOpen);
+    yield waitForCondition(() => gEdit.popup._results.itemCount > 0);
+
+    ok(gEdit.popup._results.itemCount > 0, "'Your results' populated");
+
+    EventUtils.synthesizeKey("VK_UP", {}, window);
+    is(gEdit.popup._results.selectedIndex, 0, "Pressing arrow up selects first item.");
+  }
+});
+
--- a/browser/metro/base/tests/mochitest/head.js
+++ b/browser/metro/base/tests/mochitest/head.js
@@ -391,21 +391,22 @@ function waitForMs(aMs) {
  * @param aIntervalMs the number of miliseconds between calls to aCondition
  * @returns a Promise that resolves to true, or to an Error
  */
 function waitForCondition(aCondition, aTimeoutMs, aIntervalMs) {
   let deferred = Promise.defer();
   let timeoutMs = aTimeoutMs || kDefaultWait;
   let intervalMs = aIntervalMs || kDefaultInterval;
   let startTime = Date.now();
+  let stack = new Error().stack;
 
   function testCondition() {
     let now = Date.now();
     if((now - startTime) > timeoutMs) {
-      deferred.reject( new Error("Timed out waiting for condition to be true") );
+      deferred.reject( new Error("Timed out waiting for condition to be true at " + stack) );
       return;
     }
 
     let condition;
     try {
       condition = aCondition();
     } catch (e) {
       deferred.reject( new Error("Got exception while attempting to test condition: " + e) );
--- a/browser/themes/windows/jar.mn
+++ b/browser/themes/windows/jar.mn
@@ -91,17 +91,17 @@ browser.jar:
 *       skin/classic/browser/downloads/allDownloadsViewOverlay.css   (downloads/allDownloadsViewOverlay.css)
         skin/classic/browser/downloads/buttons.png                   (downloads/buttons.png)
         skin/classic/browser/downloads/contentAreaDownloadsView.css  (downloads/contentAreaDownloadsView.css)
         skin/classic/browser/downloads/download-glow.png             (downloads/download-glow.png)
         skin/classic/browser/downloads/download-notification-finish.png (downloads/download-notification-finish.png)
         skin/classic/browser/downloads/download-notification-start.png (downloads/download-notification-start.png)
         skin/classic/browser/downloads/download-summary.png          (downloads/download-summary.png)
 *       skin/classic/browser/downloads/downloads.css                 (downloads/downloads.css)
-*       skin/classic/browser/downloads/indicator.css                 (downloads/indicator.css)
+        skin/classic/browser/downloads/indicator.css                 (downloads/indicator.css)
         skin/classic/browser/feeds/feedIcon.png                      (feeds/feedIcon.png)
         skin/classic/browser/feeds/feedIcon16.png                    (feeds/feedIcon16.png)
         skin/classic/browser/feeds/audioFeedIcon.png                 (feeds/feedIcon.png)
         skin/classic/browser/feeds/audioFeedIcon16.png               (feeds/feedIcon16.png)
         skin/classic/browser/feeds/videoFeedIcon.png                 (feeds/feedIcon.png)
         skin/classic/browser/feeds/videoFeedIcon16.png               (feeds/feedIcon16.png)
         skin/classic/browser/feeds/subscribe.css                     (feeds/subscribe.css)
         skin/classic/browser/feeds/subscribe-ui.css                  (feeds/subscribe-ui.css)
--- a/build/automationutils.py
+++ b/build/automationutils.py
@@ -3,26 +3,52 @@
 # 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/.
 
 from __future__ import with_statement
 import glob, logging, os, platform, shutil, subprocess, sys, tempfile, urllib2, zipfile
 import re
 from urlparse import urlparse
 
+try:
+  import mozinfo
+except ImportError:
+  # Stub out fake mozinfo since this is not importable on Android 4.0 Opt.
+  # This should be fixed; see
+  # https://bugzilla.mozilla.org/show_bug.cgi?id=650881
+  mozinfo = type('mozinfo', (), dict(info={}))()
+  mozinfo.isWin = mozinfo.isLinux = mozinfo.isUnix = mozinfo.isMac = False
+
+  # TODO! FILE: localautomation :/
+  # mapping from would-be mozinfo attr <-> sys.platform
+  mapping = {'isMac': ['mac', 'darwin'],
+             'isLinux': ['linux', 'linux2'],
+             'isWin': ['win32', 'win64'],
+             }
+  mapping = dict(sum([[(value, key) for value in values] for key, values in mapping.items()], []))
+  attr = mapping.get(sys.platform)
+  if attr:
+    setattr(mozinfo, attr, True)
+  if mozinfo.isLinux:
+    mozinfo.isUnix = True
+
 __all__ = [
   "ZipFileReader",
   "addCommonOptions",
   "dumpLeakLog",
   "isURL",
   "processLeakLog",
   "getDebuggerInfo",
   "DEBUGGER_INFO",
   "replaceBackSlashes",
   "wrapCommand",
+  'KeyValueParseError',
+  'parseKeyValue',
+  'systemMemory',
+  'environment'
   ]
 
 # Map of debugging programs to information about them, like default arguments
 # and whether or not they are interactive.
 DEBUGGER_INFO = {
   # gdb requires that you supply the '--args' flag in order to pass arguments
   # after the executable name to the executable.
   "gdb": {
@@ -340,8 +366,110 @@ def wrapCommand(cmd):
   binary.
   """
   if platform.system() == "Darwin" and \
      hasattr(platform, 'mac_ver') and \
      platform.mac_ver()[0][:4] < '10.6':
     return ["arch", "-arch", "i386"] + cmd
   # otherwise just execute the command normally
   return cmd
+
+class KeyValueParseError(Exception):
+  """error when parsing strings of serialized key-values"""
+  def __init__(self, msg, errors=()):
+    self.errors = errors
+    Exception.__init__(self, msg)
+
+def parseKeyValue(strings, separator='=', context='key, value: '):
+  """
+  parse string-serialized key-value pairs in the form of
+  `key = value`. Returns a list of 2-tuples.
+  Note that whitespace is not stripped.
+  """
+
+  # syntax check
+  missing = [string for string in strings if separator not in string]
+  if missing:
+    raise KeyValueParseError("Error: syntax error in %s" % (context,
+                                                            ','.join(missing)),
+                                                            errors=missing)
+  return [string.split(separator, 1) for string in strings]
+
+def systemMemory():
+  """
+  Returns total system memory in kilobytes.
+  Works only on unix-like platforms where `free` is in the path.
+  """
+  return int(os.popen("free").readlines()[1].split()[1])
+
+def environment(xrePath, env=None, crashreporter=True):
+  """populate OS environment variables for mochitest"""
+
+  env = os.environ.copy() if env is None else env
+
+  assert os.path.isabs(xrePath)
+
+  ldLibraryPath = xrePath
+
+  envVar = None
+  if mozinfo.isUnix:
+    envVar = "LD_LIBRARY_PATH"
+    env['MOZILLA_FIVE_HOME'] = xrePath
+  elif mozinfo.isMac:
+    envVar = "DYLD_LIBRARY_PATH"
+  elif mozinfo.isWin:
+    envVar = "PATH"
+  if envVar:
+    envValue = ((env.get(envVar), str(ldLibraryPath))
+                if mozinfo.isWin
+                else (ldLibraryPath, env.get(envVar)))
+    env[envVar] = os.path.pathsep.join([path for path in envValue if path])
+
+  # crashreporter
+  env['GNOME_DISABLE_CRASH_DIALOG'] = '1'
+  env['XRE_NO_WINDOWS_CRASH_DIALOG'] = '1'
+  env['NS_TRACE_MALLOC_DISABLE_STACKS'] = '1'
+
+  if crashreporter:
+    env['MOZ_CRASHREPORTER_NO_REPORT'] = '1'
+    env['MOZ_CRASHREPORTER'] = '1'
+  else:
+    env['MOZ_CRASHREPORTER_DISABLE'] = '1'
+
+  # Additional temporary logging while we try to debug some intermittent
+  # WebRTC conditions. This is necessary to troubleshoot bugs 841496,
+  # 841150, and 839677 (at least)
+  # Also (temporary) bug 870002 (mediastreamgraph)
+  env.setdefault('NSPR_LOG_MODULES', 'signaling:5,mtransport:3')
+  env['R_LOG_LEVEL'] = '5'
+  env['R_LOG_DESTINATION'] = 'stderr'
+  env['R_LOG_VERBOSE'] = '1'
+
+  # ASan specific environment stuff
+  asan = bool(mozinfo.info.get("asan"))
+  if asan and (mozinfo.isLinux or mozinfo.isMac):
+    try:
+      totalMemory = systemMemory()
+
+      # Only 2 GB RAM or less available? Use custom ASan options to reduce
+      # the amount of resources required to do the tests. Standard options
+      # will otherwise lead to OOM conditions on the current test slaves.
+      #
+      # If we have more than 2 GB or RAM but still less than 4 GB, we need
+      # another set of options to prevent OOM in some memory-intensive
+      # tests.
+      message = "INFO | runtests.py | ASan running in %s configuration"
+      if totalMemory <= 1024 * 1024 * 2:
+        message = message % 'low-memory'
+        env["ASAN_OPTIONS"] = "quarantine_size=50331648:redzone=64"
+      elif totalMemory <= 1024 * 1024 * 4:
+        message = message % 'mid-memory'
+        env["ASAN_OPTIONS"] = "quarantine_size=100663296:redzone=64"
+      else:
+        message = message % 'default memory'
+    except OSError,err:
+      log.info("Failed determine available memory, disabling ASan low-memory configuration: %s", err.strerror)
+    except:
+      log.info("Failed determine available memory, disabling ASan low-memory configuration")
+    else:
+      log.info(message)
+
+  return env
new file mode 100644
--- /dev/null
+++ b/build/docs/build-overview.rst
@@ -0,0 +1,108 @@
+.. _build_overview:
+
+=====================
+Build System Overview
+=====================
+
+This document provides an overview on how the build system works. It is
+targeted at people wanting to learn about internals of the build system.
+It is not meant for persons who casually interact with the build system.
+That being said, knowledge empowers, so consider reading on.
+
+The build system is composed of many different components working in
+harmony to build the source tree. We begin with a graphic overview.
+
+.. graphviz::
+
+   digraph build_components {
+      rankdir="LR";
+      "configure" -> "config.status" -> "build backend" -> "build output"
+   }
+
+Phase 1: Configuration
+======================
+
+Phase 1 centers around the configure script, which is a bash shell script.
+The file is generated from a file called configure.in which is written in M4
+and processed using Autoconf 2.13 to create the final configure script.
+You don't have to worry about how you obtain a configure file: the build system
+does this for you.
+
+The primary job of configure is to determine characteristics of the system and
+compiler, apply options passed into it, and validate everything looks OK to
+build. The primary output of the configure script is an executable file in the
+object directory called config.status. configure also produces some additional
+files (like autoconf.mk). However, the most important file in terms of
+architecture is config.status.
+
+The existence of a config.status file may be familiar to those who have worked
+with Autoconf before. However, Mozilla's config.status is different from almost
+any other config.status you've ever seen: it's written in Python! Instead of
+having our configure script produce a shell script, we have it generating Python.
+
+Now is as good a time as any to mention that Python is prevalent in our build
+system. If we need to write code for the build system, we do it in Python.
+That's just how we roll.
+
+config.status contains 2 parts: data structures representing the output of
+configure and a command-line interface for preparing/configuring/generating
+an appropriate build backend. (A build backend is merely a tool used to build
+the tree - like GNU Make or Tup). These data structures essentially describe
+the current state of the system and what the existing build configuration looks
+like. For example, it defines which compiler to use, how to invoke it, which
+application features are enabled, etc. You are encouraged to open up
+config.status to have a look for yourself!
+
+Once we have emitted a config.status file, we pass into the realm of phase 2.
+
+Phase 2: Build Backend Preparation and the Build Definition
+===========================================================
+
+Once configure has determined what the current build configuration is, we need
+to apply this to the source tree so we can actually build.
+
+What essentially happens is the automatically-produced config.status Python
+script is executed as soon as configure has generated it. config.status is charged
+with the task of tell a tool had to build the tree. To do this, config.status
+must first scan the build system definition.
+
+The build system definition consists of various moz.build files in the tree.
+There is roughly one moz.build file per directory or pet set of related directories.
+Each moz.build files defines how its part of the build config works. For example it
+says I want these C++ files compiled or look for additional information in these
+directories. config.status starts with the main moz.build file and then recurses
+into all referenced files and directories. As the moz.build files are read, data
+structures describing the overall build system definition are emitted. These data
+structures are then read by a build backend generator which then converts them
+into files, function calls, etc. In the case of a `make` backend, the generator
+writes out Makefiles.
+
+When config.status runs, you'll see the following output::
+
+   Reticulating splines...
+   Finished reading 1096 moz.build files into 1276 descriptors in 2.40s
+   Backend executed in 2.39s
+   2188 total backend files. 0 created; 1 updated; 2187 unchanged
+   Total wall time: 5.03s; CPU time: 3.79s; Efficiency: 75%
+
+What this is saying is that a total of 1096 moz.build files were read. Altogether,
+1276 data structures describing the build configuration were derived from them.
+It took 2.40s wall time to just read these files and produce the data structures.
+The 1276 data structures were fed into the build backend which then determined it
+had to manage 2188 files derived from those data structures. Most of them
+already existed and didn't need changed. However, 1 was updated as a result of
+the new configuration. The whole process took 5.03s. Although, only 3.79s was in
+CPU time. That likely means we spent roughly 25% of the time waiting on I/O.
+
+Phase 3: Invokation of the Build Backend
+========================================
+
+When most people think of the build system, they think of phase 3. This is
+where we take all the code in the tree and produce Firefox or whatever
+application you are creating. Phase 3 effectively takes whatever was
+generated by phase 2 and runs it. Since the dawn of Mozilla, this has been
+make consuming Makefiles. However, with the transition to moz.build files,
+you may soon see non-Make build backends, such as Tup or Visual Studio.
+
+When building the tree, most of the time is spent in phase 3. This is when
+header files are installed, C++ files are compiled, files are preprocessed, etc.
--- a/build/docs/conf.py
+++ b/build/docs/conf.py
@@ -12,16 +12,17 @@ from datetime import datetime
 
 here = os.path.abspath(os.path.dirname(__file__))
 mozilla_dir = os.path.normpath(os.path.join(here, '..', '..'))
 
 import mdn_theme
 
 extensions = [
     'sphinx.ext.autodoc',
+    'sphinx.ext.graphviz',
 ]
 
 templates_path = ['_templates']
 source_suffix = '.rst'
 master_doc = 'index'
 project = u'Mozilla Build System'
 year = datetime.now().year
 copyright = u'%s, Mozilla Foundation, CC BY-SA 3.0' % year
new file mode 100644
--- /dev/null
+++ b/build/docs/environment-variables.rst
@@ -0,0 +1,44 @@
+.. _environment_variables:
+
+================================================
+Environment Variables Impacting the Build System
+================================================
+
+Various environment variables have an impact on the behavior of the
+build system. This document attempts to document them.
+
+AUTOCLOBBER
+   If defines, the build system will automatically clobber as needed.
+   The default behavior is to print a message and error out when a
+   clobber is needed.
+
+   This variable is typically defined in a :ref:`mozconfig <mozconfig>`
+   file via ``mk_add_options``.
+
+REBUILD_CHECK
+   If defined, the build system will print information about why
+   certain files were rebuilt.
+
+   This feature is disabled by default because it makes the build slower.
+
+MACH_NO_TERMINAL_FOOTER
+   If defined, the terminal footer displayed when building with mach in
+   a TTY is disabled.
+
+MACH_NO_WRITE_TIMES
+   If defined, mach commands will not prefix output lines with the
+   elapsed time since program start. This option is equivalent to
+   passing ``--log-no-times`` to mach.
+
+MOZ_PSEUDO_DERECURSE
+   Activate an *experimental* build mode where make directory traversal
+   is derecursified. This mode should result in faster build times at
+   the expense of busted builds from time-to-time. The end goal is for
+   this build mode to be the default. At which time, this variable will
+   likely go away.
+
+   A value of ``1`` activates the mode with full optimizations.
+
+   A value of ``no-parallel-export`` activates the mode without
+   optimizations to the *export* tier, which are known to be slightly
+   buggy.
--- a/build/docs/glossary.rst
+++ b/build/docs/glossary.rst
@@ -21,8 +21,24 @@ Glossary
        options, and writes out metadata to be consumed by the build
        system.
 
    config.status
        An executable file produced by **configure** that takes the
        generated build config and writes out files used to build the
        tree. Traditionally, config.status writes out a bunch of
        Makefiles.
+
+   install manifest
+       A file containing metadata describing file installation rules.
+       A large part of the build system consists of copying files
+       around to appropriate places. We write out special files
+       describing the set of required operations so we can process the
+       actions effeciently. These files are install manifests.
+
+   clobber build
+      A build performed with an initially empty object directory. All
+      build actions must be performed.
+
+   incremental build
+      A build performed with the result of a previous build in an
+      object directory. The build should not have to work as hard because
+      it will be able to reuse the work from previous builds.
--- a/build/docs/index.rst
+++ b/build/docs/index.rst
@@ -10,18 +10,21 @@ Overview
 
    glossary
 
 Important Concepts
 ==================
 .. toctree::
    :maxdepth: 1
 
+   build-overview
    Mozconfig Files <mozconfigs>
    Profile Guided Optimization <pgo>
+   slow
+   environment-variables
 
 mozbuild
 ========
 
 mozbuild is a Python package containing a lot of the code for the
 Mozilla build system.
 
 .. toctree::
--- a/build/docs/mozconfigs.rst
+++ b/build/docs/mozconfigs.rst
@@ -1,8 +1,10 @@
+.. _mozconfig:
+
 ===============
 mozconfig Files
 ===============
 
 mozconfig files are used to configure how a build works.
 
 mozconfig files are actually shell scripts. They are executed in a
 special context with specific variables and functions exposed to them.
new file mode 100644
--- /dev/null
+++ b/build/docs/slow.rst
@@ -0,0 +1,156 @@
+.. _slow:
+
+============================
+Why the Build System is Slow
+============================
+
+A common complaint about the build system is that it's slow. There are
+many reasons contributing to its slowness. We will attempt to document
+them here.
+
+First, it is important to distinguish between a :term:`clobber build`
+and an :term:`incremental build`. The reasons for why each are slow can
+be different.
+
+The build does a lot of work
+============================
+
+It may not be obvious, but the main reason the build system is slow is
+because it does a lot of work! The source tree consists of a few
+thousand C++ files. On a modern machine, we spend over 120 minutes of CPU
+core time compiling files! So, if you are looking for the root cause of
+slow clobber builds, look at the sheer volume of C++ files in the tree.
+
+You don't have enough CPU cores and MHz
+=======================================
+
+The build should be CPU bound. If the build system maintainers are
+optimizing the build system perfectly, every CPU core in your machine
+should be 100% saturated during a build. While this isn't currently the
+case (keep reading below), generally speaking, the more CPU cores you
+have in your machine and the more total MHz in your machine, the better.
+
+**We highly recommend building with no fewer than 4 physical CPU
+cores.** Please note the *physical* in this sentence. Hyperthreaded
+cores (an Intel Core i7 will report 8 CPU cores but only 4 are physical
+for example) only yield at most a 1.25x speedup per core.
+
+We also recommend using the most modern CPU model possible. Haswell
+chips deliver much more performance per CPU cycle than say Sandy Bridge
+CPUs.
+
+This cause impacts both clobber and incremental builds.
+
+You are building with a slow I/O layer
+======================================
+
+The build system can be I/O bound if your I/O layer is slow. Linking
+libxul on some platforms and build architectures can perform gigabytes
+of I/O.
+
+To minimize the impact of slow I/O on build performance, **we highly
+recommend building with an SSD.** Power users with enough memory may opt
+to build from a RAM disk. Mechanical disks should be avoided if at all
+possible.
+
+This cause impacts both clobber and incremental builds.
+
+You don't have enough memory
+============================
+
+The build system allocates a lot of memory, especially when building
+many things in parallel. If you don't have enough free system memory,
+the build will cause swap activity, slowing down your system and the
+build. Even if you never get to the point of swapping, the build system
+performs a lot of I/O and having all accessed files in memory and the
+page cache can significantly reduce the influence of the I/O layer on
+the build system.
+
+**We recommend building with no less than 8 GB of system memory.** As
+always, the more memory you have, the better. For a bare bones machine
+doing nothing more than building the source tree, anything more than 16
+GB is likely entering the point of diminishing returns.
+
+This cause impacts both clobber and incremental builds.
+
+You are building with pymake
+============================
+
+Pymake is slower than GNU make. One reason is Python is generally slower
+than C. The build system maintainers are consistently looking at
+optimizing pymake. However, it is death by a thousand cuts.
+
+This cause impacts both clobber and incremental builds.
+
+You are building on Windows
+===========================
+
+Builds on Windows are slow for a few reasons. First, Windows builds use
+pymake, not GNU make (because of compatibility issues with GNU make).
+But, there are other sources of slowness.
+
+New processes on Windows are about a magnitude slower to spawn than on
+UNIX-y systems such as Linux. This is because Windows has optimized new
+threads while the \*NIX platforms typically optimize new processes.
+Anyway, the build system spawns thousands of new processes during a
+build. Parts of the build that rely on rapid spawning of new processes
+are slow on Windows as a result. This is most pronounced when running
+*configure*. The configure file is a giant shell script and shell
+scripts rely heavily on new processes. This is why configure on Windows
+can run over a minute slower on Windows.
+
+Another reason Windows builds are slower is because Windows lacks proper
+symlink support. On systems that support symlinks, we can generate a
+file into a staging area then symlink it into the final directory very
+quickly. On Windows, we have to perform a full file copy. This incurs
+much more I/O. And if done poorly, can muck with file modification
+times, messing up build dependencies. As of the summer of 2013, the
+impact of symlinks is being mitigated through the use
+of an :term:`install manifest`.
+
+These issues impact both clobber and incremental builds.
+
+Recursive make traversal is slow
+================================
+
+The build system has traditionally been built by employing recursive
+make. Recursive make involves make iterating through directories / make
+files sequentially and executing each in turn. This is inefficient for
+directories containing few targets/tasks because make could be *starved*
+for work when processing these directories. Any time make is starved,
+the build isn't using all available CPU cycles and the build is slower
+as a result.
+
+Work has started in bug 907365 to fix this issue by changing the way
+make traverses all the make files.
+
+The impact of slow recursive make traversal is mostly felt on
+incremental builds. Traditionally, most of the wall time during a
+no-op build is spent in make traversal.
+
+make is inefficient
+===================
+
+Compared to modern build backends like Tup or Ninja, make is slow and
+inefficient. We can only make make so fast. At some point, we'll hit a
+performance plateau and will need to use a different tool to make builds
+faster.
+
+Please note that clobber and incremental builds are different. A clobber
+build with make will likely be as fast as a clobber build with e.g. Tup.
+However, Tup should vastly outperform make when it comes to incremental
+builds. Therefore, this issue is mostly seen when performing incremental
+builds.
+
+C++ header dependency hell
+==========================
+
+Modifying a *.h* file can have significant impact on the build system.
+If you modify a *.h* that is used by 1000 C++ files, all of those 1000
+C++ files will be recompiled.
+
+Our code base has traditionally been sloppy managing the impact of
+changed headers on build performance. Bug 785103 tracks improving the
+situation.
+
+This issue mostly impacts the times of an :term:`incremental build`.
--- a/build/mobile/robocop/Makefile.in
+++ b/build/mobile/robocop/Makefile.in
@@ -9,17 +9,17 @@ dir-tests    := $(DEPTH)/$(mobile-tests)
 ANDROID_APK_NAME := robocop-debug
 
 ROBOTIUM_PATH = $(srcdir)/robotium-solo-4.2.jar
 
 JAVAFILES = \
   R.java \
   $(NULL)
 
-RES_FILES = \
+ANDROID_RESFILES = \
   res/values/strings.xml \
   $(NULL)
 
 _JAVA_HARNESS = \
   Actions.java \
   Assert.java \
   Driver.java \
   Element.java \
--- a/build/mobile/sutagent/android/Makefile.in
+++ b/build/mobile/sutagent/android/Makefile.in
@@ -16,17 +16,17 @@ JAVAFILES = \
   RedirOutputThread.java \
   RunCmdThread.java \
   RunDataThread.java \
   SUTAgentAndroid.java \
   WifiConfiguration.java \
   R.java \
   $(NULL)
 
-RES_FILES = \
+ANDROID_RESFILES = \
   res/drawable/icon.png \
   res/drawable/ateamlogo.png \
   res/drawable/ic_stat_first.png \
   res/drawable/ic_stat_neterror.png \
   res/drawable/ic_stat_warning.png \
   res/layout/main.xml \
   res/values/strings.xml \
   $(NULL)
--- a/build/mobile/sutagent/android/fencp/Makefile.in
+++ b/build/mobile/sutagent/android/fencp/Makefile.in
@@ -7,17 +7,17 @@ ANDROID_APK_NAME := FenCP
 JAVAFILES = \
   DirCursor.java \
   FenCP.java \
   FenCPFP.java \
   FileCursor.java \
   R.java \
   $(NULL)
 
-RES_FILES = \
+ANDROID_RESFILES = \
   res/drawable-hdpi/icon.png \
   res/drawable-ldpi/icon.png \
   res/drawable-mdpi/icon.png \
   res/layout/main.xml \
   res/values/strings.xml \
   $(NULL)
 
 GARBAGE += \
--- a/build/mobile/sutagent/android/ffxcp/Makefile.in
+++ b/build/mobile/sutagent/android/ffxcp/Makefile.in
@@ -7,17 +7,17 @@ ANDROID_APK_NAME := FfxCP
 JAVAFILES = \
   DirCursor.java \
   ffxcp.java \
   FfxCPFP.java \
   FileCursor.java \
   R.java \
   $(NULL)
 
-RES_FILES = \
+ANDROID_RESFILES = \
   res/drawable-hdpi/icon.png \
   res/drawable-ldpi/icon.png \
   res/drawable-mdpi/icon.png \
   res/layout/main.xml \
   res/values/strings.xml \
   $(NULL)
 
 GARBAGE += \
--- a/build/mobile/sutagent/android/watcher/Makefile.in
+++ b/build/mobile/sutagent/android/watcher/Makefile.in
@@ -8,17 +8,17 @@ JAVAFILES = \
   IWatcherService.java \
   RedirOutputThread.java \
   R.java \
   WatcherMain.java \
   WatcherReceiver.java \
   WatcherService.java \
   $(NULL)
 
-RES_FILES = \
+ANDROID_RESFILES = \
   res/drawable-hdpi/icon.png \
   res/drawable-hdpi/ateamlogo.png \
   res/drawable-ldpi/icon.png \
   res/drawable-ldpi/ateamlogo.png \
   res/drawable-mdpi/icon.png \
   res/drawable-mdpi/ateamlogo.png \
   res/layout/main.xml \
   res/values/strings.xml \
--- a/caps/include/nsNullPrincipal.h
+++ b/caps/include/nsNullPrincipal.h
@@ -11,17 +11,16 @@
 
 #ifndef nsNullPrincipal_h__
 #define nsNullPrincipal_h__
 
 #include "nsIPrincipal.h"
 #include "nsJSPrincipals.h"
 #include "nsCOMPtr.h"
 #include "nsPrincipal.h"
-#include "nsIContentSecurityPolicy.h"
 
 class nsIURI;
 
 #define NS_NULLPRINCIPAL_CID \
 { 0xdd156d62, 0xd26f, 0x4441, \
  { 0x9c, 0xdb, 0xe8, 0xf0, 0x91, 0x07, 0xc2, 0x73 } }
 #define NS_NULLPRINCIPAL_CONTRACTID "@mozilla.org/nullprincipal;1"
 
@@ -49,12 +48,11 @@ public:
 #ifdef DEBUG
   virtual void dumpImpl() MOZ_OVERRIDE;
 #endif 
 
  protected:
   virtual ~nsNullPrincipal();
 
   nsCOMPtr<nsIURI> mURI;
-  nsCOMPtr<nsIContentSecurityPolicy> mCSP;
 };
 
 #endif // nsNullPrincipal_h__
--- a/caps/src/nsNullPrincipal.cpp
+++ b/caps/src/nsNullPrincipal.cpp
@@ -144,51 +144,49 @@ nsNullPrincipal::GetHashValue(uint32_t *
 {
   *aResult = (NS_PTR_TO_INT32(this) >> 2);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsNullPrincipal::GetSecurityPolicy(void** aSecurityPolicy)
 {
-  // We don't actually do security policy caching.
+  // We don't actually do security policy caching.  And it's not like anyone
+  // can set a security policy for us anyway.
   *aSecurityPolicy = nullptr;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsNullPrincipal::SetSecurityPolicy(void* aSecurityPolicy)
 {
-  // We don't actually do security policy caching.
+  // We don't actually do security policy caching.  And it's not like anyone
+  // can set a security policy for us anyway.
   return NS_OK;
 }
 
 NS_IMETHODIMP 
 nsNullPrincipal::GetURI(nsIURI** aURI)
 {
   return NS_EnsureSafeToReturn(mURI, aURI);
 }
 
 NS_IMETHODIMP
 nsNullPrincipal::GetCsp(nsIContentSecurityPolicy** aCsp)
 {
-  NS_IF_ADDREF(*aCsp = mCSP);
+  // CSP on a null principal makes no sense
+  *aCsp = nullptr;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsNullPrincipal::SetCsp(nsIContentSecurityPolicy* aCsp)
 {
-  // If CSP was already set, it should not be destroyed!  Instead, it should
-  // get set anew when a new principal is created.
-  if (mCSP)
-    return NS_ERROR_ALREADY_INITIALIZED;
-
-  mCSP = aCsp;
-  return NS_OK;
+  // CSP on a null principal makes no sense
+  return NS_ERROR_NOT_AVAILABLE;
 }
 
 NS_IMETHODIMP
 nsNullPrincipal::GetDomain(nsIURI** aDomain)
 {
   return NS_EnsureSafeToReturn(mURI, aDomain);
 }
 
--- a/chrome/src/RegistryMessageUtils.h
+++ b/chrome/src/RegistryMessageUtils.h
@@ -2,17 +2,17 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef mozilla_RegistryMessageUtils_h
 #define mozilla_RegistryMessageUtils_h
 
 #include "ipc/IPCMessageUtils.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 
 struct SerializedURI
 {
   nsCString spec;
   nsCString charset;
 };
 
 struct ChromePackage
--- a/chrome/src/nsChromeProtocolHandler.cpp
+++ b/chrome/src/nsChromeProtocolHandler.cpp
@@ -5,42 +5,30 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 /*
 
   A protocol handler for ``chrome:''
 
 */
 
-#include "nsAutoPtr.h"
 #include "nsChromeProtocolHandler.h"
 #include "nsChromeRegistry.h"
 #include "nsCOMPtr.h"
-#include "nsContentCID.h"
-#include "nsCRT.h"
 #include "nsThreadUtils.h"
 #include "nsIChannel.h"
 #include "nsIChromeRegistry.h"
-#include "nsIComponentManager.h"
 #include "nsIFile.h"
-#include "nsIFileURL.h"
 #include "nsIFileChannel.h"
 #include "nsIIOService.h"
-#include "nsIJARChannel.h"
-#include "nsIJARURI.h"
 #include "nsILoadGroup.h"
-#include "nsIObjectOutputStream.h"
 #include "nsIScriptSecurityManager.h"
-#include "nsIServiceManager.h"
 #include "nsIStandardURL.h"
-#include "nsIStreamListener.h"
 #include "nsNetUtil.h"
-#include "nsXPIDLString.h"
 #include "nsString.h"
-#include "prlog.h"
 
 ////////////////////////////////////////////////////////////////////////////////
 
 NS_IMPL_ISUPPORTS2(nsChromeProtocolHandler,
                    nsIProtocolHandler,
                    nsISupportsWeakReference)
 
 ////////////////////////////////////////////////////////////////////////////////
--- a/chrome/src/nsChromeRegistry.cpp
+++ b/chrome/src/nsChromeRegistry.cpp
@@ -3,43 +3,33 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsChromeRegistry.h"
 #include "nsChromeRegistryChrome.h"
 #include "nsChromeRegistryContent.h"
 
-#include <string.h>
-
-#include "prio.h"
 #include "prprf.h"
 
 #include "nsCOMPtr.h"
 #include "nsError.h"
 #include "nsEscape.h"
-#include "nsLayoutCID.h"
 #include "nsNetUtil.h"
 #include "nsString.h"
-#include "nsUnicharUtils.h"
 
 #include "nsCSSStyleSheet.h"
 #include "nsIConsoleService.h"
 #include "nsIDocument.h"
 #include "nsIDOMDocument.h"
-#include "nsIDocShell.h"
-#include "nsIDOMElement.h"
 #include "nsIDOMLocation.h"
 #include "nsIDOMWindowCollection.h"
 #include "nsIDOMWindow.h"
-#include "nsIIOService.h"
-#include "nsIJARProtocolHandler.h"
 #include "nsIObserverService.h"
 #include "nsIPresShell.h"
-#include "nsIProtocolHandler.h"
 #include "nsIScriptError.h"
 #include "nsIWindowMediator.h"
 
 nsChromeRegistry* nsChromeRegistry::gChromeRegistry;
 
 ////////////////////////////////////////////////////////////////////////////////
 
 void
--- a/chrome/src/nsChromeRegistry.h
+++ b/chrome/src/nsChromeRegistry.h
@@ -1,41 +1,34 @@
 /* -*- 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 nsChromeRegistry_h
 #define nsChromeRegistry_h
 
-#include "nsIChromeRegistry.h"
 #include "nsIToolkitChromeRegistry.h"
 #include "nsIObserver.h"
 #include "nsWeakReference.h"
-#include "nsIPrefBranch.h"
 
 #ifdef MOZ_XUL
 #include "nsIXULOverlayProvider.h"
 #endif
 
-#include "pldhash.h"
-
-#include "nsCOMArray.h"
 #include "nsString.h"
-#include "nsTHashtable.h"
 #include "nsURIHashKey.h"
 #include "nsInterfaceHashtable.h"
 #include "nsXULAppAPI.h"
-#include "nsIResProtocolHandler.h"
 #include "nsIXPConnect.h"
 
-#include "mozilla/Omnijar.h"
 #include "mozilla/FileLocation.h"
 
 class nsIDOMWindow;
+class nsIPrefBranch;
 class nsIURL;
 
 // The chrome registry is actually split between nsChromeRegistryChrome and
 // nsChromeRegistryContent. The work/data that is common to both resides in
 // the shared nsChromeRegistry implementation, with operations that only make
 // sense for one side erroring out in the other.
 
 // for component registration
--- a/chrome/src/nsChromeRegistryChrome.cpp
+++ b/chrome/src/nsChromeRegistryChrome.cpp
@@ -8,45 +8,37 @@
 #include "nsResProtocolHandler.h"
 
 #include "nsChromeRegistryChrome.h"
 
 #if defined(XP_WIN)
 #include <windows.h>
 #elif defined(XP_MACOSX)
 #include <CoreServices/CoreServices.h>
-#elif defined(MOZ_WIDGET_GTK)
-#include <gtk/gtk.h>
 #endif
 
 #include "nsArrayEnumerator.h"
-#include "nsAppDirectoryServiceDefs.h"
 #include "nsComponentManager.h"
 #include "nsEnumeratorUtils.h"
 #include "nsNetUtil.h"
 #include "nsStringEnumerator.h"
 #include "nsTextFormatter.h"
-#include "nsUnicharUtils.h"
 #include "nsXPCOMCIDInternal.h"
-#include "nsZipArchive.h"
 
 #include "mozilla/LookAndFeel.h"
 
 #include "nsICommandLine.h"
 #include "nsILocaleService.h"
-#include "nsIFile.h"
 #include "nsIObserverService.h"
 #include "nsIPrefBranch.h"
 #include "nsIPrefService.h"
 #include "mozilla/Preferences.h"
 #include "nsIResProtocolHandler.h"
 #include "nsIScriptError.h"
-#include "nsIVersionComparator.h"
 #include "nsIXPConnect.h"
-#include "nsIXULAppInfo.h"
 #include "nsIXULRuntime.h"
 
 #define UILOCALE_CMD_LINE_ARG "UILocale"
 
 #define MATCH_OS_LOCALE_PREF "intl.locale.matchOS"
 #define SELECTED_LOCALE_PREF "general.useragent.locale"
 #define SELECTED_SKIN_PREF   "general.skins.selectedSkin"
 #define PACKAGE_OVERRIDE_BRANCH "chrome.override_package."
--- a/chrome/src/nsChromeRegistryChrome.h
+++ b/chrome/src/nsChromeRegistryChrome.h
@@ -1,16 +1,17 @@
 /* -*- Mode: C++; tab-width: 8; 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 nsChromeRegistryChrome_h
 #define nsChromeRegistryChrome_h
 
+#include "nsCOMArray.h"
 #include "nsChromeRegistry.h"
 #include "nsVoidArray.h"
 #include "mozilla/Move.h"
 
 namespace mozilla {
 namespace dom {
 class PContentParent;
 }
--- a/chrome/src/nsChromeRegistryContent.cpp
+++ b/chrome/src/nsChromeRegistryContent.cpp
@@ -1,19 +1,18 @@
 /* -*- Mode: C++; tab-width: 8; 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 "RegistryMessageUtils.h"
-#include "nsChromeRegistry.h"
 #include "nsChromeRegistryContent.h"
 #include "nsString.h"
 #include "nsNetUtil.h"
-#include "nsResProtocolHandler.h"
+#include "nsIResProtocolHandler.h"
 
 nsChromeRegistryContent::nsChromeRegistryContent()
 {
 }
 
 void
 nsChromeRegistryContent::RegisterRemoteChrome(
     const InfallibleTArray<ChromePackage>& aPackages,
--- a/chrome/src/nsChromeRegistryContent.h
+++ b/chrome/src/nsChromeRegistryContent.h
@@ -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/. */
 
 #ifndef nsChromeRegistryContent_h
 #define nsChromeRegistryContent_h
 
 #include "nsChromeRegistry.h"
-#include "nsTArray.h"
 #include "nsClassHashtable.h"
 
-class nsCString;
 struct ChromePackage;
 struct ResourceMapping;
 struct OverrideMapping;
 
 class nsChromeRegistryContent : public nsChromeRegistry
 {
  public:
   nsChromeRegistryContent();
--- a/config/config.mk
+++ b/config/config.mk
@@ -792,18 +792,18 @@ EXPAND_LIBNAME = $(foreach lib,$(1),$(LI
 endif
 EXPAND_LIBNAME_PATH = $(foreach lib,$(1),$(2)/$(LIB_PREFIX)$(lib).$(LIB_SUFFIX))
 EXPAND_MOZLIBNAME = $(foreach lib,$(1),$(DIST)/lib/$(LIB_PREFIX)$(lib).$(LIB_SUFFIX))
 
 PLY_INCLUDE = -I$(topsrcdir)/other-licenses/ply
 
 export CL_INCLUDES_PREFIX
 
-ifeq ($(MOZ_WIDGET_GTK),2)
-MOZ_GTK2_CFLAGS := -I$(topsrcdir)/widget/gtk2/compat $(MOZ_GTK2_CFLAGS)
+ifdef MOZ_GTK2_CFLAGS
+MOZ_GTK2_CFLAGS := -I$(topsrcdir)/widget/gtk/compat $(MOZ_GTK2_CFLAGS)
 endif
 
 DEFINES += -DNO_NSPR_10_SUPPORT
 
 # Run a named Python build action. The first argument is the name of the build
 # action. The second argument are the arguments to pass to the action (space
 # delimited arguments). e.g.
 #
--- a/config/makefiles/java-build.mk
+++ b/config/makefiles/java-build.mk
@@ -2,26 +2,26 @@
 # vim:set ts=8 sw=8 sts=8 noet:
 #
 # 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 INCLUDED_JAVA_BUILD_MK #{
 
-ifdef RES_FILES #{
+ifdef ANDROID_RESFILES #{
 res-dep := .deps-copy-java-res
 
 GENERATED_DIRS += res
 GARBAGE        += $(res-dep)
 
 export:: $(res-dep)
 
 res-dep-preqs := \
-  $(addprefix $(srcdir)/,$(RES_FILES)) \
+  $(addprefix $(srcdir)/,$(ANDROID_RESFILES)) \
   $(call mkdir_deps,res) \
   $(if $(IS_LANGUAGE_REPACK),FORCE) \
   $(NULL)
 
 # nop-build: only copy res/ files when needed
 $(res-dep): $(res-dep-preqs)
 	$(call copy_dir,$(srcdir)/res,$(CURDIR)/res)
 	@$(TOUCH) $@
--- a/config/rules.mk
+++ b/config/rules.mk
@@ -1220,17 +1220,17 @@ non-root-path = $(shell echo $(1) | sed 
 normalizepath = $(foreach p,$(1),$(if $(filter /%,$(1)),$(patsubst %/,%,$(shell cd $(call root-path,$(1)) && pwd -W))/$(call non-root-path,$(1)),$(1)))
 else
 normalizepath = $(1)
 endif
 
 ###############################################################################
 # Java rules
 ###############################################################################
-ifneq (,$(value JAVAFILES)$(value RESFILES))
+ifneq (,$(value JAVAFILES)$(value ANDROID_RESFILES))
   include $(topsrcdir)/config/makefiles/java-build.mk
 endif
 
 ###############################################################################
 # Update Files Managed by Build Backend
 ###############################################################################
 
 ifndef NO_MAKEFILE_RULE
--- a/content/base/src/DOMImplementation.h
+++ b/content/base/src/DOMImplementation.h
@@ -11,17 +11,17 @@
 #include "mozilla/Attributes.h"
 #include "mozilla/ErrorResult.h"
 #include "nsCOMPtr.h"
 #include "nsCycleCollectionParticipant.h"
 #include "nsIDocument.h"
 #include "nsIScriptGlobalObject.h"
 #include "nsIURI.h"
 #include "nsIWeakReferenceUtils.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 
 class nsIDOMDocument;
 
 namespace mozilla {
 namespace dom {
 class DocumentType;
 
 class DOMImplementation MOZ_FINAL : public nsIDOMDOMImplementation
--- a/content/base/src/contentSecurityPolicy.js
+++ b/content/base/src/contentSecurityPolicy.js
@@ -44,19 +44,19 @@ Cu.import("resource://gre/modules/CSPUti
 function ContentSecurityPolicy() {
   CSPdebug("CSP CREATED");
   this._isInitialized = false;
 
   this._policies = [];
 
   this._request = "";
   this._requestOrigin = "";
-  this._weakRequestPrincipal = null;
+  this._requestPrincipal = "";
   this._referrer = "";
-  this._weakDocRequest = { get : function() { return null; } };
+  this._docRequest = null;
   CSPdebug("CSP object initialized, no policies to enforce yet");
 
   this._cache = { };
 }
 
 /*
  * Set up mappings from nsIContentPolicy content types to CSP directives.
  */
@@ -244,30 +244,29 @@ ContentSecurityPolicy.prototype = {
    * Given an nsIHttpChannel, fill out the appropriate data.
    */
   scanRequestData:
   function(aChannel) {
     if (!aChannel)
       return;
 
     // Save the docRequest for fetching a policy-uri
-    this._weakDocRequest = Cu.getWeakReference(aChannel);
+    this._docRequest = aChannel;
 
     // save the document URI (minus <fragment>) and referrer for reporting
     let uri = aChannel.URI.cloneIgnoringRef();
     try { // GetUserPass throws for some protocols without userPass
       uri.userPass = '';
     } catch (ex) {}
     this._request = uri.asciiSpec;
     this._requestOrigin = uri;
 
     //store a reference to the principal, that can later be used in shouldLoad
-    this._weakRequestPrincipal = Cu.getWeakReference(Cc["@mozilla.org/scriptsecuritymanager;1"]
-                                                       .getService(Ci.nsIScriptSecurityManager)
-                                                       .getChannelPrincipal(aChannel));
+    this._requestPrincipal = Components.classes["@mozilla.org/scriptsecuritymanager;1"].
+    getService(Components.interfaces.nsIScriptSecurityManager).getChannelPrincipal(aChannel);
 
     if (aChannel.referrer) {
       let referrer = aChannel.referrer.cloneIgnoringRef();
       try { // GetUserPass throws for some protocols without userPass
         referrer.userPass = '';
       } catch (ex) {}
       this._referrer = referrer.asciiSpec;
     }
@@ -306,23 +305,23 @@ ContentSecurityPolicy.prototype = {
     // CSPSource only the scheme, host, and port are kept.
 
     // If we want to be CSP 1.0 spec compliant, use the new parser.
     // The old one will be deprecated in the future and will be
     // removed at that time.
     if (aSpecCompliant) {
       newpolicy = CSPRep.fromStringSpecCompliant(aPolicy,
                                                  selfURI,
-                                                 this._weakDocRequest.get(),
+                                                 this._docRequest,
                                                  this,
                                                  aReportOnly);
     } else {
       newpolicy = CSPRep.fromString(aPolicy,
                                     selfURI,
-                                    this._weakDocRequest.get(),
+                                    this._docRequest,
                                     this,
                                     aReportOnly);
     }
 
     newpolicy._specCompliant = !!aSpecCompliant;
     newpolicy._isInitialized = true;
     this._policies.push(newpolicy);
     this._cache = {}; // reset cache since effective policy changes
@@ -430,18 +429,18 @@ ContentSecurityPolicy.prototype = {
 
           // make sure this is an anonymous request (no cookies) so in case the
           // policy URI is injected, it can't be abused for CSRF.
           chan.loadFlags |= Ci.nsIChannel.LOAD_ANONYMOUS;
 
           // we need to set an nsIChannelEventSink on the channel object
           // so we can tell it to not follow redirects when posting the reports
           chan.notificationCallbacks = new CSPReportRedirectSink(policy);
-          if (this._weakDocRequest.get()) {
-            chan.loadGroup = this._weakDocRequest.get().loadGroup;
+          if (this._docRequest) {
+            chan.loadGroup = this._docRequest.loadGroup;
           }
 
           chan.QueryInterface(Ci.nsIUploadChannel)
               .setUploadStream(content, "application/json", content.available());
 
           try {
             // if this is an HTTP channel, set the request method to post
             chan.QueryInterface(Ci.nsIHttpChannel);
@@ -450,17 +449,17 @@ ContentSecurityPolicy.prototype = {
 
           // check with the content policy service to see if we're allowed to
           // send this request.
           try {
             var contentPolicy = Cc["@mozilla.org/layout/content-policy;1"]
                                   .getService(Ci.nsIContentPolicy);
             if (contentPolicy.shouldLoad(Ci.nsIContentPolicy.TYPE_CSP_REPORT,
                                          chan.URI, this._requestOrigin,
-                                         null, null, null, this._weakRequestPrincipal.get())
+                                         null, null, null, this._requestPrincipal)
                 != Ci.nsIContentPolicy.ACCEPT) {
               continue; // skip unauthorized URIs
             }
           } catch(e) {
             continue; // refuse to load if we can't do a security check.
           }
 
           //send data (and set up error notifications)
--- a/content/base/src/nsAttrValue.h
+++ b/content/base/src/nsAttrValue.h
@@ -7,17 +7,17 @@
  * A struct that represents the value (type and actual data) of an
  * attribute.
  */
 
 #ifndef nsAttrValue_h___
 #define nsAttrValue_h___
 
 #include "nscore.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 #include "nsStringBuffer.h"
 #include "nsColor.h"
 #include "nsCaseTreatment.h"
 #include "nsMargin.h"
 #include "nsCOMPtr.h"
 #include "SVGAttrValueWrapper.h"
 #include "nsTArrayForwardDeclare.h"
 #include "nsIAtom.h"
--- a/content/base/src/nsContentList.h
+++ b/content/base/src/nsContentList.h
@@ -11,17 +11,17 @@
 
 #ifndef nsContentList_h___
 #define nsContentList_h___
 
 #include "mozilla/Attributes.h"
 #include "nsContentListDeclarations.h"
 #include "nsISupports.h"
 #include "nsTArray.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 #include "nsIHTMLCollection.h"
 #include "nsIDOMNodeList.h"
 #include "nsINodeList.h"
 #include "nsStubMutationObserver.h"
 #include "nsIAtom.h"
 #include "nsINameSpaceManager.h"
 #include "nsCycleCollectionParticipant.h"
 #include "nsWrapperCache.h"
--- a/content/base/src/nsCopySupport.cpp
+++ b/content/base/src/nsCopySupport.cpp
@@ -34,16 +34,17 @@
 #include "nsIDOMNode.h"
 #include "nsIDOMElement.h"
 #include "nsIDOMDocument.h"
 #include "nsIHTMLDocument.h"
 #include "nsGkAtoms.h"
 #include "nsGUIEvent.h"
 #include "nsIFrame.h"
 #include "nsIURI.h"
+#include "nsISimpleEnumerator.h"
 
 // image copy stuff
 #include "nsIImageLoadingContent.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsContentUtils.h"
 #include "nsContentCID.h"
 
 #include "mozilla/dom/Element.h"
--- a/content/base/src/nsDOMAttributeMap.h
+++ b/content/base/src/nsDOMAttributeMap.h
@@ -11,17 +11,17 @@
 #define nsDOMAttributeMap_h
 
 #include "mozilla/MemoryReporting.h"
 #include "mozilla/dom/Attr.h"
 #include "mozilla/ErrorResult.h"
 #include "nsCycleCollectionParticipant.h"
 #include "nsIDOMMozNamedAttrMap.h"
 #include "nsRefPtrHashtable.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 #include "nsWrapperCache.h"
 
 class nsIAtom;
 class nsINodeInfo;
 class nsIDocument;
 
 /**
  * Structure used as a key for caching Attrs in nsDOMAttributeMap's mAttributeCache.
--- a/content/base/src/nsDocument.cpp
+++ b/content/base/src/nsDocument.cpp
@@ -2676,18 +2676,17 @@ nsDocument::InitCSP(nsIChannel* aChannel
       // stop!  ERROR page!
       aChannel->Cancel(NS_ERROR_CSP_FRAME_ANCESTOR_VIOLATION);
     }
   }
 
   if (csp) {
     // Copy into principal
     nsIPrincipal* principal = GetPrincipal();
-    rv = principal->SetCsp(csp);
-    NS_ENSURE_SUCCESS(rv, rv);
+    principal->SetCsp(csp);
 #ifdef PR_LOGGING
     PR_LOG(gCspPRLog, PR_LOG_DEBUG,
            ("Inserted CSP into principal %p", principal));
 #endif
   }
 
   return NS_OK;
 }
--- a/content/base/src/nsInProcessTabChildGlobal.cpp
+++ b/content/base/src/nsInProcessTabChildGlobal.cpp
@@ -15,16 +15,17 @@
 #include "nsComponentManagerUtils.h"
 #include "nsNetUtil.h"
 #include "nsScriptLoader.h"
 #include "nsFrameLoader.h"
 #include "xpcpublic.h"
 #include "nsIMozBrowserFrame.h"
 #include "nsDOMClassInfoID.h"
 #include "mozilla/dom/StructuredCloneUtils.h"
+#include "js/StructuredClone.h"
 
 using mozilla::dom::StructuredCloneData;
 using mozilla::dom::StructuredCloneClosure;
 
 bool
 nsInProcessTabChildGlobal::DoSendSyncMessage(JSContext* aCx,
                                              const nsAString& aMessage,
                                              const mozilla::dom::StructuredCloneData& aData,
--- a/content/base/test/csp/Makefile.in
+++ b/content/base/test/csp/Makefile.in
@@ -92,29 +92,16 @@ MOCHITEST_FILES := \
   test_CSP_bug888172.html \
   file_CSP_bug888172.html \
   file_CSP_bug888172.sjs \
   test_bug836922_npolicies.html \
   file_bug836922_npolicies.html \
   file_bug836922_npolicies.html^headers^ \
   file_bug836922_npolicies_violation.sjs \
   file_bug836922_npolicies_ro_violation.sjs \
-  test_bug886164.html \
-  file_bug886164.html \
-  file_bug886164.html^headers^ \
-  file_bug886164_2.html \
-  file_bug886164_2.html^headers^ \
-  file_bug886164_3.html \
-  file_bug886164_3.html^headers^ \
-  file_bug886164_4.html \
-  file_bug886164_4.html^headers^ \
-  file_bug886164_5.html \
-  file_bug886164_5.html^headers^ \
-  file_bug886164_6.html \
-  file_bug886164_6.html^headers^ \
   test_CSP_bug916446.html \
   file_CSP_bug916446.html \
   file_CSP_bug916446.html^headers^ \
   $(NULL)
 
 MOCHITEST_CHROME_FILES := \
   test_csp_bug768029.html \
   test_csp_bug773891.html \
deleted file mode 100644
--- a/content/base/test/csp/file_bug886164.html
+++ /dev/null
@@ -1,15 +0,0 @@
-<html>
-<head> <meta charset="utf-8"> </head>
-  <body>
-    <!-- sandbox="allow-same-origin" -->
-    <!-- Content-Security-Policy: default-src 'self' -->
-
-    <!-- these should be stopped by CSP -->
-    <img src="http://example.org/tests/content/base/test/csp/file_CSP.sjs?testid=img_bad&type=img/png"> </img>
-
-    <!-- these should load ok -->
-    <img src="/tests/content/base/test/csp/file_CSP.sjs?testid=img_good&type=img/png" />
-    <script src='/tests/content/base/test/csp/file_CSP.sjs?testid=scripta_bad&type=text/javascript'></script>
-
-  </body>
-</html>
deleted file mode 100644
--- a/content/base/test/csp/file_bug886164.html^headers^
+++ /dev/null
@@ -1,1 +0,0 @@
-Content-Security-Policy: default-src 'self'
deleted file mode 100644
--- a/content/base/test/csp/file_bug886164_2.html
+++ /dev/null
@@ -1,14 +0,0 @@
-<html>
-<head> <meta charset="utf-8"> </head>
-  <body>
-    <!-- sandbox -->
-    <!-- Content-Security-Policy: default-src 'self' -->
-
-    <!-- these should be stopped by CSP -->
-    <img src="http://example.org/tests/content/base/test/csp/file_CSP.sjs?testid=img2_bad&type=img/png"> </img>
-
-    <!-- these should load ok -->
-    <img src="/tests/content/base/test/csp/file_CSP.sjs?testid=img2a_good&type=img/png" />
-
-  </body>
-</html>
deleted file mode 100644
--- a/content/base/test/csp/file_bug886164_2.html^headers^
+++ /dev/null
@@ -1,1 +0,0 @@
-Content-Security-Policy: default-src 'self'
deleted file mode 100644
--- a/content/base/test/csp/file_bug886164_3.html
+++ /dev/null
@@ -1,12 +0,0 @@
-<html>
-<head> <meta charset="utf-8"> </head>
-  <body>
-    <!-- sandbox -->
-    <!-- Content-Security-Policy: default-src 'none' -->
-
-    <!-- these should be stopped by CSP -->
-    <img src="http://example.org/tests/content/base/test/csp/file_CSP.sjs?testid=img3_bad&type=img/png"> </img>
-    <img src="/tests/content/base/test/csp/file_CSP.sjs?testid=img3a_bad&type=img/png" />
-
-  </body>
-</html>
deleted file mode 100644
--- a/content/base/test/csp/file_bug886164_3.html^headers^
+++ /dev/null
@@ -1,1 +0,0 @@
-Content-Security-Policy: default-src 'none'
deleted file mode 100644
--- a/content/base/test/csp/file_bug886164_4.html
+++ /dev/null
@@ -1,12 +0,0 @@
-<html>
-<head> <meta charset="utf-8"> </head>
-  <body>
-    <!-- sandbox -->
-    <!-- Content-Security-Policy: default-src 'none' -->
-
-    <!-- these should be stopped by CSP -->
-    <img src="http://example.org/tests/content/base/test/csp/file_CSP.sjs?testid=img4_bad&type=img/png"> </img>
-    <img src="/tests/content/base/test/csp/file_CSP.sjs?testid=img4a_bad&type=img/png" />
-
-  </body>
-</html>
deleted file mode 100644
--- a/content/base/test/csp/file_bug886164_4.html^headers^
+++ /dev/null
@@ -1,1 +0,0 @@
-Content-Security-Policy: default-src 'none'
deleted file mode 100644
--- a/content/base/test/csp/file_bug886164_5.html
+++ /dev/null
@@ -1,26 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head> <meta charset="utf-8"> </head>
-<script type="text/javascript">
-  function ok(result, desc) {
-    window.parent.postMessage({ok: result, desc: desc}, "*");
-  }
-
-  function doStuff() {
-    ok(true, "documents sandboxed with allow-scripts should be able to run inline scripts");
-  }
-</script>
-<script src='file_iframe_sandbox_pass.js'></script>
-<body onLoad='ok(true, "documents sandboxed with allow-scripts should be able to run script from event listeners");doStuff();'>
-  I am sandboxed but with only inline "allow-scripts"
-
- <!-- sandbox="allow-scripts" -->
- <!-- Content-Security-Policy: default-src 'none' 'unsafe-inline'-->
-
- <!-- these should be stopped by CSP -->
- <img src="/tests/content/base/test/csp/file_CSP.sjs?testid=img5_bad&type=img/png" />
- <img src="http://example.org/tests/content/base/test/csp/file_CSP.sjs?testid=img5a_bad&type=img/png"> </img>
- <script src='/tests/content/base/test/csp/file_CSP.sjs?testid=script5_bad&type=text/javascript'></script>
- <script src='http://example.org/tests/content/base/test/csp/file_CSP.sjs?testid=script5a_bad&type=text/javascript'></script>
-</body>
-</html>
deleted file mode 100644
--- a/content/base/test/csp/file_bug886164_5.html^headers^
+++ /dev/null
@@ -1,1 +0,0 @@
-Content-Security-Policy: default-src 'none' 'unsafe-inline';
deleted file mode 100644
--- a/content/base/test/csp/file_bug886164_6.html
+++ /dev/null
@@ -1,35 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
-  <meta charset="utf-8">
-  <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
-</head>
-<script type="text/javascript">
-  function ok(result, desc) {
-    window.parent.postMessage({ok: result, desc: desc}, "*");
-  }
-
-  function doStuff() {
-    ok(true, "documents sandboxed with allow-scripts should be able to run inline scripts");
-
-    document.getElementById('a_form').submit();
-
-    // trigger the javascript: url test
-    sendMouseEvent({type:'click'}, 'a_link');
-  }
-</script>
-<script src='file_iframe_sandbox_pass.js'></script>
-<body onLoad='ok(true, "documents sandboxed with allow-scripts should be able to run script from event listeners");doStuff();'>
-  I am sandboxed but with "allow-scripts"
-  <img src="http://example.org/tests/content/base/test/csp/file_CSP.sjs?testid=img6_bad&type=img/png"> </img>
-  <script src='http://example.org/tests/content/base/test/csp/file_CSP.sjs?testid=script6_bad&type=text/javascript'></script>
-
-  <form method="get" action="file_iframe_sandbox_form_fail.html" id="a_form">
-    First name: <input type="text" name="firstname">
-    Last name: <input type="text" name="lastname">
-    <input type="submit" onclick="doSubmit()" id="a_button">
-  </form>
-
-  <a href = 'javascript:ok(true, "documents sandboxed with allow-scripts should be able to run script from javascript: URLs");' id='a_link'>click me</a>
-</body>
-</html>
deleted file mode 100644
--- a/content/base/test/csp/file_bug886164_6.html^headers^
+++ /dev/null
@@ -1,1 +0,0 @@
-Content-Security-Policy: default-src 'self' 'unsafe-inline';
deleted file mode 100644
--- a/content/base/test/csp/test_bug886164.html
+++ /dev/null
@@ -1,185 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
-  <meta charset="utf-8">
-  <title>Bug 886164 - Enforce CSP in sandboxed iframe</title>
-  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
-  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-<p id="display"></p>
-<div id="content" style="display: none">
-
-
-</div>
-
-<iframe style="width:200px;height:200px;" id='cspframe'  sandbox="allow-same-origin"></iframe>
-<iframe style="width:200px;height:200px;" id='cspframe2' sandbox></iframe>
-<iframe style="width:200px;height:200px;" id='cspframe3' sandbox="allow-same-origin"></iframe>
-<iframe style="width:200px;height:200px;" id='cspframe4' sandbox></iframe>
-<iframe style="width:200px;height:200px;" id='cspframe5' sandbox="allow-scripts"></iframe>
-<iframe style="width:200px;height:200px;" id='cspframe6' sandbox="allow-same-origin allow-scripts"></iframe>
-<script class="testbody" type="text/javascript">
-
-
-var path = "/tests/content/base/test/csp/";
-
-// These are test results: -1 means it hasn't run,
-// true/false is the pass/fail result.
-window.tests = {
-  // sandbox allow-same-origin; 'self'
-  img_good: -1, // same origin
-  img_bad: -1, //example.com
-
-  // sandbox; 'self'
-  img2_bad: -1, //example.com
-  img2a_good: -1, // same origin & is image
-
-  // sandbox allow-same-origin; 'none'
-  img3_bad: -1,
-  img3a_bad: -1,
-
-  // sandbox; 'none'
-  img4_bad: -1,
-  img4a_bad: -1,
-
-  // sandbox allow-scripts; 'none' 'unsafe-inline'
-  img5_bad: -1,
-  img5a_bad: -1,
-  script5_bad: -1,
-  script5a_bad: -1,
-
-  // sandbox allow-same-origin allow-scripts; 'self' 'unsafe-inline'
-  img6_bad: -1,
-  script6_bad: -1,
-};
-
-// a postMessage handler that is used by sandboxed iframes without
-// 'allow-same-origin' to communicate pass/fail back to this main page.
-// it expects to be called with an object like {ok: true/false, desc:
-// <description of the test> which it then forwards to ok()
-window.addEventListener("message", receiveMessage, false);
-
-function receiveMessage(event)
-{
-  ok_wrapper(event.data.ok, event.data.desc);
-}
-
-var cspTestsDone = false;
-var iframeSandboxTestsDone = false;
-
-// iframe related
-var completedTests = 0;
-var passedTests = 0;
-
-function ok_wrapper(result, desc) {
-  ok(result, desc);
-
-  completedTests++;
-
-  if (result) {
-    passedTests++;
-  }
-
-  if (completedTests === 5) {
-    iframeSandboxTestsDone = true;
-    if (cspTestsDone) {
-      SimpleTest.finish();
-    }
-  }
-}
-
-
-//csp related
-
-// This is used to watch the blocked data bounce off CSP and allowed data
-// get sent out to the wire.
-function examiner() {
-  SpecialPowers.addObserver(this, "csp-on-violate-policy", false);
-  SpecialPowers.addObserver(this, "http-on-modify-request", false);
-}
-examiner.prototype  = {
-  observe: function(subject, topic, data) {
-    // subject should be an nsURI, and should be either allowed or blocked.
-    if (!SpecialPowers.can_QI(subject))
-      return;
-
-    var testpat = new RegExp("testid=([a-z0-9_]+)");
-
-    //_good things better be allowed!
-    //_bad things better be stopped!
-
-    if (topic === "http-on-modify-request") {
-      //these things were allowed by CSP
-      var asciiSpec = SpecialPowers.getPrivilegedProps(SpecialPowers.do_QueryInterface(subject, "nsIHttpChannel"), "URI.asciiSpec");
-      if (!testpat.test(asciiSpec)) return;
-      var testid = testpat.exec(asciiSpec)[1];
-
-      window.testResult(testid,
-                        /_good/.test(testid),
-                        asciiSpec + " allowed by csp");
-    }
-
-    if(topic === "csp-on-violate-policy") {
-      //these were blocked... record that they were blocked
-      var asciiSpec = SpecialPowers.getPrivilegedProps(SpecialPowers.do_QueryInterface(subject, "nsIURI"), "asciiSpec");
-      if (!testpat.test(asciiSpec)) return;
-      var testid = testpat.exec(asciiSpec)[1];
-      window.testResult(testid,
-                        /_bad/.test(testid),
-                        asciiSpec + " blocked by \"" + data + "\"");
-    }
-  },
-
-  // must eventually call this to remove the listener,
-  // or mochitests might get borked.
-  remove: function() {
-    SpecialPowers.removeObserver(this, "csp-on-violate-policy");
-    SpecialPowers.removeObserver(this, "http-on-modify-request");
-  }
-}
-
-window.examiner = new examiner();
-
-window.testResult = function(testname, result, msg) {
-  //test already complete.... forget it... remember the first result.
-  if (window.tests[testname] != -1)
-    return;
-
-  window.tests[testname] = result;
-  is(result, true, testname + ' test: ' + msg);
-
-  // if any test is incomplete, keep waiting
-  for (var v in window.tests)
-    if(tests[v] == -1) {
-      console.log(v + " is not complete");
-      return;
-    }
-
-  // ... otherwise, finish
-  window.examiner.remove();
-  cspTestsDone = true;
-  if (iframeSandboxTestsDone) {
-    SimpleTest.finish();
-  }
-}
-
-SimpleTest.waitForExplicitFinish();
-
-SpecialPowers.pushPrefEnv(
-  {'set':[["security.csp.speccompliant", true]]},
-  function() {
-    // save this for last so that our listeners are registered.
-    // ... this loads the testbed of good and bad requests.
-    document.getElementById('cspframe').src = 'file_bug886164.html';
-    document.getElementById('cspframe2').src = 'file_bug886164_2.html';
-    document.getElementById('cspframe3').src = 'file_bug886164_3.html';
-    document.getElementById('cspframe4').src = 'file_bug886164_4.html';
-    document.getElementById('cspframe5').src = 'file_bug886164_5.html';
-    document.getElementById('cspframe6').src = 'file_bug886164_6.html';
-  });
-
-</script>
-</pre>
-</body>
-</html>
--- a/content/events/src/nsDOMEvent.cpp
+++ b/content/events/src/nsDOMEvent.cpp
@@ -18,16 +18,17 @@
 #include "nsContentUtils.h"
 #include "nsJSEnvironment.h"
 #include "mozilla/Preferences.h"
 #include "nsLayoutUtils.h"
 #include "nsIScrollableFrame.h"
 #include "nsDOMEventTargetHelper.h"
 #include "nsPIWindowRoot.h"
 #include "nsGlobalWindow.h"
+#include "nsDeviceContext.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 static char *sPopupAllowedEvents;
 
 
 nsDOMEvent::nsDOMEvent(mozilla::dom::EventTarget* aOwner,
--- a/content/events/src/nsDOMUIEvent.h
+++ b/content/events/src/nsDOMUIEvent.h
@@ -7,17 +7,18 @@
 #define nsDOMUIEvent_h
 
 #include "mozilla/Attributes.h"
 #include "nsIDOMUIEvent.h"
 #include "nsDOMEvent.h"
 #include "nsLayoutUtils.h"
 #include "nsEvent.h"
 #include "mozilla/dom/UIEventBinding.h"
-#include "Units.h"
+#include "nsPresContext.h"
+#include "nsDeviceContext.h"
 
 class nsDOMUIEvent : public nsDOMEvent,
                      public nsIDOMUIEvent
 {
   typedef mozilla::CSSIntPoint CSSIntPoint;
 public:
   nsDOMUIEvent(mozilla::dom::EventTarget* aOwner,
                nsPresContext* aPresContext, nsGUIEvent* aEvent);
--- a/content/html/content/public/HTMLMediaElement.h
+++ b/content/html/content/public/HTMLMediaElement.h
@@ -525,16 +525,22 @@ public:
   already_AddRefed<TextTrack> AddTextTrack(TextTrackKind aKind,
                                            const nsAString& aLabel,
                                            const nsAString& aLanguage);
 
   void AddTextTrack(TextTrack* aTextTrack) {
     mTextTracks->AddTextTrack(aTextTrack);
   }
 
+  void RemoveTextTrack(TextTrack* aTextTrack) {
+    if (mTextTracks) {
+      mTextTracks->RemoveTextTrack(*aTextTrack);
+    }
+  }
+
 protected:
   class MediaLoadListener;
   class StreamListener;
 
   virtual void GetItemValueText(nsAString& text) MOZ_OVERRIDE;
   virtual void SetItemValueText(const nsAString& text) MOZ_OVERRIDE;
 
   class WakeLockBoolWrapper {
--- a/content/html/content/src/HTMLTrackElement.cpp
+++ b/content/html/content/src/HTMLTrackElement.cpp
@@ -285,17 +285,24 @@ HTMLTrackElement::BindToTree(nsIDocument
   }
 
   return NS_OK;
 }
 
 void
 HTMLTrackElement::UnbindFromTree(bool aDeep, bool aNullParent)
 {
-  if (mMediaParent && aNullParent) {
-    mMediaParent = nullptr;
+  if (mMediaParent) {
+    // mTrack can be null if HTMLTrackElement::LoadResource has never been
+    // called.
+    if (mTrack) {
+      mMediaParent->RemoveTextTrack(mTrack);
+    }
+    if (aNullParent) {
+      mMediaParent = nullptr;
+    }
   }
 
   nsGenericHTMLElement::UnbindFromTree(aDeep, aNullParent);
 }
 
 } // namespace dom
 } // namespace mozilla
--- a/content/media/TextTrack.cpp
+++ b/content/media/TextTrack.cpp
@@ -68,25 +68,23 @@ void
 TextTrack::SetMode(TextTrackMode aValue)
 {
   mMode = aValue;
 }
 
 void
 TextTrack::AddCue(TextTrackCue& aCue)
 {
-  //XXX: If cue exists, remove. Bug 867823.
   mCueList->AddCue(aCue);
 }
 
 void
-TextTrack::RemoveCue(TextTrackCue& aCue)
+TextTrack::RemoveCue(TextTrackCue& aCue, ErrorResult& aRv)
 {
-  //XXX: If cue does not exists throw NotFoundError. Bug 867823.
-  mCueList->RemoveCue(aCue);
+  mCueList->RemoveCue(aCue, aRv);
 }
 
 void
 TextTrack::CueChanged(TextTrackCue& aCue)
 {
   //XXX: Implement Cue changed. Bug 867823.
 }
 
--- a/content/media/TextTrack.h
+++ b/content/media/TextTrack.h
@@ -94,17 +94,17 @@ public:
 
   void AddRegion(TextTrackRegion& aRegion);
   void RemoveRegion(const TextTrackRegion& aRegion, ErrorResult& aRv);
 
   // Time is in seconds.
   void Update(double aTime);
 
   void AddCue(TextTrackCue& aCue);
-  void RemoveCue(TextTrackCue& aCue);
+  void RemoveCue(TextTrackCue& aCue, ErrorResult& aRv);
   void CueChanged(TextTrackCue& aCue);
 
   IMPL_EVENT_HANDLER(cuechange)
 
 private:
   nsCOMPtr<nsISupports> mParent;
 
   TextTrackKind mKind;
--- a/content/media/TextTrackCue.h
+++ b/content/media/TextTrackCue.h
@@ -111,16 +111,31 @@ public:
   {
     if (mPauseOnExit == aPauseOnExit)
       return;
 
     mPauseOnExit = aPauseOnExit;
     CueChanged();
   }
 
+  void GetRegionId(nsAString& aRegionId) const
+  {
+    aRegionId = mRegionId;
+  }
+
+  void SetRegionId(const nsAString& aRegionId)
+  {
+    if (mRegionId == aRegionId) {
+      return;
+    }
+
+    mRegionId = aRegionId;
+    CueChanged();
+  }
+
   DirectionSetting Vertical() const
   {
     return mVertical;
   }
 
   void SetVertical(const DirectionSetting& aVertical)
   {
     if (mVertical == aVertical)
@@ -299,16 +314,17 @@ private:
 
   nsRefPtr<TextTrack> mTrack;
   nsRefPtr<HTMLTrackElement> mTrackElement;
   nsString mId;
   int32_t mPosition;
   int32_t mSize;
   bool mPauseOnExit;
   bool mSnapToLines;
+  nsString mRegionId;
   DirectionSetting mVertical;
   int mLine;
   TextTrackCueAlign mAlign;
 
   // Holds the computed DOM elements that represent the parsed cue text.
   // http://www.whatwg.org/specs/web-apps/current-work/#text-track-cue-display-state
   nsCOMPtr<nsIContent> mDisplayState;
   // Tells whether or not we need to recompute mDisplayState. This is set
--- a/content/media/TextTrackCueList.cpp
+++ b/content/media/TextTrackCueList.cpp
@@ -61,19 +61,26 @@ TextTrackCueList::GetCueById(const nsASt
     }
   }
   return nullptr;
 }
 
 void
 TextTrackCueList::AddCue(TextTrackCue& cue)
 {
+  if (mList.Contains(&cue)) {
+    return;
+  }
   mList.AppendElement(&cue);
 }
 
 void
-TextTrackCueList::RemoveCue(TextTrackCue& cue)
+TextTrackCueList::RemoveCue(TextTrackCue& cue, ErrorResult& aRv)
 {
+  if (!mList.Contains(&cue)) {
+    aRv.Throw(NS_ERROR_DOM_NOT_FOUND_ERR);
+    return;
+  }
   mList.RemoveElement(&cue);
 }
 
 } // namespace dom
 } // namespace mozilla
--- a/content/media/TextTrackCueList.h
+++ b/content/media/TextTrackCueList.h
@@ -6,16 +6,17 @@
 
 #ifndef mozilla_dom_TextTrackCueList_h
 #define mozilla_dom_TextTrackCueList_h
 
 #include "nsTArray.h"
 #include "nsCOMPtr.h"
 #include "nsCycleCollectionParticipant.h"
 #include "nsWrapperCache.h"
+#include "mozilla/ErrorResult.h"
 
 namespace mozilla {
 namespace dom {
 
 class TextTrackCue;
 
 class TextTrackCueList MOZ_FINAL : public nsISupports
                                  , public nsWrapperCache
@@ -42,17 +43,17 @@ public:
 
   // Time is in seconds.
   void Update(double aTime);
 
   TextTrackCue* IndexedGetter(uint32_t aIndex, bool& aFound);
   TextTrackCue* GetCueById(const nsAString& aId);
 
   void AddCue(TextTrackCue& cue);
-  void RemoveCue(TextTrackCue& cue);
+  void RemoveCue(TextTrackCue& cue, ErrorResult& aRv);
 
 private:
   nsCOMPtr<nsISupports> mParent;
 
   nsTArray< nsRefPtr<TextTrackCue> > mList;
 };
 
 } // namespace dom
--- a/content/media/TextTrackRegion.cpp
+++ b/content/media/TextTrackRegion.cpp
@@ -1,33 +1,33 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim:set ts=2 sw=2 et tw=78: */
 /* 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/TextTrack.h"
 #include "mozilla/dom/TextTrackRegion.h"
-#include "mozilla/dom/TextTrackRegionBinding.h"
+#include "mozilla/dom/VTTRegionBinding.h"
 
 namespace mozilla {
 namespace dom {
 
 NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE_2(TextTrackRegion, mParent, mTrack)
 NS_IMPL_CYCLE_COLLECTING_ADDREF(TextTrackRegion)
 NS_IMPL_CYCLE_COLLECTING_RELEASE(TextTrackRegion)
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(TextTrackRegion)
   NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
   NS_INTERFACE_MAP_ENTRY(nsISupports)
 NS_INTERFACE_MAP_END
 
 JSObject*
 TextTrackRegion::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aScope)
 {
-  return TextTrackRegionBinding::Wrap(aCx, aScope, this);
+  return VTTRegionBinding::Wrap(aCx, aScope, this);
 }
 
 already_AddRefed<TextTrackRegion>
 TextTrackRegion::Constructor(const GlobalObject& aGlobal, ErrorResult& aRv)
 {
   nsCOMPtr<nsPIDOMWindow> window = do_QueryInterface(aGlobal.GetAsSupports());
   if (!window) {
     aRv.Throw(NS_ERROR_FAILURE);
--- a/content/media/TextTrackRegionList.cpp
+++ b/content/media/TextTrackRegionList.cpp
@@ -1,16 +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/. */
 
 #include "mozilla/dom/TextTrackRegion.h"
 #include "mozilla/dom/TextTrackRegionList.h"
-#include "mozilla/dom/TextTrackRegionListBinding.h"
+#include "mozilla/dom/VTTRegionListBinding.h"
 
 namespace mozilla {
 namespace dom {
 
 NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE_2(TextTrackRegionList,
                                         mParent,
                                         mTextTrackRegions)
 NS_IMPL_CYCLE_COLLECTING_ADDREF(TextTrackRegionList)
@@ -18,17 +18,17 @@ NS_IMPL_CYCLE_COLLECTING_RELEASE(TextTra
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(TextTrackRegionList)
   NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
   NS_INTERFACE_MAP_ENTRY(nsISupports)
 NS_INTERFACE_MAP_END
 
 JSObject*
 TextTrackRegionList::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aScope)
 {
-  return TextTrackRegionListBinding::Wrap(aCx, aScope, this);
+  return VTTRegionListBinding::Wrap(aCx, aScope, this);
 }
 
 TextTrackRegionList::TextTrackRegionList(nsISupports* aGlobal)
   : mParent(aGlobal)
 {
   SetIsDOMBinding();
 }
 
--- a/content/media/WebVTTListener.cpp
+++ b/content/media/WebVTTListener.cpp
@@ -1,15 +1,17 @@
 /* -*- 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 "WebVTTListener.h"
 #include "mozilla/dom/TextTrackCue.h"
+#include "mozilla/dom/TextTrackRegion.h"
+#include "mozilla/dom/VTTRegionBinding.h"
 #include "mozilla/dom/HTMLTrackElement.h"
 #include "nsIInputStream.h"
 #include "nsIWebVTTParserWrapper.h"
 #include "nsComponentManagerUtils.h"
 
 namespace mozilla {
 namespace dom {
 
@@ -167,14 +169,24 @@ WebVTTListener::OnCue(const JS::Value &a
 
   return NS_OK;
 }
 
 
 NS_IMETHODIMP
 WebVTTListener::OnRegion(const JS::Value &aRegion, JSContext* aCx)
 {
-  // TODO: Implement VTTRegions see bug 897504
+  if (!aRegion.isObject()) {
+    return NS_ERROR_FAILURE;
+  }
+
+  TextTrackRegion* region;
+  nsresult rv = UNWRAP_OBJECT(VTTRegion, aCx, &aRegion.toObject(),
+                              region);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  mElement->mTrack->AddRegion(*region);
+
   return NS_OK;
 }
 
 } // namespace dom
 } // namespace mozilla
--- a/content/media/test/Makefile.in
+++ b/content/media/test/Makefile.in
@@ -135,16 +135,17 @@ MOCHITEST_FILES = \
 		test_streams_element_capture.html \
 		test_streams_element_capture_reset.html \
 		test_streams_element_capture_createObjectURL.html \
 		test_streams_gc.html \
 		test_streams_tracks.html \
 		$(filter disabled-for-intermittent-failures--bug-608634, test_error_in_video_document.html) \
 		test_texttrack.html \
 		test_texttrackcue.html \
+		test_texttrackregion.html \
 		test_timeupdate_small_files.html \
 		test_unseekable.html \
 		test_VideoPlaybackQuality.html \
 		test_VideoPlaybackQuality_disabled.html \
 		test_webvtt_disabled.html \
 		test_bug895305.html \
 		test_bug895091.html \
 		$(NULL)
@@ -267,16 +268,17 @@ MOCHITEST_FILES += \
 		test-8-7.1.opus \
 		vbr.mp3 \
 		video-overhang.ogg \
 		file_a4_tone.ogg \
 		detodos.opus \
 		notags.mp3 \
 		id3tags.mp3 \
 		basic.vtt \
+		region.vtt \
 		long.vtt \
 		$(NULL)
 
 # Wave sample files
 MOCHITEST_FILES += \
 		big.wav \
 		bogus.wav \
 		r11025_msadpcm_c1.wav \
new file mode 100644
--- /dev/null
+++ b/content/media/test/region.vtt
@@ -0,0 +1,5 @@
+WEBVTT
+Region: id=fred width=62% lines=5 regionanchor=4%,78% viewportanchor=10%,90% scroll=up
+
+00:01.000 --> 00:02.000 region:fred
+Test here.
--- a/content/media/test/test_texttrackcue.html
+++ b/content/media/test/test_texttrackcue.html
@@ -79,50 +79,39 @@ SpecialPowers.pushPrefEnv({"set": [["med
 
       // Check that new VTTCue was added correctly
       cue = cueList[4];
       is(cue.startTime, 3.999, "Cue's start time should be 3.999.");
       is(cue.endTime, 4, "Cue's end time should be 4.");
       is(cue.text, "foo", "Cue's text should be foo.");
 
       // Adding the same cue again should not increase the cue count.
-      // TODO: https://bugzilla.mozilla.org/show_bug.cgi?id=867823
-      //       http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dom-texttrack-addcue
       trackElement.track.addCue(vttCue);
-      todo_is(cueList.length, 5, "Cue list length should be 5.");
+      is(cueList.length, 5, "Cue list length should be 5.");
 
       // Check that we are able to remove cues.
       trackElement.track.removeCue(cue);
-      // TODO: Marked as todo as incorrect addition up top increases cue count
-      // to 4 -- https://bugzilla.mozilla.org/show_bug.cgi?id=867823
-      todo_is(cueList.length, 4, "Cue list length should be 4.");
+      is(cueList.length, 4, "Cue list length should be 4.");
 
       var exceptionHappened = false;
       try {
         // We should not be able to remove a cue that is not in the list.
         cue = new VTTCue(1, 2, "foo");
-        trackElement.removeCue(cue);
+        trackElement.track.removeCue(cue);
       } catch (e) {
         // "NotFoundError" should be thrown when trying to remove a cue that is
         // not in the list.
-        // TODO: https://bugzilla.mozilla.org/show_bug.cgi?id=867823
-        //       http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dom-texttrack-removecue
-        todo_is(e.name, "NotFoundError", "We should have caught an error.");
+        is(e.name, "NotFoundError", "Should have thrown NotFoundError.");
         exceptionHappened = true;
       }
       // If this is false then we did not throw an error and probably removed a cue
       // when we shouln't have.
       ok(exceptionHappened, "Exception should have happened.");
 
-      // We should not have removed a cue so the cue list length should not
-      // have changed.
-      // TODO: Marked as todo as incorrect addition of cue up top increases
-      // count erroneously.
-      // https://bugzilla.mozilla.org/show_bug.cgi?id=867823
-      todo_is(cueList.length, 4, "Cue list length should be 4.");
+      is(cueList.length, 4, "Cue list length should be 4.");
 
       SimpleTest.finish();
     });
   }
 );
 
 </script>
 </pre>
new file mode 100644
--- /dev/null
+++ b/content/media/test/test_texttrackregion.html
@@ -0,0 +1,66 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=917945
+-->
+<head>
+  <meta charset='utf-8'>
+  <title>Test for Bug 917945 - VTTRegion</title>
+  <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+<p id="display"></p>
+<div id="content">
+</div>
+<pre id="test">
+<script class="testbody" type="text/javascript">
+SimpleTest.waitForExplicitFinish();
+SpecialPowers.pushPrefEnv({"set": [["media.webvtt.enabled", true]]},
+  function() {
+    var video = document.createElement("video");
+    video.src = "seek.webm";
+    video.preload = "auto";
+    var trackElement = document.createElement("track");
+    trackElement.src = "region.vtt";
+    trackElement.kind = "subtitles";
+    document.getElementById("content").appendChild(video);
+    video.appendChild(trackElement);
+    video.addEventListener("loadedmetadata", function run_tests() {
+      // Re-que run_tests() at the end of the event loop until the track
+      // element has loaded its data.
+      if (trackElement.readyState == 1) {
+        setTimeout(run_tests, 0);
+        return;
+      }
+      is(trackElement.readyState, 2, "Track::ReadyState should be set to LOADED.");
+
+      var cues = trackElement.track.cues,
+          regions = trackElement.track.regions;
+
+      is(regions.length, 1, "Region list length should be 1.");
+      is(cues.length, 1, "Cue list length should be 1.");
+
+      is(cues[0].regionId, "fred", "Cue regionId should be 'fred'.");
+
+      var region = regions[0];
+
+      is(region.id, "fred", "Region ID should be 'fred'.");
+      is(region.width, 62, "Region width should be 50.");
+      is(region.lines, 5, "Region lines should be 5.");
+      is(region.regionAnchorX, 4, "Region regionAnchorX should be 4.");
+      is(region.regionAnchorY, 78, "Region regionAnchorY should be 78.");
+      is(region.viewportAnchorX, 10, "Region viewportAnchorX should be 10.");
+      is(region.viewportAnchorY, 90, "Region viewportAnchorY should be 90.");
+      is(region.scroll, "up", "Region scroll should be 'up'");
+
+      SimpleTest.finish();
+    });
+  }
+);
+
+</script>
+</pre>
+</body>
+</html>
--- a/content/media/webspeech/synth/pico/nsPicoService.cpp
+++ b/content/media/webspeech/synth/pico/nsPicoService.cpp
@@ -4,16 +4,17 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsISupports.h"
 #include "nsPicoService.h"
 #include "nsPrintfCString.h"
 #include "nsIWeakReferenceUtils.h"
 #include "SharedBuffer.h"
+#include "nsISimpleEnumerator.h"
 
 #include "mozilla/dom/nsSynthVoiceRegistry.h"
 #include "mozilla/dom/nsSpeechTask.h"
 
 #include "nsIFile.h"
 #include "nsThreadUtils.h"
 #include "prenv.h"
 
--- a/content/svg/content/src/SVGAttrValueWrapper.h
+++ b/content/svg/content/src/SVGAttrValueWrapper.h
@@ -7,17 +7,17 @@
 #ifndef MOZILLA_SVGATTRVALUEWRAPPER_H__
 #define MOZILLA_SVGATTRVALUEWRAPPER_H__
 
 /**
  * Utility wrapper for handling SVG types used inside nsAttrValue so that these
  * types don't need to be exported outside the SVG module.
  */
 
-#include "nsStringGlue.h"
+#include "nsString.h"
 
 class nsSVGAngle;
 class nsSVGIntegerPair;
 class nsSVGLength2;
 class nsSVGNumberPair;
 class nsSVGViewBox;
 
 namespace mozilla {
--- a/content/svg/content/src/nsSVGDataParser.h
+++ b/content/svg/content/src/nsSVGDataParser.h
@@ -2,17 +2,17 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef __NS_SVGDATAPARSER_H__
 #define __NS_SVGDATAPARSER_H__
 
 #include "nsError.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 
 //----------------------------------------------------------------------
 // helper macros
 #define ENSURE_MATCHED(exp) { nsresult rv = exp; if (NS_FAILED(rv)) return rv; }
 
 ////////////////////////////////////////////////////////////////////////
 // nsSVGDataParser: a simple abstract class for parsing values
 // for path and transform values.
--- a/content/xbl/src/nsXBLPrototypeBinding.cpp
+++ b/content/xbl/src/nsXBLPrototypeBinding.cpp
@@ -29,17 +29,17 @@
 #include "nsIInterfaceInfoManager.h"
 #include "nsIDocumentObserver.h"
 #include "nsGkAtoms.h"
 #include "nsXBLProtoImpl.h"
 #include "nsCRT.h"
 #include "nsContentUtils.h"
 #include "nsTextFragment.h"
 #include "nsTextNode.h"
-
+#include "nsIInterfaceInfo.h"
 #include "nsIScriptError.h"
 
 #include "nsIStyleRuleProcessor.h"
 #include "nsXBLResourceLoader.h"
 #include "mozilla/dom/CDATASection.h"
 #include "mozilla/dom/Comment.h"
 #include "mozilla/dom/Element.h"
 
--- a/content/xslt/src/xpath/txXPCOMExtensionFunction.cpp
+++ b/content/xslt/src/xpath/txXPCOMExtensionFunction.cpp
@@ -13,16 +13,17 @@
 #include "txIFunctionEvaluationContext.h"
 #include "txIXPathContext.h"
 #include "txNodeSetAdaptor.h"
 #include "txXPathTreeWalker.h"
 #include "xptcall.h"
 #include "txXPathObjectAdaptor.h"
 #include "mozilla/Attributes.h"
 #include "nsIClassInfo.h"
+#include "nsIInterfaceInfo.h"
 
 NS_IMPL_ISUPPORTS1(txXPathObjectAdaptor, txIXPathObject)
 
 class txFunctionEvaluationContext MOZ_FINAL : public txIFunctionEvaluationContext
 {
 public:
     txFunctionEvaluationContext(txIEvalContext *aContext, nsISupports *aState);
 
--- a/docshell/base/nsDefaultURIFixup.cpp
+++ b/docshell/base/nsDefaultURIFixup.cpp
@@ -17,16 +17,17 @@
 
 #include "nsIURIFixup.h"
 #include "nsDefaultURIFixup.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/dom/ContentChild.h"
 #include "mozilla/ipc/InputStreamUtils.h"
 #include "mozilla/ipc/URIUtils.h"
 #include "nsIObserverService.h"
+#include "nsXULAppAPI.h"
 
 using namespace mozilla;
 
 /* Implementation file */
 NS_IMPL_ISUPPORTS1(nsDefaultURIFixup, nsIURIFixup)
 
 nsDefaultURIFixup::nsDefaultURIFixup()
 {
--- a/dom/apps/src/PermissionsTable.jsm
+++ b/dom/apps/src/PermissionsTable.jsm
@@ -282,16 +282,21 @@ this.PermissionsTable =  { geolocation: 
                              privileged: DENY_ACTION,
                              certified: ALLOW_ACTION
                            },
                            "keyboard": {
                              app: DENY_ACTION,
                              privileged: ALLOW_ACTION,
                              certified: ALLOW_ACTION
                            },
+                           "inputmethod-manage": {
+                             app: DENY_ACTION,
+                             privileged: DENY_ACTION,
+                             certified: ALLOW_ACTION
+                           },
                            "wappush": {
                              app: DENY_ACTION,
                              privileged: DENY_ACTION,
                              certified: ALLOW_ACTION
                            },
                            "audio-capture": {
                              app: PROMPT_ACTION,
                              privileged: PROMPT_ACTION,
--- a/dom/base/Crypto.cpp
+++ b/dom/base/Crypto.cpp
@@ -1,16 +1,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 "Crypto.h"
 #include "jsfriendapi.h"
 #include "nsCOMPtr.h"
 #include "nsIRandomGenerator.h"
 #include "nsPIDOMWindow.h"
+#include "MainThreadUtils.h"
+#include "nsXULAppAPI.h"
 
 #include "mozilla/dom/ContentChild.h"
 #include "mozilla/dom/CryptoBinding.h"
 
 using mozilla::dom::ContentChild;
 
 using namespace js::ArrayBufferView;
 
--- a/dom/base/DOMException.cpp
+++ b/dom/base/DOMException.cpp
@@ -12,16 +12,17 @@
 #include "mozilla/Util.h"
 #include "mozilla/dom/Exceptions.h"
 #include "nsContentUtils.h"
 #include "nsCOMPtr.h"
 #include "nsIClassInfoImpl.h"
 #include "nsIDocument.h"
 #include "nsIDOMDOMException.h"
 #include "nsIException.h"
+#include "nsIProgrammingLanguage.h"
 #include "nsMemory.h"
 #include "prprf.h"
 #include "xpcprivate.h"
 
 #include "mozilla/dom/DOMExceptionBinding.h"
 
 using namespace mozilla;
 
--- a/dom/base/nsFocusManager.cpp
+++ b/dom/base/nsFocusManager.cpp
@@ -36,16 +36,17 @@
 #include "nsIPrincipal.h"
 #include "nsIObserverService.h"
 #include "nsIObjectFrame.h"
 #include "nsBindingManager.h"
 
 #include "mozilla/dom/Element.h"
 #include "mozilla/LookAndFeel.h"
 #include "mozilla/Preferences.h"
+#include "mozilla/Services.h"
 #include <algorithm>
 
 #ifdef MOZ_XUL
 #include "nsIDOMXULTextboxElement.h"
 #include "nsIDOMXULMenuListElement.h"
 #endif
 
 #ifdef ACCESSIBILITY
--- a/dom/base/nsIDOMScriptObjectFactory.h
+++ b/dom/base/nsIDOMScriptObjectFactory.h
@@ -3,17 +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 nsIDOMScriptObjectFactory_h__
 #define nsIDOMScriptObjectFactory_h__
 
 #include "nsISupports.h"
 #include "nsIDOMClassInfo.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 
 #define NS_IDOM_SCRIPT_OBJECT_FACTORY_IID \
 { 0x2a50e17c, 0x46ff, 0x4150, \
   { 0xbb, 0x46, 0xd8, 0x07, 0xb3, 0x36, 0xde, 0xab } }
 
 class nsIScriptContext;
 class nsIScriptGlobalObject;
 class nsIDOMEventListener;
--- a/dom/base/nsIScriptContext.h
+++ b/dom/base/nsIScriptContext.h
@@ -2,17 +2,17 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef nsIScriptContext_h__
 #define nsIScriptContext_h__
 
 #include "nscore.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 #include "nsISupports.h"
 #include "nsCOMPtr.h"
 #include "nsIProgrammingLanguage.h"
 #include "jspubtd.h"
 #include "js/GCAPI.h"
 
 class nsIScriptGlobalObject;
 class nsIScriptSecurityManager;
--- a/dom/base/nsScreen.cpp
+++ b/dom/base/nsScreen.cpp
@@ -8,16 +8,17 @@
 #include "nsIDocShell.h"
 #include "nsPresContext.h"
 #include "nsCOMPtr.h"
 #include "nsIDocShellTreeItem.h"
 #include "nsLayoutUtils.h"
 #include "nsDOMEvent.h"
 #include "nsJSUtils.h"
 #include "mozilla/dom/ScreenBinding.h"
+#include "nsDeviceContext.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 namespace {
 
 bool
 IsChromeType(nsIDocShell *aDocShell)
--- a/dom/base/nsScriptNameSpaceManager.cpp
+++ b/dom/base/nsScriptNameSpaceManager.cpp
@@ -21,16 +21,17 @@
 #include "xptinfo.h"
 #include "nsXPIDLString.h"
 #include "nsPrintfCString.h"
 #include "nsReadableUtils.h"
 #include "nsHashKeys.h"
 #include "nsDOMClassInfo.h"
 #include "nsCRT.h"
 #include "nsIObserverService.h"
+#include "nsISimpleEnumerator.h"
 
 #include "mozilla/MemoryReporting.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/Services.h"
 
 #define NS_INTERFACE_PREFIX "nsI"
 #define NS_DOM_INTERFACE_PREFIX "nsIDOM"
 
--- a/dom/bindings/Bindings.conf
+++ b/dom/bindings/Bindings.conf
@@ -1249,16 +1249,24 @@ DOMInterfaces = {
 {
     'workers': True,
 }],
 
 'VTTCue': {
     'nativeType': 'mozilla::dom::TextTrackCue'
 },
 
+'VTTRegion': {
+  'nativeType': 'mozilla::dom::TextTrackRegion',
+},
+
+'VTTRegionList': {
+  'nativeType': 'mozilla::dom::TextTrackRegionList',
+},
+
 'WebGLActiveInfo': {
     'nativeType': 'mozilla::WebGLActiveInfo',
     'headerFile': 'WebGLActiveInfo.h',
     'wrapperCache': False
 },
 
 'WebGLBuffer': {
     'nativeType': 'mozilla::WebGLBuffer',
--- a/dom/bindings/DOMJSProxyHandler.h
+++ b/dom/bindings/DOMJSProxyHandler.h
@@ -6,17 +6,17 @@
 #ifndef mozilla_dom_DOMJSProxyHandler_h
 #define mozilla_dom_DOMJSProxyHandler_h
 
 #include "mozilla/Attributes.h"
 #include "mozilla/Likely.h"
 
 #include "jsapi.h"
 #include "jsproxy.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 
 #define DOM_PROXY_OBJECT_SLOT js::PROXY_PRIVATE_SLOT
 
 namespace mozilla {
 namespace dom {
 
 class DOMClass;
 
--- a/dom/bluetooth/BluetoothA2dpManager.cpp
+++ b/dom/bluetooth/BluetoothA2dpManager.cpp
@@ -14,16 +14,17 @@
 #include "BluetoothSocket.h"
 #include "BluetoothUtils.h"
 
 #include "mozilla/dom/bluetooth/BluetoothTypes.h"
 #include "mozilla/Services.h"
 #include "mozilla/StaticPtr.h"
 #include "nsIAudioManager.h"
 #include "nsIObserverService.h"
+#include "MainThreadUtils.h"
 
 
 using namespace mozilla;
 USING_BLUETOOTH_NAMESPACE
 
 namespace {
   StaticRefPtr<BluetoothA2dpManager> sBluetoothA2dpManager;
   bool sInShutdown = false;
--- a/dom/bluetooth/BluetoothCommon.h
+++ b/dom/bluetooth/BluetoothCommon.h
@@ -4,17 +4,17 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef mozilla_dom_bluetooth_bluetoothcommon_h__
 #define mozilla_dom_bluetooth_bluetoothcommon_h__
 
 #include "mozilla/Observer.h"
 #include "nsPrintfCString.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 #include "nsTArray.h"
 
 extern bool gBluetoothDebugFlag;
 
 #define SWITCH_BT_DEBUG(V) (gBluetoothDebugFlag = V)
 
 #undef BT_LOG
 #if defined(MOZ_WIDGET_GONK)
--- a/dom/bluetooth/BluetoothHidManager.cpp
+++ b/dom/bluetooth/BluetoothHidManager.cpp
@@ -12,16 +12,17 @@
 #include "BluetoothService.h"
 #include "BluetoothProfileController.h"
 #include "BluetoothUtils.h"
 
 #include "mozilla/dom/bluetooth/BluetoothTypes.h"
 #include "mozilla/Services.h"
 #include "mozilla/StaticPtr.h"
 #include "nsIObserverService.h"
+#include "MainThreadUtils.h"
 
 using namespace mozilla;
 USING_BLUETOOTH_NAMESPACE
 
 namespace {
   StaticRefPtr<BluetoothHidManager> sBluetoothHidManager;
   bool sInShutdown = false;
 } // anonymous namespace
--- a/dom/bluetooth/ipc/BluetoothServiceChildProcess.cpp
+++ b/dom/bluetooth/ipc/BluetoothServiceChildProcess.cpp
@@ -7,16 +7,17 @@
 #include "base/basictypes.h"
 
 #include "BluetoothServiceChildProcess.h"
 
 #include "mozilla/Assertions.h"
 #include "mozilla/dom/ContentChild.h"
 
 #include "BluetoothChild.h"
+#include "MainThreadUtils.h"
 
 USING_BLUETOOTH_NAMESPACE
 
 namespace {
 
 BluetoothChild* gBluetoothChild;
 
 inline
--- a/dom/browser-element/BrowserElementChildPreload.js
+++ b/dom/browser-element/BrowserElementChildPreload.js
@@ -205,16 +205,17 @@ BrowserElementChild.prototype = {
       "go-forward": this._recvGoForward,
       "reload": this._recvReload,
       "stop": this._recvStop,
       "unblock-modal-prompt": this._recvStopWaiting,
       "fire-ctx-callback": this._recvFireCtxCallback,
       "owner-visibility-change": this._recvOwnerVisibilityChange,
       "exit-fullscreen": this._recvExitFullscreen.bind(this),
       "activate-next-paint-listener": this._activateNextPaintListener.bind(this),
+      "set-input-method-active": this._recvSetInputMethodActive.bind(this),
       "deactivate-next-paint-listener": this._deactivateNextPaintListener.bind(this)
     }
 
     addMessageListener("browser-element-api:call", function(aMessage) {
       if (aMessage.data.msg_name in mmCalls) {
         return mmCalls[aMessage.data.msg_name].apply(self, arguments);
       }
     });
@@ -881,16 +882,30 @@ BrowserElementChild.prototype = {
     }
   },
 
   _recvStop: function(data) {
     let webNav = docShell.QueryInterface(Ci.nsIWebNavigation);
     webNav.stop(webNav.STOP_NETWORK);
   },
 
+  _recvSetInputMethodActive: function(data) {
+    let msgData = { id: data.json.id };
+    // Unwrap to access webpage content.
+    let nav = XPCNativeWrapper.unwrap(content.document.defaultView.navigator);
+    if (nav.mozInputMethod) {
+      // Wrap to access the chrome-only attribute setActive.
+      new XPCNativeWrapper(nav.mozInputMethod).setActive(data.json.args.isActive);
+      msgData.successRv = null;
+    } else {
+      msgData.errorMsg = 'Cannot access mozInputMethod.';
+    }
+    sendAsyncMsg('got-set-input-method-active', msgData);
+  },
+
   _keyEventHandler: function(e) {
     if (whitelistedEvents.indexOf(e.keyCode) != -1 && !e.defaultPrevented) {
       sendAsyncMsg('keyevent', {
         type: e.type,
         keyCode: e.keyCode,
         charCode: e.charCode,
       });
     }
--- a/dom/browser-element/BrowserElementParent.jsm
+++ b/dom/browser-element/BrowserElementParent.jsm
@@ -87,16 +87,20 @@ function visibilityChangeHandler(e) {
 }
 
 this.BrowserElementParentBuilder = {
   create: function create(frameLoader, hasRemoteFrame) {
     return new BrowserElementParent(frameLoader, hasRemoteFrame);
   }
 }
 
+
+// The active input method iframe.
+let activeInputFrame = null;
+
 function BrowserElementParent(frameLoader, hasRemoteFrame) {
   debug("Creating new BrowserElementParent object for " + frameLoader);
   this._domRequestCounter = 0;
   this._pendingDOMRequests = {};
   this._hasRemoteFrame = hasRemoteFrame;
   this._nextPaintListeners = [];
 
   this._frameLoader = frameLoader;
@@ -136,16 +140,17 @@ function BrowserElementParent(frameLoade
     "got-screenshot": this._gotDOMRequestResult,
     "got-can-go-back": this._gotDOMRequestResult,
     "got-can-go-forward": this._gotDOMRequestResult,
     "fullscreen-origin-change": this._remoteFullscreenOriginChange,
     "rollback-fullscreen": this._remoteFrameFullscreenReverted,
     "exit-fullscreen": this._exitFullscreen,
     "got-visible": this._gotDOMRequestResult,
     "visibilitychange": this._childVisibilityChange,
+    "got-set-input-method-active": this._gotDOMRequestResult
   }
 
   this._mm.addMessageListener('browser-element-api:call', function(aMsg) {
     if (self._isAlive() && (aMsg.data.msg_name in mmCalls)) {
       return mmCalls[aMsg.data.msg_name].apply(self, arguments);
     }
   });
 
@@ -183,16 +188,23 @@ function BrowserElementParent(frameLoade
   defineMethod('stop', this._stop);
   defineMethod('purgeHistory', this._purgeHistory);
   defineMethod('getScreenshot', this._getScreenshot);
   defineMethod('addNextPaintListener', this._addNextPaintListener);
   defineMethod('removeNextPaintListener', this._removeNextPaintListener);
   defineDOMRequestMethod('getCanGoBack', 'get-can-go-back');
   defineDOMRequestMethod('getCanGoForward', 'get-can-go-forward');
 
+  let principal = this._frameElement.ownerDocument.nodePrincipal;
+  let perm = Services.perms
+             .testExactPermissionFromPrincipal(principal, "inputmethod-manage");
+  if (perm === Ci.nsIPermissionManager.ALLOW_ACTION) {
+    defineMethod('setInputMethodActive', this._setInputMethodActive);
+  }
+
   // Listen to visibilitychange on the iframe's owner window, and forward
   // changes down to the child.  We want to do this while registering as few
   // visibilitychange listeners on _window as possible, because such a listener
   // may live longer than this BrowserElementParent object.
   //
   // To accomplish this, we register just one listener on the window, and have
   // it reference a WeakMap whose keys are all the BrowserElementParent objects
   // on the window.  Then when the listener fires, we iterate over the
@@ -576,16 +588,57 @@ BrowserElementParent.prototype = {
         break;
       }
     }
 
     if (this._nextPaintListeners.length == 0)
       this._sendAsyncMsg('deactivate-next-paint-listener');
   },
 
+  _setInputMethodActive: function(isActive) {
+    if (typeof isActive !== 'boolean') {
+      throw Components.Exception("Invalid argument",
+                                 Cr.NS_ERROR_INVALID_ARG);
+    }
+
+    let req = Services.DOMRequest.createRequest(this._window);
+
+    // Deactivate the old input method if needed.
+    if (activeInputFrame && isActive) {
+      let reqOld = XPCNativeWrapper.unwrap(activeInputFrame)
+                                   .setInputMethodActive(false);
+      reqOld.onsuccess = function() {
+        activeInputFrame = null;
+        this._sendSetInputMethodActiveDOMRequest(req, isActive);
+      }.bind(this);
+      reqOld.onerror = function() {
+        Services.DOMRequest.fireErrorAsync(req,
+          'Failed to deactivate the old input method: ' +
+          reqOld.error + '.');
+      };
+    } else {
+      this._sendSetInputMethodActiveDOMRequest(req, isActive);
+    }
+    return req;
+  },
+
+  _sendSetInputMethodActiveDOMRequest: function(req, isActive) {
+    let id = 'req_' + this._domRequestCounter++;
+    let data = {
+      id : id,
+      args: { isActive: isActive }
+    };
+    if (this._sendAsyncMsg('set-input-method-active', data)) {
+      activeInputFrame = this._frameElement;
+      this._pendingDOMRequests[id] = req;
+    } else {
+      Services.DOMRequest.fireErrorAsync(req, 'fail');
+    }
+  },
+
   _fireKeyEvent: function(data) {
     let evt = this._window.document.createEvent("KeyboardEvent");
     evt.initKeyEvent(data.json.type, true, true, this._window,
                      false, false, false, false, // modifiers
                      data.json.keyCode,
                      data.json.charCode);
 
     this._frameElement.dispatchEvent(evt);
--- a/dom/browser-element/mochitest/Makefile.in
+++ b/dom/browser-element/mochitest/Makefile.in
@@ -158,16 +158,21 @@ MOCHITEST_FILES = \
 		browserElement_DocumentFirstPaint.js \
 		test_browserElement_inproc_DocumentFirstPaint.html \
 		browserElement_VisibilityChange.js \
 		test_browserElement_inproc_VisibilityChange.html \
 		browserElement_BrowserWindowResize.js \
 		test_browserElement_inproc_BrowserWindowResize.html \
 		$(NULL)
 
+# Disabled until we fix bug 906096.
+#		browserElement_SetInputMethodActive.js \
+#		test_browserElement_inproc_SetInputMethodActive.html \
+#		file_inputmethod.html \
+
 # Disabled due to https://bugzilla.mozilla.org/show_bug.cgi?id=774100
 #		test_browserElement_inproc_Reload.html \
 
 # Disabled due to focus issues (no bug that I'm aware of)
 # 		test_browserElement_oop_KeyEvents.html \
 
 # Disable due to certificate issue (no bug that I'm aware of)
 #		test_browserElement_inproc_ErrorSecurity.html \
@@ -234,9 +239,12 @@ MOCHITEST_FILES += \
 		test_browserElement_oop_FrameWrongURI.html \
 		test_browserElement_oop_ReloadPostRequest.html \
 		test_browserElement_oop_PurgeHistory.html \
 		test_browserElement_oop_DocumentFirstPaint.html \
 		test_browserElement_oop_VisibilityChange.html \
 		test_browserElement_oop_BrowserWindowResize.html \
 	$(NULL)
 
+# Disabled until we fix bug 906096.
+#		test_browserElement_oop_SetInputMethodActive.html \
+
 endif #}
new file mode 100644
--- /dev/null
+++ b/dom/browser-element/mochitest/browserElement_SetInputMethodActive.js
@@ -0,0 +1,96 @@
+/* Any copyright is dedicated to the public domain.
+   http://creativecommons.org/publicdomain/zero/1.0/ */
+
+// Bug 905573 - Add setInputMethodActive to browser elements to allow gaia
+// system set the active IME app.
+'use strict';
+
+SimpleTest.waitForExplicitFinish();
+browserElementTestHelpers.setEnabledPref(true);
+browserElementTestHelpers.addPermission();
+
+function setup() {
+  SpecialPowers.setBoolPref("dom.mozInputMethod.enabled", true);
+  SpecialPowers.setBoolPref("dom.mozInputMethod.testing", true);
+  SpecialPowers.addPermission('inputmethod-manage', true, document);
+}
+
+function tearDown() {
+  SpecialPowers.setBoolPref("dom.mozInputMethod.enabled", false);
+  SpecialPowers.setBoolPref("dom.mozInputMethod.testing", false);
+  SpecialPowers.removePermission("inputmethod-manage", document);
+  SimpleTest.finish();
+}
+
+function runTest() {
+  // Create an input field to receive string from input method iframes.
+  let input = document.createElement('input');
+  input.type = 'text';
+  document.body.appendChild(input);
+
+  // Create two input method iframes.
+  let frames = [];
+  for (let i = 0; i < 2; i++) {
+    frames[i] = document.createElement('iframe');
+    SpecialPowers.wrap(frames[i]).mozbrowser = true;
+    // When the input method iframe is activated, it will send the URL
+    // hash to current focused element. We set different hash to each
+    // iframe so that iframes can be differentiated by their hash.
+    frames[i].src = 'file_inputmethod.html#' + i;
+    frames[i].setAttribute('mozapp', location.href.replace(/[^/]+$/, 'file_inputmethod.webapp'));
+    document.body.appendChild(frames[i]);
+  }
+
+  let count = 0;
+
+  // Set focus to the input field and wait for input methods' inputting.
+  SpecialPowers.DOMWindowUtils.focus(input);
+  var timerId = null;
+  input.oninput = function() {
+    // The texts sent from the first and the second input method are '#0' and
+    // '#1' respectively.
+    switch (count) {
+      case 1:
+        is(input.value, '#0', 'Failed to get correct input from the first iframe.');
+        testNextInputMethod();
+        break;
+      case 2:
+        is(input.value, '#0#1', 'Failed to get correct input from the second iframe.');
+        // Do nothing and wait for the next input from the second iframe.
+        count++;
+        break;
+      case 3:
+        is(input.value, '#0#1#1', 'Failed to get correct input from the second iframe.');
+        // Receive the second input from the second iframe.
+        count++;
+        // Deactive the second iframe.
+        frames[1].setInputMethodActive(false);
+        // Wait for a short while to ensure the second iframe is not active any
+        // more.
+        timerId = setTimeout(function() {
+          ok(true, 'Successfully deactivate the second iframe.');
+          tearDown();
+        }, 1000);
+        break;
+      default:
+        ok(false, 'Failed to deactivate the second iframe.');
+        clearTimeout(timerId);
+        tearDown();
+        break;
+    }
+  }
+
+  ok(frames[0].setInputMethodActive, 'Cannot access setInputMethodActive.');
+
+  function testNextInputMethod() {
+    frames[count++].setInputMethodActive(true);
+  }
+
+  // Wait for a short while to let input method get ready.
+  setTimeout(function() {
+    testNextInputMethod();
+  }, 500);
+}
+
+setup();
+addEventListener('testready', runTest);
new file mode 100644
--- /dev/null
+++ b/dom/browser-element/mochitest/file_inputmethod.html
@@ -0,0 +1,21 @@
+<html>
+<body>
+<script>
+  var im = navigator.mozInputMethod;
+  if (im) {
+    var intervalId = null;
+    // Automatically append location hash to current input field.
+    im.oninputcontextchange = function() {
+      var ctx = im.inputcontext;
+      if (ctx) {
+        intervalId = setInterval(function() {
+          ctx.replaceSurroundingText(location.hash);
+        }, 500);
+      } else {
+        clearInterval(intervalId);
+      }
+    };
+  }
+</script>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/dom/browser-element/mochitest/test_browserElement_inproc_SetInputMethodActive.html
@@ -0,0 +1,14 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <title>Test for Bug 905573</title>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="application/javascript" src="browserElementTestHelpers.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+<script type="application/javascript;version=1.7" src="browserElement_SetInputMethodActive.js">
+</script>
+</body>
+</html>
+
new file mode 100644
--- /dev/null
+++ b/dom/browser-element/mochitest/test_browserElement_oop_SetInputMethodActive.html
@@ -0,0 +1,14 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <title>Test for Bug 905573</title>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="application/javascript" src="browserElementTestHelpers.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+<script type="application/javascript;version=1.7" src="browserElement_SetInputMethodActive.js">
+</script>
+</body>
+</html>
+
--- a/dom/devicestorage/DeviceStorageRequestParent.cpp
+++ b/dom/devicestorage/DeviceStorageRequestParent.cpp
@@ -8,16 +8,17 @@
 #include "nsIMIMEService.h"
 #include "nsCExternalHandlerService.h"
 #include "mozilla/unused.h"
 #include "mozilla/dom/ipc/Blob.h"
 #include "ContentParent.h"
 #include "nsProxyRelease.h"
 #include "AppProcessChecker.h"
 #include "mozilla/Preferences.h"
+#include "nsNetCID.h"
 
 namespace mozilla {
 namespace dom {
 namespace devicestorage {
 
 DeviceStorageRequestParent::DeviceStorageRequestParent(
   const DeviceStorageParams& aParams)
   : mParams(aParams)
--- a/dom/file/FileCommon.h
+++ b/dom/file/FileCommon.h
@@ -7,17 +7,17 @@
 #ifndef mozilla_dom_file_filecommon_h__
 #define mozilla_dom_file_filecommon_h__
 
 #include "nsAutoPtr.h"
 #include "nsCOMPtr.h"
 #include "nsCycleCollectionParticipant.h"
 #include "nsDOMEventTargetHelper.h"
 #include "nsDebug.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 #include "nsTArray.h"
 
 #define BEGIN_FILE_NAMESPACE \
   namespace mozilla { namespace dom { namespace file {
 #define END_FILE_NAMESPACE \
   } /* namespace file */ } /* namespace dom */ } /* namespace mozilla */
 #define USING_FILE_NAMESPACE \
   using namespace mozilla::dom::file;
--- a/dom/imptests/editing/conformancetest/test_event.html
+++ b/dom/imptests/editing/conformancetest/test_event.html
@@ -1,10 +1,11 @@
 <!doctype html>
 <title>Editing event tests</title>
+<style>body { font-family: serif }</style>
 <script src=/resources/testharness.js></script>
 <script src=/resources/testharnessreport.js></script>
 <div id=test></div>
 <div id=log></div>
 <script>
 "use strict";
 
 var div = document.querySelector("#test");
--- a/dom/indexedDB/Client.cpp
+++ b/dom/indexedDB/Client.cpp
@@ -8,16 +8,17 @@
 
 #include "mozilla/dom/quota/QuotaManager.h"
 #include "mozilla/dom/quota/UsageInfo.h"
 #include "mozilla/dom/quota/Utilities.h"
 
 #include "IDBDatabase.h"
 #include "IndexedDatabaseManager.h"
 #include "TransactionThreadPool.h"
+#include "nsISimpleEnumerator.h"
 
 USING_INDEXEDDB_NAMESPACE
 using mozilla::dom::quota::AssertIsOnIOThread;
 using mozilla::dom::quota::QuotaManager;
 
 namespace {
 
 bool
--- a/dom/indexedDB/IDBFactory.cpp
+++ b/dom/indexedDB/IDBFactory.cpp
@@ -39,16 +39,17 @@
 #include "CheckPermissionsHelper.h"
 #include "DatabaseInfo.h"
 #include "IDBDatabase.h"
 #include "IDBEvents.h"
 #include "IDBKeyRange.h"
 #include "IndexedDatabaseManager.h"
 #include "Key.h"
 #include "ProfilerHelpers.h"
+#include "nsNetUtil.h"
 
 #include "ipc/IndexedDBChild.h"
 
 #define PREF_INDEXEDDB_ENABLED "dom.indexedDB.enabled"
 
 USING_INDEXEDDB_NAMESPACE
 USING_QUOTA_NAMESPACE
 
--- a/dom/indexedDB/IDBRequest.cpp
+++ b/dom/indexedDB/IDBRequest.cpp
@@ -13,17 +13,17 @@
 #include "nsComponentManagerUtils.h"
 #include "nsDOMClassInfoID.h"
 #include "nsDOMJSUtils.h"
 #include "nsContentUtils.h"
 #include "nsCxPusher.h"
 #include "nsEventDispatcher.h"
 #include "nsJSUtils.h"
 #include "nsPIDOMWindow.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 #include "nsThreadUtils.h"
 #include "nsWrapperCacheInlines.h"
 
 #include "AsyncConnectionHelper.h"
 #include "IDBCursor.h"
 #include "IDBEvents.h"
 #include "IDBFactory.h"
 #include "IDBIndex.h"
--- a/dom/indexedDB/IndexedDatabase.h
+++ b/dom/indexedDB/IndexedDatabase.h
@@ -10,17 +10,17 @@
 #include "nsIProgrammingLanguage.h"
 
 #include "mozilla/Attributes.h"
 #include "js/StructuredClone.h"
 #include "nsAutoPtr.h"
 #include "nsCOMPtr.h"
 #include "nsDebug.h"
 #include "nsError.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 #include "nsTArray.h"
 #include "nsIInputStream.h"
 
 #define BEGIN_INDEXEDDB_NAMESPACE \
   namespace mozilla { namespace dom { namespace indexedDB {
 
 #define END_INDEXEDDB_NAMESPACE \
   } /* namespace indexedDB */ } /* namepsace dom */ } /* namespace mozilla */
--- a/dom/ipc/AppProcessChecker.cpp
+++ b/dom/ipc/AppProcessChecker.cpp
@@ -1,25 +1,27 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  * vim: sw=2 ts=8 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/. */
 
 #include "AppProcessChecker.h"
+#ifdef MOZ_CHILD_PERMISSIONS
 #include "ContentParent.h"
 #include "mozIApplication.h"
 #include "mozilla/hal_sandbox/PHalParent.h"
 #include "nsIDOMApplicationRegistry.h"
 #include "TabParent.h"
 
 using namespace mozilla::dom;
 using namespace mozilla::hal_sandbox;
 using namespace mozilla::services;
+#endif
 
 namespace mozilla {
 
 #ifdef MOZ_CHILD_PERMISSIONS
 
 bool
 AssertAppProcess(PBrowserParent* aActor,
                  AssertAppProcessType aType,
--- a/dom/ipc/Blob.cpp
+++ b/dom/ipc/Blob.cpp
@@ -23,16 +23,17 @@
 #include "mozilla/ipc/InputStreamUtils.h"
 #include "nsDOMFile.h"
 #include "nsProxyRelease.h"
 #include "nsThreadUtils.h"
 #include "jsapi.h"
 
 #include "ContentChild.h"
 #include "ContentParent.h"
+#include "nsNetCID.h"
 
 #define PRIVATE_REMOTE_INPUT_STREAM_IID \
   {0x30c7699f, 0x51d2, 0x48c8, {0xad, 0x56, 0xc0, 0x16, 0xd7, 0x6f, 0x71, 0x27}}
 
 using namespace mozilla::dom;
 using namespace mozilla::dom::ipc;
 using namespace mozilla::ipc;
 
--- a/dom/ipc/Blob.h
+++ b/dom/ipc/Blob.h
@@ -7,26 +7,23 @@
 #ifndef mozilla_dom_ipc_Blob_h
 #define mozilla_dom_ipc_Blob_h
 
 #include "mozilla/Attributes.h"
 #include "mozilla/dom/PBlobChild.h"
 #include "mozilla/dom/PBlobParent.h"
 #include "mozilla/dom/PBlobStreamChild.h"
 #include "mozilla/dom/PBlobStreamParent.h"
-#include "mozilla/dom/PContent.h"
 
 #include "nsAutoPtr.h"
 #include "nsCOMPtr.h"
 #include "nsTArray.h"
-#include "nsThreadUtils.h"
 
 class nsIDOMBlob;
-class nsIIPCSerializableInputStream;
-class nsIInputStream;
+template<class T> class nsRevocableEventPtr;
 
 namespace mozilla {
 namespace dom {
 
 class ContentParent;
 class ContentChild;
 
 namespace ipc {
--- a/dom/ipc/ContentChild.cpp
+++ b/dom/ipc/ContentChild.cpp
@@ -15,68 +15,64 @@
 #include "ContentChild.h"
 #include "CrashReporterChild.h"
 #include "TabChild.h"
 
 #include "mozilla/Attributes.h"
 #include "mozilla/dom/ExternalHelperAppChild.h"
 #include "mozilla/dom/PCrashReporterChild.h"
 #include "mozilla/dom/DOMStorageIPC.h"
-#include "mozilla/Hal.h"
 #include "mozilla/hal_sandbox/PHalChild.h"
 #include "mozilla/ipc/GeckoChildProcessHost.h"
 #include "mozilla/ipc/TestShellChild.h"
-#include "mozilla/ipc/XPCShellEnvironment.h"
 #include "mozilla/layers/CompositorChild.h"
 #include "mozilla/layers/ImageBridgeChild.h"
 #include "mozilla/layers/PCompositorChild.h"
 #include "mozilla/net/NeckoChild.h"
 #include "mozilla/Preferences.h"
 #ifdef MOZ_CONTENT_SANDBOX
 #include "mozilla/Sandbox.h"
 #endif
 #include "mozilla/unused.h"
 
+#include "nsIConsoleListener.h"
+#include "nsIInterfaceRequestorUtils.h"
 #include "nsIMemoryReporter.h"
 #include "nsIMemoryInfoDumper.h"
 #include "nsIMutable.h"
 #include "nsIObserverService.h"
-#include "nsTObserverArray.h"
 #include "nsIObserver.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsServiceManagerUtils.h"
 #include "nsStyleSheetService.h"
 #include "nsXULAppAPI.h"
-#include "nsWeakReference.h"
 #include "nsIScriptError.h"
 #include "nsIConsoleService.h"
 #include "nsJSEnvironment.h"
 #include "SandboxHal.h"
 #include "nsDebugImpl.h"
 #include "nsHashPropertyBag.h"
 #include "nsLayoutStylesheetCache.h"
 #include "nsIJSRuntimeService.h"
 
 #include "IHistory.h"
-#include "nsDocShellCID.h"
 #include "nsNetUtil.h"
 
 #include "base/message_loop.h"
 #include "base/process_util.h"
 #include "base/task.h"
 
 #include "nsChromeRegistryContent.h"
-#include "mozilla/chrome/RegistryMessageUtils.h"
 #include "nsFrameMessageManager.h"
 
 #include "nsIGeolocationProvider.h"
-#include "JavaScriptParent.h"
 #include "mozilla/dom/PMemoryReportRequestChild.h"
 
 #ifdef MOZ_PERMISSIONS
+#include "nsIScriptSecurityManager.h"
 #include "nsPermission.h"
 #include "nsPermissionManager.h"
 #endif
 
 #if defined(MOZ_WIDGET_ANDROID)
 #include "APKOpen.h"
 #endif
 
@@ -91,38 +87,36 @@
 #endif
 
 #ifdef ACCESSIBILITY
 #include "nsIAccessibilityService.h"
 #endif
 
 #include "mozilla/dom/indexedDB/PIndexedDBChild.h"
 #include "mozilla/dom/mobilemessage/SmsChild.h"
-#include "mozilla/dom/telephony/TelephonyChild.h"
 #include "mozilla/dom/devicestorage/DeviceStorageRequestChild.h"
 #include "mozilla/dom/bluetooth/PBluetoothChild.h"
 #include "mozilla/dom/PFMRadioChild.h"
 #include "mozilla/ipc/InputStreamUtils.h"
 
 #ifdef MOZ_WEBSPEECH
 #include "mozilla/dom/PSpeechSynthesisChild.h"
 #endif
 
 #include "nsDOMFile.h"
 #include "nsIRemoteBlob.h"
 #include "ProcessUtils.h"
 #include "StructuredCloneUtils.h"
 #include "URIUtils.h"
-#include "nsIScriptSecurityManager.h"
 #include "nsContentUtils.h"
 #include "nsIPrincipal.h"
 #include "nsDeviceStorage.h"
 #include "AudioChannelService.h"
 #include "JavaScriptChild.h"
-#include "ProcessPriorityManager.h"
+#include "mozilla/dom/telephony/PTelephonyChild.h"
 
 using namespace base;
 using namespace mozilla;
 using namespace mozilla::docshell;
 using namespace mozilla::dom::bluetooth;
 using namespace mozilla::dom::devicestorage;
 using namespace mozilla::dom::ipc;
 using namespace mozilla::dom::mobilemessage;
@@ -504,24 +498,24 @@ ContentChild::RecvDumpGCAndCCLogsToFile(
 {
     nsCOMPtr<nsIMemoryInfoDumper> dumper = do_GetService("@mozilla.org/memory-info-dumper;1");
 
     dumper->DumpGCAndCCLogsToFile(aIdentifier, aDumpAllTraces,
                                   aDumpChildProcesses);
     return true;
 }
 
-PCompositorChild*
+bool
 ContentChild::AllocPCompositorChild(mozilla::ipc::Transport* aTransport,
                                     base::ProcessId aOtherProcess)
 {
     return CompositorChild::Create(aTransport, aOtherProcess);
 }
 
-PImageBridgeChild*
+bool
 ContentChild::AllocPImageBridgeChild(mozilla::ipc::Transport* aTransport,
                                      base::ProcessId aOtherProcess)
 {
     return ImageBridgeChild::StartUpInChildProcess(aTransport, aOtherProcess);
 }
 
 bool
 ContentChild::RecvSetProcessPrivileges(const ChildPrivileges& aPrivs)
--- a/dom/ipc/ContentChild.h
+++ b/dom/ipc/ContentChild.h
@@ -4,21 +4,18 @@
  * 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_ContentChild_h
 #define mozilla_dom_ContentChild_h
 
 #include "mozilla/Attributes.h"
 #include "mozilla/dom/PContentChild.h"
-#include "mozilla/dom/TabContext.h"
 #include "mozilla/dom/ipc/Blob.h"
-
-#include "nsTArray.h"
-#include "nsIConsoleListener.h"
+#include "nsWeakPtr.h"
 
 struct ChromePackage;
 class nsIDOMBlob;
 class nsIObserver;
 struct ResourceMapping;
 struct OverrideMapping;
 
 namespace mozilla {
@@ -75,20 +72,20 @@ public:
 
     const AppInfo& GetAppInfo() {
         return mAppInfo;
     }
 
     void SetProcessName(const nsAString& aName);
     const void GetProcessName(nsAString& aName);
 
-    PCompositorChild*
+    bool
     AllocPCompositorChild(mozilla::ipc::Transport* aTransport,
                           base::ProcessId aOtherProcess) MOZ_OVERRIDE;
-    PImageBridgeChild*
+    bool
     AllocPImageBridgeChild(mozilla::ipc::Transport* aTransport,
                            base::ProcessId aOtherProcess) MOZ_OVERRIDE;
 
     virtual bool RecvSetProcessPrivileges(const ChildPrivileges& aPrivs);
 
     virtual PBrowserChild* AllocPBrowserChild(const IPCTabContext &aContext,
                                               const uint32_t &chromeFlags);
     virtual bool DeallocPBrowserChild(PBrowserChild*);
--- a/dom/ipc/ContentParent.cpp
+++ b/dom/ipc/ContentParent.cpp
@@ -32,87 +32,80 @@
 #include "mozilla/dom/power/PowerManagerService.h"
 #include "mozilla/dom/DOMStorageIPC.h"
 #include "mozilla/dom/bluetooth/PBluetoothParent.h"
 #include "mozilla/dom/PFMRadioParent.h"
 #include "mozilla/dom/devicestorage/DeviceStorageRequestParent.h"
 #include "mozilla/dom/GeolocationBinding.h"
 #include "mozilla/dom/telephony/TelephonyParent.h"
 #include "SmsParent.h"
-#include "mozilla/Hal.h"
 #include "mozilla/hal_sandbox/PHalParent.h"
 #include "mozilla/ipc/TestShellParent.h"
 #include "mozilla/ipc/InputStreamUtils.h"
 #include "mozilla/layers/CompositorParent.h"
 #include "mozilla/layers/ImageBridgeParent.h"
 #include "mozilla/net/NeckoParent.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/Services.h"
 #include "mozilla/StaticPtr.h"
 #include "mozilla/unused.h"
-#include "nsAppDirectoryServiceDefs.h"
-#include "nsAppDirectoryServiceDefs.h"
 #include "nsAppRunner.h"
 #include "nsAutoPtr.h"
 #include "nsCDefaultURIFixup.h"
 #include "nsCExternalHandlerService.h"
 #include "nsCOMPtr.h"
 #include "nsChromeRegistryChrome.h"
 #include "nsConsoleMessage.h"
 #include "nsConsoleService.h"
 #include "nsDebugImpl.h"
-#include "nsDirectoryServiceDefs.h"
 #include "nsDOMFile.h"
-#include "nsExternalHelperAppService.h"
 #include "nsFrameMessageManager.h"
 #include "nsHashPropertyBag.h"
 #include "nsIAlertsService.h"
 #include "nsIAppsService.h"
 #include "nsIClipboard.h"
 #include "nsIDOMApplicationRegistry.h"
 #include "nsIDOMGeoGeolocation.h"
 #include "nsIDOMWakeLock.h"
 #include "nsIDOMWindow.h"
+#include "nsIExternalProtocolService.h"
 #include "nsIFilePicker.h"
 #include "nsIMemoryReporter.h"
 #include "nsIMozBrowserFrame.h"
 #include "nsIMutable.h"
 #include "nsIObserverService.h"
 #include "nsIPresShell.h"
 #include "nsIRemoteBlob.h"
 #include "nsIScriptError.h"
-#include "nsIScriptSecurityManager.h"
 #include "nsIStyleSheet.h"
 #include "nsISupportsPrimitives.h"
 #include "nsIURIFixup.h"
 #include "nsIWindowWatcher.h"
 #include "nsServiceManagerUtils.h"
 #include "nsStyleSheetService.h"
-#include "nsSystemInfo.h"
 #include "nsThreadUtils.h"
 #include "nsToolkitCompsCID.h"
 #include "nsWidgetsCID.h"
 #include "PreallocatedProcessManager.h"
 #include "ProcessPriorityManager.h"
 #include "SandboxHal.h"
 #include "StructuredCloneUtils.h"
 #include "TabParent.h"
 #include "URIUtils.h"
 #include "nsIWebBrowserChrome.h"
 #include "nsIDocShell.h"
 
+#if defined(ANDROID) || defined(LINUX)
+#include "nsSystemInfo.h"
+#endif
+
 #ifdef ANDROID
 # include "gfxAndroidPlatform.h"
 #endif
 
-#ifdef MOZ_CRASHREPORTER
-# include "nsExceptionHandler.h"
-# include "nsICrashReporter.h"
-#endif
-
 #ifdef MOZ_PERMISSIONS
 # include "nsPermissionManager.h"
 #endif
 
 #ifdef MOZ_WIDGET_ANDROID
 # include "AndroidBridge.h"
 #endif
 
@@ -1777,24 +1770,24 @@ ContentParent::Observe(nsISupports* aSub
              !strcmp(aTopic, "a11y-init-or-shutdown")) {
         unused << SendActivateA11y();
     }
 #endif
 
     return NS_OK;
 }
 
-PCompositorParent*
+bool
 ContentParent::AllocPCompositorParent(mozilla::ipc::Transport* aTransport,
                                       base::ProcessId aOtherProcess)
 {
     return CompositorParent::Create(aTransport, aOtherProcess);
 }
 
-PImageBridgeParent*
+bool
 ContentParent::AllocPImageBridgeParent(mozilla::ipc::Transport* aTransport,
                                        base::ProcessId aOtherProcess)
 {
     return ImageBridgeParent::Create(aTransport, aOtherProcess);
 }
 
 bool
 ContentParent::RecvGetProcessAttributes(uint64_t* aId,
--- a/dom/ipc/ContentParent.h
+++ b/dom/ipc/ContentParent.h
@@ -2,45 +2,37 @@
 /* vim: set sw=4 ts=8 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/. */
 
 #ifndef mozilla_dom_ContentParent_h
 #define mozilla_dom_ContentParent_h
 
-#include "base/waitable_event_watcher.h"
-
 #include "mozilla/dom/PContentParent.h"
-#include "mozilla/dom/PMemoryReportRequestParent.h"
-#include "mozilla/dom/TabContext.h"
 #include "mozilla/ipc/GeckoChildProcessHost.h"
 #include "mozilla/dom/ipc/Blob.h"
 #include "mozilla/Attributes.h"
 #include "mozilla/HalTypes.h"
 #include "mozilla/LinkedList.h"
 #include "mozilla/StaticPtr.h"
 
 #include "nsFrameMessageManager.h"
 #include "nsIObserver.h"
 #include "nsIThreadInternal.h"
-#include "nsNetUtil.h"
-#include "nsIPermissionManager.h"
 #include "nsIDOMGeoPositionCallback.h"
-#include "nsCOMArray.h"
-#include "nsDataHashtable.h"
-#include "nsHashKeys.h"
 #include "PermissionMessageUtils.h"
 
 #define CHILD_PROCESS_SHUTDOWN_MESSAGE NS_LITERAL_STRING("child-process-shutdown")
 
 class mozIApplication;
 class nsConsoleService;
 class nsIDOMBlob;
 class nsIMemoryReporter;
+template<class KeyClass,class DataType> class nsDataHashtable;
 
 namespace mozilla {
 
 namespace ipc {
 class OptionalURIParams;
 class URIParams;
 class TestShellParent;
 } // namespace ipc
@@ -54,16 +46,18 @@ class PCompositorParent;
 } // namespace layers
 
 namespace dom {
 
 class Element;
 class TabParent;
 class PStorageParent;
 class ClonedMessageData;
+class MemoryReport;
+class TabContext;
 
 class ContentParent : public PContentParent
                     , public nsIObserver
                     , public nsIThreadObserver
                     , public nsIDOMGeoPositionCallback
                     , public mozilla::dom::ipc::MessageManagerCallback
                     , public mozilla::LinkedListElement<ContentParent>
 {
@@ -251,20 +245,20 @@ private:
      *
      * If aCloseWithError is true and this is the first call to
      * ShutDownProcess, then we'll close our channel using CloseWithError()
      * rather than vanilla Close().  CloseWithError() indicates to IPC that this
      * is an abnormal shutdown (e.g. a crash).
      */
     void ShutDownProcess(bool aCloseWithError);
 
-    PCompositorParent*
+    bool
     AllocPCompositorParent(mozilla::ipc::Transport* aTransport,
                            base::ProcessId aOtherProcess) MOZ_OVERRIDE;
-    PImageBridgeParent*
+    bool
     AllocPImageBridgeParent(mozilla::ipc::Transport* aTransport,
                             base::ProcessId aOtherProcess) MOZ_OVERRIDE;
 
     virtual bool RecvGetProcessAttributes(uint64_t* aId,
                                           bool* aIsForApp,
                                           bool* aIsForBrowser) MOZ_OVERRIDE;
     virtual bool RecvGetXPCOMProcessAttributes(bool* aIsOffline) MOZ_OVERRIDE;
 
--- a/dom/ipc/CrashReporterChild.h
+++ b/dom/ipc/CrashReporterChild.h
@@ -3,20 +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/. */
 
 #ifndef mozilla_dom_CrashReporterChild_h
 #define mozilla_dom_CrashReporterChild_h
 
 #include "mozilla/dom/PCrashReporterChild.h"
-#ifdef MOZ_CRASHREPORTER
-#include "nsExceptionHandler.h"
-#include "nsXULAppAPI.h"
-#endif
 
 namespace mozilla {
 namespace dom {
 class CrashReporterChild :
     public PCrashReporterChild
 {
  public:
     CrashReporterChild() {
--- a/dom/ipc/CrashReporterParent.cpp
+++ b/dom/ipc/CrashReporterParent.cpp
@@ -1,16 +1,15 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  * vim: set sw=4 ts=8 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 "CrashReporterParent.h"
-
-#include "base/process_util.h"
+#include "nsXULAppAPI.h"
 
 #include <time.h>
 
 using namespace base;
 
 namespace mozilla {
 namespace dom {
 
--- a/dom/ipc/CrashReporterParent.h
+++ b/dom/ipc/CrashReporterParent.h
@@ -1,16 +1,15 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  * vim: set sw=4 ts=8 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 "mozilla/dom/PCrashReporterParent.h"
 #include "mozilla/dom/TabMessageUtils.h"
-#include "nsXULAppAPI.h"
 #include "nsIFile.h"
 #ifdef MOZ_CRASHREPORTER
 #include "nsExceptionHandler.h"
 #include "nsDataHashtable.h"
 #endif
 
 namespace mozilla {
 namespace dom {
--- a/dom/ipc/PreallocatedProcessManager.cpp
+++ b/dom/ipc/PreallocatedProcessManager.cpp
@@ -3,16 +3,17 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "mozilla/PreallocatedProcessManager.h"
 #include "mozilla/ClearOnShutdown.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/dom/ContentParent.h"
+#include "nsIPropertyBag2.h"
 
 using namespace mozilla;
 using namespace mozilla::hal;
 using namespace mozilla::dom;
 
 namespace {
 
 /**
--- a/dom/ipc/PreallocatedProcessManager.h
+++ b/dom/ipc/PreallocatedProcessManager.h
@@ -3,20 +3,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/. */
 
 #ifndef mozilla_PreallocatedProcessManager_h
 #define mozilla_PreallocatedProcessManager_h
 
 #include "base/basictypes.h"
-#include "mozilla/StaticPtr.h"
 #include "nsCOMPtr.h"
 #include "nsIObserver.h"
-#include "nsAutoPtr.h"
 
 namespace mozilla {
 namespace dom {
 class ContentParent;
 }
 
 /**
  * This class manages a ContentParent that it starts up ahead of any particular
--- a/dom/ipc/ProcessPriorityManager.cpp
+++ b/dom/ipc/ProcessPriorityManager.cpp
@@ -11,35 +11,24 @@
 #include "mozilla/dom/TabParent.h"
 #include "mozilla/Hal.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/Services.h"
 #include "mozilla/unused.h"
 #include "AudioChannelService.h"
 #include "prlog.h"
 #include "nsPrintfCString.h"
-#include "nsWeakPtr.h"
 #include "nsXULAppAPI.h"
 #include "nsIFrameLoader.h"
-#include "nsIInterfaceRequestorUtils.h"
-#include "nsITimer.h"
-#include "nsIObserver.h"
 #include "nsIObserverService.h"
-#include "nsIDocument.h"
-#include "nsIDOMEventListener.h"
-#include "nsIDOMWindow.h"
-#include "nsIDOMEvent.h"
-#include "nsIDOMDocument.h"
-#include "nsPIDOMWindow.h"
 #include "StaticPtr.h"
 #include "nsIMozBrowserFrame.h"
 #include "nsIObserver.h"
 #include "nsITimer.h"
-#include "nsPrintfCString.h"
-#include "prlog.h"
+#include "nsIPropertyBag2.h"
 
 #ifdef XP_WIN
 #include <process.h>
 #define getpid _getpid
 #else
 #include <unistd.h>
 #endif
 
--- a/dom/ipc/ProcessPriorityManager.h
+++ b/dom/ipc/ProcessPriorityManager.h
@@ -3,19 +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/. */
 
 #ifndef mozilla_ProcessPriorityManager_h_
 #define mozilla_ProcessPriorityManager_h_
 
 #include "mozilla/HalTypes.h"
-#include "mozilla/StaticPtr.h"
-#include "nsIObserver.h"
-#include "nsDataHashtable.h"
 
 namespace mozilla {
 namespace dom {
 class ContentParent;
 }
 
 /**
  * This class sets the priority of subprocesses in response to explicit
--- a/dom/ipc/StructuredCloneUtils.cpp
+++ b/dom/ipc/StructuredCloneUtils.cpp
@@ -8,17 +8,17 @@
 
 #include "nsIDOMFile.h"
 #include "nsIDOMDOMException.h"
 #include "nsIMutable.h"
 #include "nsIXPConnect.h"
 
 #include "nsContentUtils.h"
 #include "nsJSEnvironment.h"
-#include "nsThreadUtils.h"
+#include "MainThreadUtils.h"
 #include "StructuredCloneTags.h"
 #include "jsapi.h"
 
 using namespace mozilla::dom;
 
 namespace {
 
 void
--- a/dom/ipc/TabChild.cpp
+++ b/dom/ipc/TabChild.cpp
@@ -4,92 +4,68 @@
  * 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 "TabChild.h"
 
 #include "Layers.h"
-#include "Blob.h"
 #include "ContentChild.h"
 #include "IndexedDBChild.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/ClearOnShutdown.h"
 #include "mozilla/IntentionalCrash.h"
 #include "mozilla/docshell/OfflineCacheUpdateChild.h"
-#include "mozilla/dom/PContentChild.h"
 #include "mozilla/dom/PContentDialogChild.h"
 #include "mozilla/ipc/DocumentRendererChild.h"
 #include "mozilla/ipc/FileDescriptorUtils.h"
 #include "mozilla/layers/AsyncPanZoomController.h"
 #include "mozilla/layers/CompositorChild.h"
 #include "mozilla/layers/ImageBridgeChild.h"
-#include "mozilla/layers/PLayerTransactionChild.h"
 #include "mozilla/layers/ShadowLayers.h"
 #include "mozilla/layout/RenderFrameChild.h"
 #include "mozilla/StaticPtr.h"
 #include "mozilla/unused.h"
 #include "mozIApplication.h"
-#include "nsComponentManagerUtils.h"
-#include "nsComponentManagerUtils.h"
 #include "nsContentUtils.h"
 #include "nsCxPusher.h"
 #include "nsEmbedCID.h"
 #include "nsEventListenerManager.h"
 #include <algorithm>
 #ifdef MOZ_CRASHREPORTER
 #include "nsExceptionHandler.h"
 #endif
 #include "mozilla/dom/Element.h"
-#include "nsIAppsService.h"
 #include "nsIBaseWindow.h"
 #include "nsICachedFileDescriptorListener.h"
-#include "nsIComponentManager.h"
+#include "nsIDialogParamBlock.h"
 #include "nsIDocumentInlines.h"
-#include "nsIDOMClassInfo.h"
-#include "nsIDOMElement.h"
+#include "nsIDocShellTreeOwner.h"
 #include "nsIDOMEvent.h"
 #include "nsIDOMWindow.h"
 #include "nsIDOMWindowUtils.h"
 #include "nsIDocShell.h"
-#include "nsIInterfaceRequestorUtils.h"
-#include "nsIInterfaceRequestorUtils.h"
-#include "nsIJSRuntimeService.h"
-#include "nsISSLStatusProvider.h"
-#include "nsIScriptContext.h"
-#include "nsIScriptGlobalObject.h"
-#include "nsIScriptSecurityManager.h"
-#include "nsISecureBrowserUI.h"
-#include "nsIServiceManager.h"
-#include "nsISupportsImpl.h"
 #include "nsIURI.h"
 #include "nsIURIFixup.h"
 #include "nsCDefaultURIFixup.h"
-#include "nsView.h"
 #include "nsIWebBrowser.h"
 #include "nsIWebBrowserFocus.h"
 #include "nsIWebBrowserSetup.h"
 #include "nsIWebProgress.h"
-#include "nsIXPCSecurityManager.h"
 #include "nsInterfaceHashtable.h"
 #include "nsPIDOMWindow.h"
 #include "nsPIWindowRoot.h"
-#include "nsGlobalWindow.h"
 #include "nsLayoutUtils.h"
-#include "nsPresContext.h"
 #include "nsPrintfCString.h"
-#include "nsScriptLoader.h"
-#include "nsSerializationHelper.h"
 #include "nsThreadUtils.h"
 #include "nsWeakReference.h"
 #include "PCOMContentPermissionRequestChild.h"
 #include "PuppetWidget.h"
 #include "StructuredCloneUtils.h"
-#include "xpcpublic.h"
 #include "nsViewportInfo.h"
 #include "JavaScriptChild.h"
 #include "APZCCallbackHelper.h"
 
 #define BROWSER_ELEMENT_CHILD_SCRIPT \
     NS_LITERAL_STRING("chrome://global/content/BrowserElementChild.js")
 
 using namespace mozilla;
--- a/dom/ipc/TabChild.h
+++ b/dom/ipc/TabChild.h
@@ -13,41 +13,33 @@
 #endif /* DEBUG */
 #include "nsIWebNavigation.h"
 #include "nsCOMPtr.h"
 #include "nsAutoPtr.h"
 #include "nsEventDispatcher.h"
 #include "nsIWebBrowserChrome2.h"
 #include "nsIEmbeddingSiteWindow.h"
 #include "nsIWebBrowserChromeFocus.h"
-#include "nsIWidget.h"
 #include "nsIDOMEventListener.h"
 #include "nsIInterfaceRequestor.h"
 #include "nsIWindowProvider.h"
 #include "nsIDOMWindow.h"
 #include "nsIDocShell.h"
-#include "nsIDocShellTreeItem.h"
-#include "nsIDocShellTreeOwner.h"
 #include "nsIDocument.h"
-#include "nsNetUtil.h"
+#include "nsIInterfaceRequestorUtils.h"
 #include "nsFrameMessageManager.h"
 #include "nsIWebProgressListener.h"
 #include "nsDOMEventTargetHelper.h"
 #include "nsIDialogCreator.h"
-#include "nsIDialogParamBlock.h"
 #include "nsIPresShell.h"
-#include "nsIPrincipal.h"
 #include "nsIScriptObjectPrincipal.h"
 #include "nsWeakReference.h"
 #include "nsITabChild.h"
 #include "mozilla/Attributes.h"
-#include "FrameMetrics.h"
-#include "ProcessUtils.h"
 #include "mozilla/dom/TabContext.h"
-#include "mozilla/dom/ContentChild.h"
 
 struct gfxMatrix;
 class nsICachedFileDescriptorListener;
 class nsIDOMWindowUtils;
 
 namespace mozilla {
 namespace layout {
 class RenderFrameChild;
--- a/dom/ipc/TabContext.cpp
+++ b/dom/ipc/TabContext.cpp
@@ -1,18 +1,20 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set sw=2 ts=8 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 "mozilla/dom/TabContext.h"
+#include "mozilla/dom/PTabContext.h"
 #include "mozilla/dom/TabParent.h"
 #include "mozilla/dom/TabChild.h"
 #include "nsIAppsService.h"
+#include "nsIScriptSecurityManager.h"
 
 #define NO_APP_ID (nsIScriptSecurityManager::NO_APP_ID)
 
 using namespace mozilla::dom::ipc;
 using namespace mozilla::layout;
 
 namespace mozilla {
 namespace dom {
--- a/dom/ipc/TabContext.h
+++ b/dom/ipc/TabContext.h
@@ -2,26 +2,25 @@
 /* vim: set sw=2 ts=8 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/. */
 
 #ifndef mozilla_dom_TabContext_h
 #define mozilla_dom_TabContext_h
 
-#include "mozilla/Assertions.h"
-#include "mozilla/dom/PContent.h"
-#include "mozilla/dom/PBrowser.h"
 #include "mozilla/layout/RenderFrameUtils.h"
-#include "nsIScriptSecurityManager.h"
 #include "mozIApplication.h"
+#include "nsCOMPtr.h"
 
 namespace mozilla {
 namespace dom {
 
+struct IPCTabContext;
+
 /**
  * TabContext encapsulates information about an iframe that may be a mozbrowser
  * or mozapp.  You can ask whether a TabContext corresponds to a mozbrowser or
  * mozapp, get the app that contains the browser, and so on.
  *
  * TabParent and TabChild both inherit from TabContext, and you can also have
  * standalone TabContext objects.
  *
--- a/dom/ipc/TabParent.cpp
+++ b/dom/ipc/TabParent.cpp
@@ -3,65 +3,60 @@
 /* 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 "TabParent.h"
 
-#include "Blob.h"
 #include "IDBFactory.h"
 #include "IndexedDBParent.h"
 #include "mozIApplication.h"
 #include "mozilla/BrowserElementParent.h"
 #include "mozilla/docshell/OfflineCacheUpdateParent.h"
 #include "mozilla/dom/ContentParent.h"
 #include "mozilla/Hal.h"
 #include "mozilla/ipc/DocumentRendererParent.h"
 #include "mozilla/layers/CompositorParent.h"
 #include "mozilla/layout/RenderFrameParent.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/unused.h"
 #include "nsCOMPtr.h"
 #include "nsContentPermissionHelper.h"
 #include "nsContentUtils.h"
 #include "nsDebug.h"
-#include "nsEventDispatcher.h"
 #include "nsEventStateManager.h"
 #include "nsFocusManager.h"
 #include "nsFrameLoader.h"
 #include "nsIContent.h"
 #include "nsIDocShell.h"
-#include "nsIDOMApplicationRegistry.h"
+#include "nsIDocShellTreeOwner.h"
 #include "nsIDOMElement.h"
 #include "nsIDOMEvent.h"
-#include "nsIDOMHTMLFrameElement.h"
 #include "nsIDOMWindow.h"
 #include "nsIDialogCreator.h"
+#include "nsIInterfaceRequestorUtils.h"
 #include "nsIPromptFactory.h"
 #include "nsIURI.h"
-#include "nsIMozBrowserFrame.h"
-#include "nsIScriptSecurityManager.h"
 #include "nsIWebBrowserChrome.h"
 #include "nsIXULBrowserWindow.h"
 #include "nsIXULWindow.h"
 #include "nsViewManager.h"
 #include "nsIWidget.h"
 #include "nsIWindowWatcher.h"
-#include "nsNetUtil.h"
 #include "nsPIDOMWindow.h"
 #include "nsPrintfCString.h"
-#include "nsSerializationHelper.h"
 #include "nsServiceManagerUtils.h"
 #include "nsThreadUtils.h"
 #include "private/pprio.h"
 #include "StructuredCloneUtils.h"
 #include "JavaScriptParent.h"
 #include "TabChild.h"
+#include "nsNetCID.h"
 #include <algorithm>
 
 using namespace mozilla::dom;
 using namespace mozilla::ipc;
 using namespace mozilla::layers;
 using namespace mozilla::layout;
 using namespace mozilla::services;
 using namespace mozilla::widget;
--- a/dom/ipc/TabParent.h
+++ b/dom/ipc/TabParent.h
@@ -2,35 +2,29 @@
 /* vim: set sw=4 ts=8 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/. */
 
 #ifndef mozilla_tabs_TabParent_h
 #define mozilla_tabs_TabParent_h
 
-#include "base/basictypes.h"
-
-#include "mozilla/dom/ContentParent.h"
 #include "mozilla/dom/PBrowserParent.h"
 #include "mozilla/dom/PContentDialogParent.h"
 #include "mozilla/dom/TabContext.h"
-#include "mozilla/ipc/GeckoChildProcessHost.h"
 #include "nsCOMPtr.h"
 #include "nsIAuthPromptProvider.h"
 #include "nsIBrowserDOMWindow.h"
 #include "nsIDialogParamBlock.h"
 #include "nsISecureBrowserUI.h"
 #include "nsITabParent.h"
-#include "nsWeakReference.h"
 #include "Units.h"
 #include "js/TypeDecls.h"
 
 struct gfxMatrix;
-class mozIApplication;
 class nsFrameLoader;
 class nsIURI;
 class CpowHolder;
 
 namespace mozilla {
 
 namespace layers {
 struct FrameMetrics;
@@ -39,16 +33,17 @@ struct TextureFactoryIdentifier;
 
 namespace layout {
 class RenderFrameParent;
 }
 
 namespace dom {
 
 class ClonedMessageData;
+class ContentParent;
 class Element;
 struct StructuredCloneData;
 
 class ContentDialogParent : public PContentDialogParent {};
 
 class TabParent : public PBrowserParent 
                 , public nsITabParent 
                 , public nsIAuthPromptProvider
--- a/dom/media/MediaPermissionGonk.cpp
+++ b/dom/media/MediaPermissionGonk.cpp
@@ -13,16 +13,17 @@
 #include "nsISupportsArray.h"
 #include "nsPIDOMWindow.h"
 #include "nsTArray.h"
 #include "GetUserMediaRequest.h"
 #include "PCOMContentPermissionRequestChild.h"
 #include "mozilla/dom/PBrowserChild.h"
 #include "mozilla/dom/TabChild.h"
 #include "mozilla/dom/MediaStreamTrackBinding.h"
+#include "nsISupportsPrimitives.h"
 
 #define AUDIO_PERMISSION_NAME "audio-capture"
 
 namespace mozilla {
 
 static MediaPermissionManager *gMediaPermMgr = nullptr;
 
 // Helper function for notifying permission granted
--- a/dom/media/tests/mochitest/head.js
+++ b/dom/media/tests/mochitest/head.js
@@ -108,28 +108,42 @@ function getUserMedia(constraints, onSuc
  * Setup any Mochitest for WebRTC by enabling the preference for
  * peer connections. As by bug 797979 it will also enable mozGetUserMedia()
  * and disable the mozGetUserMedia() permission checking.
  *
  * @param {Function} aCallback
  *        Test method to execute after initialization
  */
 function runTest(aCallback) {
-  SimpleTest.waitForExplicitFinish();
-  SpecialPowers.pushPrefEnv({'set': [
-    ['media.peerconnection.enabled', true],
-    ['media.navigator.permission.disabled', true]]
-  }, function () {
-    try {
-      aCallback();
-    }
-    catch (err) {
-      unexpectedCallbackAndFinish()(err);
-    }
-  });
+  if (window.SimpleTest) {
+    // Running as a Mochitest.
+    SimpleTest.waitForExplicitFinish();
+    SpecialPowers.pushPrefEnv({'set': [
+      ['media.peerconnection.enabled', true],
+      ['media.navigator.permission.disabled', true]]
+    }, function () {
+      try {
+        aCallback();
+      }
+      catch (err) {
+        unexpectedCallbackAndFinish()(err);
+      }
+    });
+  } else {
+    // Steeplechase, let it call the callback.
+    window.run_test = function(is_initiator) {
+      var options = {is_local: is_initiator,
+                     is_remote: !is_initiator};
+      aCallback(options);
+    };
+    // Also load the steeplechase test code.
+    var s = document.createElement("script");
+    s.src = "/test.js";
+    document.head.appendChild(s);
+  }
 }
 
 /**
  * Checks that the media stream tracks have the expected amount of tracks
  * with the correct kind and id based on the type and constraints given.
  *
  * @param {Object} constraints specifies whether the stream should have
  *                             audio, video, or both
--- a/dom/media/tests/mochitest/pc.js
+++ b/dom/media/tests/mochitest/pc.js
@@ -219,16 +219,30 @@ CommandChain.prototype = {
    *        Identifier of the command
    * @returns {object[]} Removed commands
    */
   replaceBefore : function (id, commands) {
     var oldCommands = this.removeBefore(id);
     this.insertBefore(id, commands);
 
     return oldCommands;
+  },
+
+  /**
+   * Remove all commands whose identifiers match the specified regex.
+   *
+   * @param {regex} id_match
+   *        Regular expression to match command identifiers.
+   */
+  filterOut : function (id_match) {
+    for (var i = this._commands.length - 1; i >= 0; i--) {
+      if (id_match.test(this._commands[i][0])) {
+        this._commands.splice(i, 1);
+      }
+    }
   }
 };
 
 /**
  * This class provides a state checker for media elements which store
  * a media stream to check for media attribute state and events fired.
  * When constructed by a caller, an object instance is created with
  * a media element, event state checkers for canplaythrough, timeupdate, and
@@ -313,54 +327,75 @@ MediaElementChecker.prototype = {
 /**
  * This class handles tests for peer connections.
  *
  * @constructor
  * @param {object} [options={}]
  *        Optional options for the peer connection test
  * @param {object} [options.commands=commandsPeerConnection]
  *        Commands to run for the test
+ * @param {bool}   [options.is_local=true]
+ *        true if this test should run the tests for the "local" side.
+ * @param {bool}   [options.is_remote=true]
+ *        true if this test should run the tests for the "remote" side.
  * @param {object} [options.config_pc1=undefined]
  *        Configuration for the local peer connection instance
  * @param {object} [options.config_pc2=undefined]
  *        Configuration for the remote peer connection instance. If not defined
  *        the configuration from the local instance will be used
  */
 function PeerConnectionTest(options) {
   // If no options are specified make it an empty object
   options = options || { };
   options.commands = options.commands || commandsPeerConnection;
+  options.is_local = "is_local" in options ? options.is_local : true;
+  options.is_remote = "is_remote" in options ? options.is_remote : true;
 
-  this.pcLocal = new PeerConnectionWrapper('pcLocal', options.config_pc1);
-  this.pcRemote = new PeerConnectionWrapper('pcRemote', options.config_pc2 || options.config_pc1);
+  if (options.is_local)
+    this.pcLocal = new PeerConnectionWrapper('pcLocal', options.config_pc1);
+  else
+    this.pcLocal = null;
+
+  if (options.is_remote)
+    this.pcRemote = new PeerConnectionWrapper('pcRemote', options.config_pc2 || options.config_pc1);
+  else
+    this.pcRemote = null;
 
   this.connected = false;
 
   // Create command chain instance and assign default commands
   this.chain = new CommandChain(this, options.commands);
+  if (!options.is_local) {
+    this.chain.filterOut(/^PC_LOCAL/);
+  }
+  if (!options.is_remote) {
+    this.chain.filterOut(/^PC_REMOTE/);
+  }
 
   var self = this;
   this.chain.onFinished = function () {
     self.teardown();
-  }
+  };
 }
 
 /**
  * Closes the peer connection if it is active
  *
  * @param {Function} onSuccess
  *        Callback to execute when the peer connection has been closed successfully
  */
 PeerConnectionTest.prototype.close = function PCT_close(onSuccess) {
   info("Closing peer connections. Connection state=" + this.connected);
 
   // There is no onclose event for the remote peer existent yet. So close it
   // side-by-side with the local peer.
-  this.pcLocal.close();
-  this.pcRemote.close();
+  if (this.pcLocal)
+    this.pcLocal.close();
+  if (this.pcRemote)
+    this.pcRemote.close();
   this.connected = false;
 
   onSuccess();
 };
 
 /**
  * Executes the next command.
  */
@@ -439,28 +474,31 @@ function PCT_setLocalDescription(peer, d
  * Sets the media constraints for both peer connection instances.
  *
  * @param {object} constraintsLocal
  *        Media constrains for the local peer connection instance
  * @param constraintsRemote
  */
 PeerConnectionTest.prototype.setMediaConstraints =
 function PCT_setMediaConstraints(constraintsLocal, constraintsRemote) {
-  this.pcLocal.constraints = constraintsLocal;
-  this.pcRemote.constraints = constraintsRemote;
+  if (this.pcLocal)
+    this.pcLocal.constraints = constraintsLocal;
+  if (this.pcRemote)
+    this.pcRemote.constraints = constraintsRemote;
 };
 
 /**
  * Sets the media constraints used on a createOffer call in the test.
  *
  * @param {object} constraints the media constraints to use on createOffer
  */
 PeerConnectionTest.prototype.setOfferConstraints =
 function PCT_setOfferConstraints(constraints) {
-  this.pcLocal.offerConstraints = constraints;
+  if (this.pcLocal)
+    this.pcLocal.offerConstraints = constraints;
 };
 
 /**
  * Sets the remote description for the specified peer connection instance
  * and automatically handles the failure case.
  *
  * @param {PeerConnectionWrapper} peer
           The peer connection wrapper to run the command on
@@ -501,17 +539,20 @@ PeerConnectionTest.prototype.run = funct
 };
 
 /**
  * Clean up the objects used by the test
  */
 PeerConnectionTest.prototype.teardown = function PCT_teardown() {
   this.close(function () {
     info("Test finished");
-    SimpleTest.finish();
+    if (window.SimpleTest)
+      SimpleTest.finish();
+    else
+      finish();
   });
 };
 
 /**
  * This class handles tests for data channels.
  *
  * @constructor
  * @param {object} [options={}]
--- a/dom/media/tests/mochitest/templates.js
+++ b/dom/media/tests/mochitest/templates.js
@@ -14,69 +14,117 @@ var commandsPeerConnection = [
     'PC_REMOTE_GUM',
     function (test) {
       test.pcRemote.getAllUserMedia(function () {
         test.next();
       });
     }
   ],
   [
-    'PC_CHECK_INITIAL_SIGNALINGSTATE',
+    'PC_LOCAL_CHECK_INITIAL_SIGNALINGSTATE',
     function (test) {
       is(test.pcLocal.signalingState, "stable",
          "Initial local signalingState is 'stable'");
+      test.next();
+    }
+  ],
+  [
+    'PC_REMOTE_CHECK_INITIAL_SIGNALINGSTATE',
+    function (test) {
       is(test.pcRemote.signalingState, "stable",
          "Initial remote signalingState is 'stable'");
       test.next();
     }
   ],
   [
     'PC_LOCAL_CREATE_OFFER',
     function (test) {
       test.createOffer(test.pcLocal, function () {
         is(test.pcLocal.signalingState, "stable",
            "Local create offer does not change signaling state");
+        if (!test.pcRemote) {
+          send_message({"offer": test.pcLocal._last_offer,
+                        "media_constraints": test.pcLocal.constraints});
+        }
         test.next();
       });
     }
   ],
   [
     'PC_LOCAL_SET_LOCAL_DESCRIPTION',
     function (test) {
       test.setLocalDescription(test.pcLocal, test.pcLocal._last_offer, function () {
         is(test.pcLocal.signalingState, "have-local-offer",
            "signalingState after local setLocalDescription is 'have-local-offer'");
         test.next();
       });
     }
   ],
   [
+    'PC_REMOTE_GET_OFFER',
+    function (test) {
+      if (test.pcLocal) {
+        test._local_offer = test.pcLocal._last_offer;
+        test._local_constraints = test.pcLocal.constraints;
+        test.next();
+      } else {
+        wait_for_message().then(function(message) {
+          ok("offer" in message, "Got an offer message");
+          test._local_offer = new mozRTCSessionDescription(message.offer);
+          test._local_constraints = message.media_constraints;
+          test.next();
+        });
+      }
+    }
+  ],
+  [
     'PC_REMOTE_SET_REMOTE_DESCRIPTION',
     function (test) {
-      test.setRemoteDescription(test.pcRemote, test.pcLocal._last_offer, function () {
+      test.setRemoteDescription(test.pcRemote, test._local_offer, function () {
         is(test.pcRemote.signalingState, "have-remote-offer",
            "signalingState after remote setRemoteDescription is 'have-remote-offer'");
         test.next();
       });
     }
   ],
   [
     'PC_REMOTE_CREATE_ANSWER',
     function (test) {
       test.createAnswer(test.pcRemote, function () {
         is(test.pcRemote.signalingState, "have-remote-offer",
            "Remote createAnswer does not change signaling state");
+        if (!test.pcLocal) {
+          send_message({"answer": test.pcRemote._last_answer,
+                        "media_constraints": test.pcRemote.constraints});
+        }
         test.next();
       });
     }
   ],
   [
+    'PC_LOCAL_GET_ANSWER',
+    function (test) {
+      if (test.pcRemote) {
+        test._remote_answer = test.pcRemote._last_answer;
+        test._remote_constraints = test.pcRemote.constraints;
+        test.next();
+      } else {
+        wait_for_message().then(function(message) {
+          ok("answer" in message, "Got an answer message");
+          test._remote_answer = new mozRTCSessionDescription(message.answer);
+          test._remote_constraints = message.media_constraints;
+          test.next();
+        });
+      }
+    }
+  ],
+  [
     'PC_LOCAL_SET_REMOTE_DESCRIPTION',
     function (test) {
-      test.setRemoteDescription(test.pcLocal, test.pcRemote._last_answer, function () {
+      test.setRemoteDescription(test.pcLocal, test._remote_answer, function () {
         is(test.pcLocal.signalingState, "stable",
            "signalingState after local setRemoteDescription is 'stable'");
         test.next();
       });
     }
   ],
   [
     'PC_REMOTE_SET_LOCAL_DESCRIPTION',
@@ -86,24 +134,24 @@ var commandsPeerConnection = [
            "signalingState after remote setLocalDescription is 'stable'");
         test.next();
       });
     }
   ],
   [
     'PC_LOCAL_CHECK_MEDIA_STREAMS',
     function (test) {
-      test.pcLocal.checkMediaStreams(test.pcRemote.constraints);
+      test.pcLocal.checkMediaStreams(test._remote_constraints);
       test.next();
     }
   ],
   [
     'PC_REMOTE_CHECK_MEDIA_STREAMS',
     function (test) {
-      test.pcRemote.checkMediaStreams(test.pcLocal.constraints);
+      test.pcRemote.checkMediaStreams(test._local_constraints);
       test.next();
     }
   ],
   [
     'PC_LOCAL_CHECK_MEDIA_FLOW_PRESENT',
     function (test) {
       test.pcLocal.checkMediaFlowPresent(function () {
         test.next();
--- a/dom/media/tests/mochitest/test_peerConnection_basicAudio.html
+++ b/dom/media/tests/mochitest/test_peerConnection_basicAudio.html
@@ -12,17 +12,17 @@
 <pre id="test">
 <script type="application/javascript">
   createHTML({
     bug: "796892",
     title: "Basic audio-only peer connection"
   });
 
   var test;
-  runTest(function () {
-    test = new PeerConnectionTest();
+  runTest(function (options) {
+    test = new PeerConnectionTest(options);
     test.setMediaConstraints([{audio: true}], [{audio: true}]);
     test.run();
   });
 </script>
 </pre>
 </body>
 </html>
--- a/dom/mobilemessage/src/ipc/SmsChild.cpp
+++ b/dom/mobilemessage/src/ipc/SmsChild.cpp
@@ -6,16 +6,17 @@
 #include "SmsMessage.h"
 #include "MmsMessage.h"
 #include "SmsSegmentInfo.h"
 #include "nsIObserverService.h"
 #include "mozilla/Services.h"
 #include "mozilla/dom/ContentChild.h"
 #include "mozilla/dom/mobilemessage/Constants.h" // For MessageType
 #include "MobileMessageThread.h"
+#include "MainThreadUtils.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 using namespace mozilla::dom::mobilemessage;
 
 namespace {
 
 already_AddRefed<nsISupports>
--- a/dom/network/src/TCPSocketParent.cpp
+++ b/dom/network/src/TCPSocketParent.cpp
@@ -9,16 +9,17 @@
 #include "nsIDOMTCPSocket.h"
 #include "nsCxPusher.h"
 #include "mozilla/unused.h"
 #include "mozilla/AppProcessChecker.h"
 #include "mozilla/net/NeckoCommon.h"
 #include "mozilla/net/PNeckoParent.h"
 #include "mozilla/dom/ContentParent.h"
 #include "mozilla/dom/TabParent.h"
+#include "nsIScriptSecurityManager.h"
 
 namespace IPC {
 
 //Defined in TCPSocketChild.cpp
 extern bool
 DeserializeArrayBuffer(JS::Handle<JSObject*> aObj,
                        const InfallibleTArray<uint8_t>& aBuffer,
                        JS::MutableHandle<JS::Value> aVal);
--- a/dom/plugins/base/nsNPAPIPlugin.cpp
+++ b/dom/plugins/base/nsNPAPIPlugin.cpp
@@ -1917,17 +1917,17 @@ NPError NP_CALLBACK
           needsXEmbed = 0;
         }
       }
       if (windowless || needsXEmbed) {
         (*(Display **)result) = mozilla::DefaultXDisplay();
         return NPERR_NO_ERROR;
       }
     }
-#ifdef MOZ_WIDGET_GTK2
+#if (MOZ_WIDGET_GTK == 2)
     // adobe nppdf calls XtGetApplicationNameAndClass(display,
     // &instance, &class) we have to init Xt toolkit before get
     // XtDisplay just call gtk_xtbin_new(w,0) once
     static GtkWidget *gtkXtBinHolder = 0;
     if (!gtkXtBinHolder) {
       gtkXtBinHolder = gtk_xtbin_new(gdk_get_default_root_window(),0);
       // it crashes on destroy, let it leak
       // gtk_widget_destroy(gtkXtBinHolder);
@@ -1938,17 +1938,17 @@ NPError NP_CALLBACK
 #endif
     return NPERR_GENERIC_ERROR;
   }
 
   case NPNVxtAppContext:
     return NPERR_GENERIC_ERROR;
 #endif
 
-#if defined(XP_WIN) || defined(XP_OS2) || defined(MOZ_WIDGET_GTK2) \
+#if defined(XP_WIN) || defined(XP_OS2) || (MOZ_WIDGET_GTK == 2) \
  || defined(MOZ_WIDGET_QT)
   case NPNVnetscapeWindow: {
     if (!npp || !npp->ndata)
       return NPERR_INVALID_INSTANCE_ERROR;
 
     nsNPAPIPluginInstance *inst = (nsNPAPIPluginInstance *) npp->ndata;
 
     nsRefPtr<nsPluginInstanceOwner> owner = inst->GetOwner();
--- a/dom/plugins/base/nsNPAPIPluginInstance.cpp
+++ b/dom/plugins/base/nsNPAPIPluginInstance.cpp
@@ -552,17 +552,17 @@ nsNPAPIPluginInstance::Start()
 }
 
 nsresult nsNPAPIPluginInstance::SetWindow(NPWindow* window)
 {
   // NPAPI plugins don't want a SetWindow(NULL).
   if (!window || RUNNING != mRunning)
     return NS_OK;
 
-#if defined(MOZ_WIDGET_GTK2)
+#if (MOZ_WIDGET_GTK == 2)
   // bug 108347, flash plugin on linux doesn't like window->width <=
   // 0, but Java needs wants this call.
   if (!nsPluginHost::IsJavaMIMEType(mMIMEType) && window->type == NPWindowTypeWindow &&
       (window->width <= 0 || window->height <= 0)) {
     return NS_OK;
   }
 #endif
 
--- a/dom/plugins/base/nsPluginInstanceOwner.cpp
+++ b/dom/plugins/base/nsPluginInstanceOwner.cpp
@@ -70,17 +70,17 @@ static NS_DEFINE_CID(kAppShellCID, NS_AP
 #include <winuser.h>
 #endif
 
 #ifdef XP_MACOSX
 #include <Carbon/Carbon.h>
 #include "nsPluginUtilsOSX.h"
 #endif
 
-#ifdef MOZ_WIDGET_GTK2
+#if (MOZ_WIDGET_GTK == 2)
 #include <gdk/gdk.h>
 #include <gdk/gdkx.h>
 #include <gtk/gtk.h>
 #endif
 
 #ifdef MOZ_WIDGET_ANDROID
 #include "ANPBase.h"
 #include "AndroidBridge.h"
--- a/dom/plugins/base/nsPluginStreamListenerPeer.cpp
+++ b/dom/plugins/base/nsPluginStreamListenerPeer.cpp
@@ -732,17 +732,17 @@ nsresult nsPluginStreamListenerPeer::Ser
   
   // mPluginInstance->Stop calls mPStreamListener->CleanUpStream(), so stream will be properly clean up
   mPluginInstance->Stop();
   mPluginInstance->Start();
   nsRefPtr<nsPluginInstanceOwner> owner = mPluginInstance->GetOwner();
   if (owner) {
     NPWindow* window = nullptr;
     owner->GetWindow(window);
-#if defined(MOZ_WIDGET_GTK2) || defined(MOZ_WIDGET_QT)
+#if (MOZ_WIDGET_GTK == 2) || defined(MOZ_WIDGET_QT)
     // Should call GetPluginPort() here.
     // This part is copied from nsPluginInstanceOwner::GetPluginPort(). 
     nsCOMPtr<nsIWidget> widget;
     ((nsPluginNativeWindow*)window)->GetPluginWidget(getter_AddRefs(widget));
     if (widget) {
       window->window = widget->GetNativeData(NS_NATIVE_PLUGIN_PORT);
     }
 #endif
--- a/dom/plugins/base/nsPluginTags.h
+++ b/dom/plugins/base/nsPluginTags.h
@@ -8,17 +8,17 @@
 
 #include "mozilla/Attributes.h"
 #include "nscore.h"
 #include "nsAutoPtr.h"
 #include "nsCOMPtr.h"
 #include "nsCOMArray.h"
 #include "nsIPluginTag.h"
 #include "nsITimer.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 
 class nsPluginHost;
 struct PRLibrary;
 struct nsPluginInfo;
 class nsNPAPIPlugin;
 
 // A linked-list of plugin information that is used for instantiating plugins
 // and reflecting plugin information into JavaScript.
--- a/dom/plugins/base/nsPluginsDirUnix.cpp
+++ b/dom/plugins/base/nsPluginsDirUnix.cpp
@@ -6,16 +6,17 @@
 #include "nsNPAPIPlugin.h"
 #include "nsNPAPIPluginInstance.h"
 #include "nsIMemory.h"
 #include "nsPluginsDir.h"
 #include "nsPluginsDirUtils.h"
 #include "prmem.h"
 #include "prenv.h"
 #include "prerror.h"
+#include "prio.h"
 #include <sys/stat.h>
 #include "nsString.h"
 #include "nsIFile.h"
 #include "nsIPrefBranch.h"
 #include "nsIPrefService.h"
 
 #define LOCAL_PLUGIN_DLL_SUFFIX ".so"
 #if defined(__hpux)
@@ -34,17 +35,17 @@
 #define DEFAULT_X11_PATH "/usr/X11R6/lib"
 #undef LOCAL_PLUGIN_DLL_SUFFIX
 #define LOCAL_PLUGIN_DLL_SUFFIX ".dylib"
 #define LOCAL_PLUGIN_DLL_ALT_SUFFIX ".so"
 #else
 #define DEFAULT_X11_PATH ""
 #endif
 
-#if defined(MOZ_WIDGET_GTK2)
+#if (MOZ_WIDGET_GTK == 2)
 
 #define PLUGIN_MAX_LEN_OF_TMP_ARR 512
 
 static void DisplayPR_LoadLibraryErrorMessage(const char *libName)
 {
     char errorMsg[PLUGIN_MAX_LEN_OF_TMP_ARR] = "Cannot get error from NSPR.";
     if (PR_GetErrorTextLength() < (int) sizeof(errorMsg))
         PR_GetErrorText(errorMsg);
@@ -260,17 +261,17 @@ nsresult nsPluginFile::LoadPlugin(PRLibr
     nsresult rv;
     nsAutoCString path;
     rv = mPlugin->GetNativePath(path);
     if (NS_FAILED(rv))
         return rv;
 
     libSpec.value.pathname = path.get();
 
-#if defined(MOZ_WIDGET_GTK2)
+#if (MOZ_WIDGET_GTK == 2)
 
     // Normally, Mozilla isn't linked against libXt and libXext
     // since it's a Gtk/Gdk application.  On the other hand,
     // legacy plug-ins expect the libXt and libXext symbols
     // to already exist in the global name space.  This plug-in
     // wrapper is linked against libXt and libXext, but since
     // we never call on any of these libraries, plug-ins still
     // fail to resolve Xt symbols when trying to do a dlopen
--- a/dom/plugins/ipc/PluginIdentifierChild.h
+++ b/dom/plugins/ipc/PluginIdentifierChild.h
@@ -6,17 +6,17 @@
 
 #ifndef dom_plugins_PluginIdentifierChild_h
 #define dom_plugins_PluginIdentifierChild_h
 
 #include "mozilla/plugins/PPluginIdentifierChild.h"
 #include "npapi.h"
 #include "npruntime.h"
 
-#include "nsStringGlue.h"
+#include "nsString.h"
 
 namespace mozilla {
 namespace plugins {
 
 class PluginModuleChild;
 
 /**
  * Plugin identifiers may be "temporary", see the comment on the
--- a/dom/plugins/ipc/PluginInstanceChild.cpp
+++ b/dom/plugins/ipc/PluginInstanceChild.cpp
@@ -1096,17 +1096,17 @@ PluginInstanceChild::AnswerNPP_SetWindow
     FindVisualAndDepth(mWsInfo.display, aWindow.visualID,
                        &mWsInfo.visual, &depth);
     mWsInfo.depth = depth;
 
     if (!mWindow.window && mWindow.type == NPWindowTypeWindow) {
         CreateWindow(aWindow);
     }
 
-#ifdef MOZ_WIDGET_GTK2
+#if (MOZ_WIDGET_GTK == 2)
     if (mXEmbed && gtk_check_version(2,18,7) != NULL) { // older
         if (aWindow.type == NPWindowTypeWindow) {
             GdkWindow* socket_window = gdk_window_lookup(static_cast<GdkNativeWindow>(aWindow.window));
             if (socket_window) {
                 // A GdkWindow for the socket already exists.  Need to
                 // workaround https://bugzilla.gnome.org/show_bug.cgi?id=607061
                 // See wrap_gtk_plug_embedded in PluginModuleChild.cpp.
                 g_object_set_data(G_OBJECT(socket_window),
--- a/dom/plugins/ipc/PluginMessageUtils.h
+++ b/dom/plugins/ipc/PluginMessageUtils.h
@@ -13,17 +13,17 @@
 #include "mozilla/ipc/RPCChannel.h"
 #include "mozilla/ipc/CrossProcessMutex.h"
 #include "gfxipc/ShadowLayerUtils.h"
 
 #include "npapi.h"
 #include "npruntime.h"
 #include "npfunctions.h"
 #include "nsAutoPtr.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 #include "nsTArray.h"
 #include "prlog.h"
 #include "nsHashKeys.h"
 #ifdef MOZ_CRASHREPORTER
 #  include "nsExceptionHandler.h"
 #endif
 #ifdef XP_MACOSX
 #include "PluginInterposeOSX.h"
--- a/dom/plugins/ipc/PluginModuleParent.cpp
+++ b/dom/plugins/ipc/PluginModuleParent.cpp
@@ -488,29 +488,20 @@ PluginModuleParent::TerminateChildProces
     if (!GetProcessCpuUsage(processHandles, mPluginCpuUsageOnHang)) {
       mPluginCpuUsageOnHang.Clear();
     }
 #endif
 
     // this must run before the error notification from the channel,
     // or not at all
     bool isFromHangUI = aMsgLoop != MessageLoop::current();
-    if (isFromHangUI) {
-        // If we're posting from a different thread we can't create
-        // the task via mTaskFactory
-        aMsgLoop->PostTask(FROM_HERE,
-                           NewRunnableMethod(this,
-                               &PluginModuleParent::CleanupFromTimeout,
-                               isFromHangUI));
-    } else {
-        aMsgLoop->PostTask(
-            FROM_HERE,
-            mTaskFactory.NewRunnableMethod(
-                &PluginModuleParent::CleanupFromTimeout, isFromHangUI));
-    }
+    aMsgLoop->PostTask(
+        FROM_HERE,
+        mTaskFactory.NewRunnableMethod(
+            &PluginModuleParent::CleanupFromTimeout, isFromHangUI));
 
     if (!KillProcess(OtherProcess(), 1, false))
         NS_WARNING("failed to kill subprocess!");
 }
 
 #ifdef XP_WIN
 void
 PluginModuleParent::EvaluateHangUIState(const bool aReset)
--- a/dom/plugins/ipc/PluginModuleParent.h
+++ b/dom/plugins/ipc/PluginModuleParent.h
@@ -5,16 +5,17 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef mozilla_plugins_PluginModuleParent_h
 #define mozilla_plugins_PluginModuleParent_h
 
 #include "base/process.h"
 #include "mozilla/FileUtils.h"
 #include "mozilla/PluginLibrary.h"
+#include "mozilla/plugins/ScopedMethodFactory.h"
 #include "mozilla/plugins/PluginProcessParent.h"
 #include "mozilla/plugins/PPluginModuleParent.h"
 #include "npapi.h"
 #include "npfunctions.h"
 #include "nsAutoPtr.h"
 #include "nsDataHashtable.h"
 #include "nsHashKeys.h"
 #include "nsIObserver.h"
@@ -297,17 +298,17 @@ private:
     // the plugin thread in mSubprocess
     NativeThreadId mPluginThread;
     bool mShutdown;
     bool mClearSiteDataSupported;
     bool mGetSitesWithDataSupported;
     const NPNetscapeFuncs* mNPNIface;
     nsDataHashtable<nsPtrHashKey<void>, PluginIdentifierParent*> mIdentifiers;
     nsNPAPIPlugin* mPlugin;
-    ScopedRunnableMethodFactory<PluginModuleParent> mTaskFactory;
+    ScopedMethodFactory<PluginModuleParent> mTaskFactory;
     nsString mPluginDumpID;
     nsString mBrowserDumpID;
     nsString mHangID;
     nsRefPtr<nsIObserver> mProfilerObserver;
 #ifdef XP_WIN
     InfallibleTArray<float> mPluginCpuUsageOnHang;
     PluginHangUIParent *mHangUIParent;
     bool mHangUIEnabled;
new file mode 100644
--- /dev/null
+++ b/dom/plugins/ipc/ScopedMethodFactory.h
@@ -0,0 +1,87 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_plugins_ScopedMethodFactory_h
+#define mozilla_plugins_ScopedMethodFactory_h
+
+#include <base/task.h>
+
+/*
+ * This is based on the ScopedRunnableMethodFactory from ipc/chromium/src/base/task.h
+ * Chromiums factories assert if tasks are created and run on different threads,
+ * which is something we need to do in PluginModuleParent (hang UI vs. main thread).
+ * ScopedMethodFactory just provides cancellable tasks that don't assert this.
+ */
+
+namespace mozilla {
+namespace plugins {
+
+template<class T>
+class ScopedMethodFactory : public RevocableStore
+{
+private:
+  template<class TaskType>
+  class TaskWrapper : public TaskType
+  {
+  public:
+    explicit TaskWrapper(RevocableStore* store) : revocable_(store) { }
+
+    virtual void Run() {
+      if (!revocable_.revoked())
+        TaskType::Run();
+    }
+
+  private:
+    Revocable revocable_;
+  };
+
+public:
+  explicit ScopedMethodFactory(T* object) : object_(object) { }
+
+  template <class Method>
+  inline Task* NewRunnableMethod(Method method) {
+    typedef TaskWrapper<RunnableMethod<Method, Tuple0> > TaskWrapper;
+
+    TaskWrapper* task = new TaskWrapper(this);
+    task->Init(object_, method, MakeTuple());
+    return task;
+  }
+
+  template <class Method, class A>
+  inline Task* NewRunnableMethod(Method method, const A& a) {
+    typedef TaskWrapper<RunnableMethod<Method, Tuple1<A> > > TaskWrapper;
+
+    TaskWrapper* task = new TaskWrapper(this);
+    task->Init(object_, method, MakeTuple(a));
+    return task;
+  }
+
+protected:
+  template <class Method, class Params>
+  class RunnableMethod : public Task {
+   public:
+    RunnableMethod() { }
+
+    void Init(T* obj, Method meth, const Params& params) {
+      obj_ = obj;
+      meth_ = meth;
+      params_ = params;
+    }
+
+    virtual void Run() { DispatchToMethod(obj_, meth_, params_); }
+
+   private:
+    T* obj_;
+    Method meth_;
+    Params params_;
+  };
+
+private:
+  T* object_;
+};
+
+} // namespace plugins
+} // namespace mozilla
+
+#endif // mozilla_plugins_ScopedMethodFactory_h
--- a/dom/plugins/ipc/moz.build
+++ b/dom/plugins/ipc/moz.build
@@ -34,16 +34,17 @@ EXPORTS.mozilla.plugins += [
     'PluginProcessParent.h',
     'PluginScriptableObjectChild.h',
     'PluginScriptableObjectParent.h',
     'PluginScriptableObjectUtils-inl.h',
     'PluginScriptableObjectUtils.h',
     'PluginStreamChild.h',
     'PluginStreamParent.h',
     'PluginUtilsOSX.h',
+    'ScopedMethodFactory.h',
     'StreamNotifyChild.h',
     'StreamNotifyParent.h',
 ]
 
 if CONFIG['OS_ARCH'] == 'WINNT':
     EXPORTS.mozilla.plugins += [
         'PluginSurfaceParent.h',
     ]
--- a/dom/power/WakeLock.cpp
+++ b/dom/power/WakeLock.cpp
@@ -9,16 +9,17 @@
 #include "mozilla/HalWakeLock.h"
 #include "nsDOMClassInfoID.h"
 #include "nsDOMEvent.h"
 #include "nsError.h"
 #include "nsIDocument.h"
 #include "nsIDOMWindow.h"
 #include "nsIDOMEvent.h"
 #include "nsPIDOMWindow.h"
+#include "nsIPropertyBag2.h"
 
 DOMCI_DATA(MozWakeLock, mozilla::dom::power::WakeLock)
 
 using namespace mozilla::hal;
 
 namespace mozilla {
 namespace dom {
 namespace power {
--- a/dom/quota/FileStreams.cpp
+++ b/dom/quota/FileStreams.cpp
@@ -2,16 +2,17 @@
 /* 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 "FileStreams.h"
 
 #include "QuotaManager.h"
+#include "prio.h"
 
 USING_QUOTA_NAMESPACE
 
 template <class FileStreamBase>
 NS_IMETHODIMP
 FileQuotaStream<FileStreamBase>::SetEOF()
 {
   nsresult rv = FileStreamBase::SetEOF();
--- a/dom/quota/QuotaCommon.h
+++ b/dom/quota/QuotaCommon.h
@@ -5,17 +5,17 @@
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef mozilla_dom_quota_quotacommon_h__
 #define mozilla_dom_quota_quotacommon_h__
 
 #include "nsAutoPtr.h"
 #include "nsCOMPtr.h"
 #include "nsDebug.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 #include "nsTArray.h"
 
 #define BEGIN_QUOTA_NAMESPACE \
   namespace mozilla { namespace dom { namespace quota {
 #define END_QUOTA_NAMESPACE \
   } /* namespace quota */ } /* namespace dom */ } /* namespace mozilla */
 #define USING_QUOTA_NAMESPACE \
   using namespace mozilla::dom::quota;
--- a/dom/src/notification/DesktopNotification.cpp
+++ b/dom/src/notification/DesktopNotification.cpp
@@ -7,16 +7,17 @@
 #include "nsXULAppAPI.h"
 #include "mozilla/dom/PBrowserChild.h"
 #include "nsIDOMDesktopNotification.h"
 #include "TabChild.h"
 #include "mozilla/Preferences.h"
 #include "nsGlobalWindow.h"
 #include "nsIAppsService.h"
 #include "PCOMContentPermissionRequestChild.h"
+#include "nsIScriptSecurityManager.h"
 
 namespace mozilla {
 namespace dom {
 
 /*
  * Simple Request
  */
 class DesktopNotificationRequest : public nsIContentPermissionRequest,
--- a/dom/src/notification/Notification.cpp
+++ b/dom/src/notification/Notification.cpp
@@ -12,16 +12,17 @@
 #include "nsIAlertsService.h"
 #include "nsIContentPermissionPrompt.h"
 #include "nsIDocument.h"
 #include "nsIPermissionManager.h"
 #include "nsServiceManagerUtils.h"
 #include "nsToolkitCompsCID.h"
 #include "nsGlobalWindow.h"
 #include "nsDOMJSUtils.h"
+#include "nsIScriptSecurityManager.h"
 #ifdef MOZ_B2G
 #include "nsIDOMDesktopNotification.h"
 #include "nsIAppsService.h"
 #endif
 
 namespace mozilla {
 namespace dom {
 
--- a/dom/src/storage/DOMStorageIPC.cpp
+++ b/dom/src/storage/DOMStorageIPC.cpp
@@ -5,16 +5,17 @@
 
 #include "DOMStorageIPC.h"
 
 #include "DOMStorageManager.h"
 
 #include "mozilla/dom/ContentChild.h"
 #include "mozilla/unused.h"
 #include "nsIDiskSpaceWatcher.h"
+#include "nsThreadUtils.h"
 
 namespace mozilla {
 namespace dom {
 
 // ----------------------------------------------------------------------------
 // Child
 // ----------------------------------------------------------------------------
 
--- a/dom/system/gonk/SystemWorkerManager.h
+++ b/dom/system/gonk/SystemWorkerManager.h
@@ -20,17 +20,17 @@
 
 #include "nsIInterfaceRequestor.h"
 #include "nsISystemWorkerManager.h"
 #include "nsIObserver.h"
 #include "nsAutoPtr.h"
 #include "nsCOMPtr.h"
 #include "nsDebug.h"
 #include "nsDOMEventTargetHelper.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 #include "nsTArray.h"
 
 class nsIWorkerHolder;
 
 namespace mozilla {
 
 namespace ipc {
   class RilConsumer;
--- a/dom/system/gonk/nsVolumeMountLock.cpp
+++ b/dom/system/gonk/nsVolumeMountLock.cpp
@@ -7,16 +7,17 @@
 #include "mozilla/dom/ContentChild.h"
 #include "mozilla/Services.h"
 
 #include "nsIObserverService.h"
 #include "nsIPowerManagerService.h"
 #include "nsIVolume.h"
 #include "nsIVolumeService.h"
 #include "nsString.h"
+#include "nsXULAppAPI.h"
 
 #define VOLUME_MANAGER_LOG_TAG  "nsVolumeMountLock"
 #include "VolumeManagerLog.h"
 
 using namespace mozilla::dom;
 using namespace mozilla::services;
 
 namespace mozilla {
--- a/dom/telephony/TelephonyCommon.h
+++ b/dom/telephony/TelephonyCommon.h
@@ -9,17 +9,17 @@
 
 #include "mozilla/Attributes.h"
 #include "mozilla/ErrorResult.h"
 #include "nsAutoPtr.h"
 #include "nsCOMPtr.h"
 #include "nsCycleCollectionParticipant.h"
 #include "nsDebug.h"
 #include "nsDOMEventTargetHelper.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 #include "nsTArray.h"
 
 #define BEGIN_TELEPHONY_NAMESPACE \
   namespace mozilla { namespace dom { namespace telephony {
 #define END_TELEPHONY_NAMESPACE \
   } /* namespace telephony */ } /* namespace dom */ } /* namespace mozilla */
 #define USING_TELEPHONY_NAMESPACE \
   using namespace mozilla::dom::telephony;
--- a/dom/webidl/InputMethod.webidl
+++ b/dom/webidl/InputMethod.webidl
@@ -18,16 +18,20 @@ interface MozInputMethod : EventTarget {
   // Note that if the app saves the original context, it might get
   // void; implementation decides when to void the input context.
   attribute EventHandler oninputcontextchange;
 
   // An "input context" is mapped to a text field that the app is
   // allow to mutate.  this attribute should be null when there is no
   // text field currently focused.
   readonly attribute MozInputContext? inputcontext;
+
+  [ChromeOnly]
+  // Activate or decactive current input method window.
+  void setActive(boolean isActive);
 };
 
 // Manages the list of IMEs, enables/disables IME and switches to an
 // IME.
 [JSImplementation="@mozilla.org/b2g-imm;1"]
 interface MozInputMethodManager {
   // Ask the OS to show a list of available IMEs for users to switch from.
   // OS should ignore this request if the app is currently not the active one.
--- a/dom/webidl/TextTrack.webidl
+++ b/dom/webidl/TextTrack.webidl
@@ -29,18 +29,19 @@ interface TextTrack : EventTarget {
 
   readonly attribute DOMString id;
   readonly attribute DOMString inBandMetadataTrackDispatchType;
 
            attribute TextTrackMode mode;
 
   readonly attribute TextTrackCueList? cues;
   readonly attribute TextTrackCueList? activeCues;
-  readonly attribute TextTrackRegionList? regions;
+  readonly attribute VTTRegionList? regions;
 
   void addCue(VTTCue cue);
+  [Throws]
   void removeCue(VTTCue cue);
 
            attribute EventHandler oncuechange;
   [Throws]
-  void removeRegion(TextTrackRegion region);
-  void addRegion(TextTrackRegion region);
+  void removeRegion(VTTRegion region);
+  void addRegion(VTTRegion region);
 };
--- a/dom/webidl/VTTCue.webidl
+++ b/dom/webidl/VTTCue.webidl
@@ -29,16 +29,17 @@ enum DirectionSetting {
  Pref="media.webvtt.enabled"]
 interface VTTCue : EventTarget {
   readonly attribute TextTrack? track;
 
   attribute DOMString id;
   attribute double startTime;
   attribute double endTime;
   attribute boolean pauseOnExit;
+  attribute DOMString regionId;
   attribute DirectionSetting vertical;
   attribute boolean snapToLines;
   // XXXhumph: https://www.w3.org/Bugs/Public/show_bug.cgi?id=20651
   // attribute (long or AutoKeyword) line;
   [SetterThrows]
   attribute long position;
   [SetterThrows]
   attribute long size;
rename from dom/webidl/TextTrackRegion.webidl
rename to dom/webidl/VTTRegion.webidl
--- a/dom/webidl/TextTrackRegion.webidl
+++ b/dom/webidl/VTTRegion.webidl
@@ -2,30 +2,29 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/.
  *
  * The origin of this IDL file is
  *  http://dev.w3.org/html5/webvtt/#extension-of-the-texttrack-interface-for-region-support
  */
 
+[Constructor, Pref="media.webvtt.enabled"]
+interface VTTRegion {
+  readonly attribute TextTrack? track;
+           attribute DOMString id;
 
-[Constructor, Pref="media.webvtt.enabled"]
-interface TextTrackRegion {
-  readonly attribute TextTrack? track;
-           attribute DOMString id;
-
-           [SetterThrows]
-           attribute double width;
-
-           attribute long lines;
-
-           [SetterThrows]
-           attribute double regionAnchorX;
-           [SetterThrows]
-           attribute double regionAnchorY;
-           [SetterThrows]
-           attribute double viewportAnchorX;
-           [SetterThrows]
+           [SetterThrows]
+           attribute double width;
+
+           attribute long lines;
+
+           [SetterThrows]
+           attribute double regionAnchorX;
+           [SetterThrows]
+           attribute double regionAnchorY;
+           [SetterThrows]
+           attribute double viewportAnchorX;
+           [SetterThrows]
            attribute double viewportAnchorY;
-           [SetterThrows]
+           [SetterThrows]
            attribute DOMString scroll;
 };
rename from dom/webidl/TextTrackRegionList.webidl
rename to dom/webidl/VTTRegionList.webidl
--- a/dom/webidl/TextTrackRegionList.webidl
+++ b/dom/webidl/VTTRegionList.webidl
@@ -2,16 +2,14 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/.
  *
  * The origin of this IDL file is
  *  http://dev.w3.org/html5/webvtt/#extension-of-the-texttrack-interface-for-region-support
  */
 
-
 [Pref="media.webvtt.enabled"]
-interface TextTrackRegionList {
+interface VTTRegionList {
   readonly attribute unsigned long length;
-  getter TextTrackRegion (unsigned long index);
-  TextTrackRegion? getRegionById(DOMString id);
+  getter VTTRegion (unsigned long index);
+  VTTRegion? getRegionById(DOMString id);
 };
-
--- a/dom/webidl/moz.build
+++ b/dom/webidl/moz.build
@@ -376,32 +376,32 @@ WEBIDL_FILES = [
     'TelephonyCall.webidl',
     'TelephonyCallGroup.webidl',
     'Text.webidl',
     'TextDecoder.webidl',
     'TextEncoder.webidl',
     'TextTrack.webidl',
     'TextTrackCueList.webidl',
     'TextTrackList.webidl',
-    'TextTrackRegion.webidl',
-    'TextTrackRegionList.webidl',
     'TimeEvent.webidl',
     'TimeRanges.webidl',
     'Touch.webidl',
     'TouchEvent.webidl',
     'TouchList.webidl',
     'TransitionEvent.webidl',
     'TreeColumns.webidl',
     'TreeWalker.webidl',
     'UIEvent.webidl',
     'UndoManager.webidl',
     'URL.webidl',
     'URLUtils.webidl',
     'URLUtilsReadOnly.webidl',
     'VTTCue.webidl',
+    'VTTRegion.webidl',
+    'VTTRegionList.webidl',
     'ValidityState.webidl',
     'VideoPlaybackQuality.webidl',
     'VideoStreamTrack.webidl',
     'WaveShaperNode.webidl',
     'WebComponents.webidl',
     'WebSocket.webidl',
     'WheelEvent.webidl',
     'WifiOptions.webidl',
--- a/dom/workers/ChromeWorkerScope.cpp
+++ b/dom/workers/ChromeWorkerScope.cpp
@@ -4,17 +4,17 @@
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "ChromeWorkerScope.h"
 
 #include "jsapi.h"
 
 #include "nsXPCOM.h"
 #include "nsNativeCharsetUtils.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 
 #include "WorkerPrivate.h"
 
 using namespace mozilla::dom;
 USING_WORKERS_NAMESPACE
 
 namespace {
 
--- a/dom/workers/File.cpp
+++ b/dom/workers/File.cpp
@@ -9,17 +9,17 @@
 #include "nsIDOMFile.h"
 #include "nsDOMBlobBuilder.h"
 #include "nsError.h"
 
 #include "jsapi.h"
 #include "jsfriendapi.h"
 #include "nsCOMPtr.h"
 #include "nsJSUtils.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 
 #include "mozilla/dom/Exceptions.h"
 #include "WorkerInlines.h"
 #include "WorkerPrivate.h"
 
 USING_WORKERS_NAMESPACE
 using mozilla::dom::Throw;
 
--- a/dom/workers/FileReaderSync.h
+++ b/dom/workers/FileReaderSync.h
@@ -6,17 +6,17 @@
 
 #ifndef mozilla_dom_workers_filereadersync_h__
 #define mozilla_dom_workers_filereadersync_h__
 
 #include "Workers.h"
 #include "mozilla/dom/workers/bindings/DOMBindingBase.h"
 
 #include "nsICharsetDetectionObserver.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 #include "mozilla/Attributes.h"
 
 class nsIInputStream;
 class nsIDOMBlob;
 
 namespace mozilla {
 class ErrorResult;
 
--- a/dom/workers/Navigator.h
+++ b/dom/workers/Navigator.h
@@ -3,17 +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 mozilla_dom_workers_navigator_h__
 #define mozilla_dom_workers_navigator_h__
 
 #include "Workers.h"
 #include "mozilla/dom/workers/bindings/DOMBindingBase.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 
 BEGIN_WORKERS_NAMESPACE
 
 class WorkerNavigator MOZ_FINAL : public DOMBindingBase
 {
   nsString mAppName;
   nsString mAppVersion;
   nsString mPlatform;
--- a/dom/workers/RuntimeService.h
+++ b/dom/workers/RuntimeService.h
@@ -13,17 +13,17 @@
 
 #include "mozilla/Attributes.h"
 #include "mozilla/Mutex.h"
 #include "mozilla/TimeStamp.h"
 #include "nsAutoPtr.h"
 #include "nsClassHashtable.h"
 #include "nsCOMPtr.h"
 #include "nsHashKeys.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 #include "nsTArray.h"
 
 class nsIThread;
 class nsITimer;
 class nsPIDOMWindow;
 
 BEGIN_WORKERS_NAMESPACE
 
--- a/dom/workers/ScriptLoader.cpp
+++ b/dom/workers/ScriptLoader.cpp
@@ -20,17 +20,17 @@
 #include "nsChannelPolicy.h"
 #include "nsError.h"
 #include "nsContentPolicyUtils.h"
 #include "nsContentUtils.h"
 #include "nsDocShellCID.h"
 #include "nsISupportsPrimitives.h"
 #include "nsNetUtil.h"
 #include "nsScriptLoader.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 #include "nsTArray.h"
 #include "nsThreadUtils.h"
 #include "nsXPCOM.h"
 #include "xpcpublic.h"
 
 #include "mozilla/dom/Exceptions.h"
 #include "Principal.h"
 #include "WorkerFeature.h"
--- a/dom/workers/WorkerPrivate.h
+++ b/dom/workers/WorkerPrivate.h
@@ -17,17 +17,17 @@
 
 #include "mozilla/Assertions.h"
 #include "mozilla/CondVar.h"
 #include "mozilla/Mutex.h"
 #include "mozilla/TimeStamp.h"
 #include "nsAutoPtr.h"
 #include "nsCOMPtr.h"
 #include "nsEventQueue.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 #include "nsTArray.h"
 #include "nsTPriorityQueue.h"
 #include "StructuredCloneTags.h"
 
 #include "EventTarget.h"
 #include "Queue.h"
 #include "WorkerFeature.h"
 
--- a/dom/workers/Workers.h
+++ b/dom/workers/Workers.h
@@ -8,17 +8,17 @@
 
 #include "jsapi.h"
 #include "mozilla/Attributes.h"
 #include "mozilla/Mutex.h"
 #include <stdint.h>
 #include "nsAutoPtr.h"
 #include "nsCOMPtr.h"
 #include "nsDebug.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 
 #define BEGIN_WORKERS_NAMESPACE \
   namespace mozilla { namespace dom { namespace workers {
 #define END_WORKERS_NAMESPACE \
   } /* namespace workers */ } /* namespace dom */ } /* namespace mozilla */
 #define USING_WORKERS_NAMESPACE \
   using namespace mozilla::dom::workers;
 
--- a/embedding/browser/webBrowser/nsEmbedStream.cpp
+++ b/embedding/browser/webBrowser/nsEmbedStream.cpp
@@ -1,14 +1,15 @@
 /* -*- 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 "nsIAsyncInputStream.h"
+#include "nsIAsyncOutputStream.h"
 #include "nsIDocShell.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsIPipe.h"
 
 #include "nsEmbedStream.h"
 #include "nsError.h"
 #include "nsString.h"
 
--- a/embedding/components/appstartup/src/nsAppStartupNotifier.cpp
+++ b/embedding/components/appstartup/src/nsAppStartupNotifier.cpp
@@ -6,17 +6,17 @@
 #include "nsCOMPtr.h"
 #include "nsString.h"
 #include "nsXPIDLString.h"
 #include "nsIServiceManager.h"
 #include "nsICategoryManager.h"
 #include "nsXPCOM.h"
 #include "nsISupportsPrimitives.h"
 #include "nsAppStartupNotifier.h"
-
+#include "nsISimpleEnumerator.h"
 
 NS_IMPL_ISUPPORTS1(nsAppStartupNotifier, nsIObserver)
 
 nsAppStartupNotifier::nsAppStartupNotifier()
 {
 }
 
 nsAppStartupNotifier::~nsAppStartupNotifier()
--- a/extensions/spellcheck/src/mozSpellChecker.cpp
+++ b/extensions/spellcheck/src/mozSpellChecker.cpp
@@ -4,16 +4,17 @@
 
 
 #include "mozSpellChecker.h"
 #include "nsIServiceManager.h"
 #include "mozISpellI18NManager.h"
 #include "nsIStringEnumerator.h"
 #include "nsICategoryManager.h"
 #include "nsISupportsPrimitives.h"
+#include "nsISimpleEnumerator.h"
 
 #define DEFAULT_SPELL_CHECKER "@mozilla.org/spellchecker/engine;1"
 
 NS_IMPL_CYCLE_COLLECTING_ADDREF(mozSpellChecker)
 NS_IMPL_CYCLE_COLLECTING_RELEASE(mozSpellChecker)
 
 NS_INTERFACE_MAP_BEGIN(mozSpellChecker)
   NS_INTERFACE_MAP_ENTRY(nsISpellChecker)
--- a/extensions/spellcheck/src/mozSpellCheckerFactory.cpp
+++ b/extensions/spellcheck/src/mozSpellCheckerFactory.cpp
@@ -7,16 +7,17 @@
 #include "mozilla/ModuleUtils.h"
 #include "mozHunspell.h"
 #include "mozHunspellDirProvider.h"
 #include "mozSpellChecker.h"
 #include "mozInlineSpellChecker.h"
 #include "nsTextServicesCID.h"
 #include "mozPersonalDictionary.h"
 #include "mozSpellI18NManager.h"
+#include "nsIFile.h"
 
 #define NS_SPELLCHECKER_CID         \
 { /* 8227f019-afc7-461e-b030-9f185d7a0e29 */    \
 0x8227F019, 0xAFC7, 0x461e,                     \
 { 0xB0, 0x30, 0x9F, 0x18, 0x5D, 0x7A, 0x0E, 0x29} }
 
 #define MOZ_INLINESPELLCHECKER_CID         \
 { /* 9FE5D975-09BD-44aa-A01A-66402EA28657 */    \
--- a/extensions/widgetutils/src/nsWidgetUtils.cpp
+++ b/extensions/widgetutils/src/nsWidgetUtils.cpp
@@ -18,17 +18,17 @@
 #include "nsIObserver.h"
 #include "nsIPresShell.h"
 #include "nsIStyleSheetService.h"
 #include "nsIWebProgress.h"
 #include "nsIWebProgressListener.h"
 #include "nsIWindowWatcher.h"
 #include "nsNetUtil.h"
 #include "nsRect.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 #include "nsWeakReference.h"
 #include "nsIWebBrowser.h"
 #include "nsIObserverService.h"
 #include "nsPIDOMWindow.h"
 #include "nsIDOMWindow.h"
 #include "nsIDOMCompositionListener.h"
 #include "nsIDOMTextListener.h"
 #include "nsIDOMMouseEvent.h"
--- a/gfx/layers/Effects.cpp
+++ b/gfx/layers/Effects.cpp
@@ -34,24 +34,16 @@ EffectMask::PrintInfo(nsACString& aTo, c
   aTo += aPrefix;
   aTo += nsPrintfCString("EffectMask (0x%p)", this);
   AppendToString(aTo, mSize, " [size=", "]");
   AppendToString(aTo, mMaskTransform, " [mask-transform=", "]");
 
   if (mIs3D) {
     aTo += " [is-3d]";
   }
-
-  if (mMaskTexture) {
-    nsAutoCString prefix(aPrefix);
-    prefix += "  ";
-
-    aTo += "\n";
-    mMaskTexture->PrintInfo(aTo, prefix.get());
-  }
 }
 
 void
 EffectRenderTarget::PrintInfo(nsACString& aTo, const char* aPrefix)
 {
   TexturedEffect::PrintInfo(aTo, aPrefix);
   aTo += nsPrintfCString(" [render-target=%p]", mRenderTarget.get());
 }
--- a/gfx/layers/ThebesLayerBuffer.cpp
+++ b/gfx/layers/ThebesLayerBuffer.cpp
@@ -502,16 +502,30 @@ ComputeBufferRect(const nsIntRect& aRequ
 {
   nsIntRect rect(aRequestedRect);
   // Set a minimum width to guarantee a minimum size of buffers we
   // allocate (and work around problems on some platforms with smaller
   // dimensions).  64 is the magic number needed to work around the
   // rendering glitch, and guarantees image rows can be SIMD'd for
   // even r5g6b5 surfaces pretty much everywhere.
   rect.width = std::max(aRequestedRect.width, 64);
+#ifdef MOZ_WIDGET_GONK
+  // Set a minumum height to guarantee a minumum height of buffers we
+  // allocate. Some GL implementations fail to render gralloc textures
+  // with a height 9px-16px. It happens on Adreno 200. Adreno 320 does not
+  // have this problem. 32 is choosed as alignment of gralloc buffers.
+  // See Bug 873937.
+  // Increase the height only when the requested height is more than 0.
+  // See Bug 895976.
+  // XXX it might be better to disable it on the gpu that does not have
+  // the height problem.
+  if (rect.height > 0) {
+    rect.height = std::max(aRequestedRect.height, 32);
+  }
+#endif
   return rect;
 }
 
 ThebesLayerBuffer::PaintState
 ThebesLayerBuffer::BeginPaint(ThebesLayer* aLayer, ContentType aContentType,
                               uint32_t aFlags)
 {
   PaintState result;
--- a/gfx/layers/composite/TextureHost.cpp
+++ b/gfx/layers/composite/TextureHost.cpp
@@ -156,16 +156,30 @@ TextureHost::TextureHost(uint64_t aID,
     , mNextTexture(nullptr)
     , mFlags(aFlags)
 {}
 
 TextureHost::~TextureHost()
 {
 }
 
+#ifdef MOZ_LAYERS_HAVE_LOG
+
+void
+TextureHost::PrintInfo(nsACString& aTo, const char* aPrefix)
+{
+  aTo += aPrefix;
+  aTo += nsPrintfCString("%s (0x%p)", Name(), this);
+  AppendToString(aTo, GetSize(), " [size=", "]");
+  AppendToString(aTo, GetFormat(), " [format=", "]");
+  AppendToString(aTo, mFlags, " [flags=", "]");
+}
+
+#endif
+
 void TextureSource::SetCompositableQuirks(CompositableQuirks* aQuirks)
 {
     mQuirks = aQuirks;
 }
 
 TextureSource::TextureSource()
 {
     MOZ_COUNT_CTOR(TextureSource);
@@ -226,22 +240,16 @@ DeprecatedTextureHost::SwapTextures(cons
   // register the TextureHost with the GrallocBufferActor.
   // The reason why this SetBuffer calls is needed here is that just above we
   // overwrote *mBuffer in place, so we need to tell the new mBuffer about this
   // TextureHost.
   SetBuffer(mBuffer, mDeAllocator);
 }
 
 #ifdef MOZ_LAYERS_HAVE_LOG
-void
-TextureSource::PrintInfo(nsACString& aTo, const char* aPrefix)
-{
-  aTo += aPrefix;
-  aTo += nsPrintfCString("UnknownTextureSource (0x%p)", this);
-}
 
 void
 DeprecatedTextureHost::PrintInfo(nsACString& aTo, const char* aPrefix)
 {
   aTo += aPrefix;
   aTo += nsPrintfCString("%s (0x%p)", Name(), this);
   AppendToString(aTo, GetSize(), " [size=", "]");
   AppendToString(aTo, GetFormat(), " [format=", "]");
--- a/gfx/layers/composite/TextureHost.h
+++ b/gfx/layers/composite/TextureHost.h
@@ -115,20 +115,16 @@ public:
   /**
    * Overload this if the TextureSource supports big textures that don't fit in
    * one device texture and must be tiled internally.
    */
   virtual TileIterator* AsTileIterator() { return nullptr; }
 
   virtual void SetCompositableQuirks(CompositableQuirks* aQuirks);
 
-#ifdef MOZ_LAYERS_HAVE_LOG
-  virtual void PrintInfo(nsACString& aTo, const char* aPrefix);
-#endif
-
 protected:
   RefPtr<CompositableQuirks> mQuirks;
 };
 
 
 /**
  * XXX - merge this class with TextureSource when deprecated texture classes
  * are completely removed.
@@ -384,23 +380,18 @@ public:
     // By default we return an empty render state, this should be overridden
     // by the TextureHost implementations that are used on B2G with Composer2D
     return LayerRenderState();
   }
 
   virtual void SetCompositableQuirks(CompositableQuirks* aQuirks);
 
 #ifdef MOZ_LAYERS_HAVE_LOG
-  virtual void PrintInfo(nsACString& aTo, const char* aPrefix)
-  {
-    RefPtr<TextureSource> source = GetTextureSources();
-    if (source) {
-      source->PrintInfo(aTo, aPrefix);
-    }
-  }
+  virtual const char *Name() { return "TextureHost"; }
+  virtual void PrintInfo(nsACString& aTo, const char* aPrefix);
 #endif
 
 protected:
   uint64_t mID;
   RefPtr<TextureHost> mNextTexture;
   TextureFlags mFlags;
   RefPtr<CompositableQuirks> mQuirks;
 };
@@ -484,16 +475,20 @@ public:
                    TextureFlags aFlags);
 
   ~ShmemTextureHost();
 
   virtual void DeallocateSharedData() MOZ_OVERRIDE;
 
   virtual uint8_t* GetBuffer() MOZ_OVERRIDE;
 
+#ifdef MOZ_LAYERS_HAVE_LOG
+  virtual const char *Name() MOZ_OVERRIDE { return "ShmemTextureHost"; }
+#endif
+
 protected:
   ipc::Shmem* mShmem;
   ISurfaceAllocator* mDeallocator;
 };
 
 /**
  * TextureHost that wraps raw memory.
  * The corresponding texture on the client side is MemoryTextureClient.
@@ -509,16 +504,20 @@ public:
                     TextureFlags aFlags);
 
   ~MemoryTextureHost();
 
   virtual void DeallocateSharedData() MOZ_OVERRIDE;
 
   virtual uint8_t* GetBuffer() MOZ_OVERRIDE;
 
+#ifdef MOZ_LAYERS_HAVE_LOG
+  virtual const char *Name() MOZ_OVERRIDE { return "MemoryTextureHost"; }
+#endif
+
 protected:
   uint8_t* mBuffer;
 };
 
 
 /**
  * XXX - This class is deprectaed, will be removed soon.
  *
--- a/gfx/layers/ipc/CompositorChild.cpp
+++ b/gfx/layers/ipc/CompositorChild.cpp
@@ -46,36 +46,37 @@ CompositorChild::Destroy()
   while (size_t len = ManagedPLayerTransactionChild().Length()) {
     LayerTransactionChild* layers =
       static_cast<LayerTransactionChild*>(ManagedPLayerTransactionChild()[len - 1]);
     layers->Destroy();
   }
   SendStop();
 }
 
-/*static*/ PCompositorChild*
+/*static*/ bool
 CompositorChild::Create(Transport* aTransport, ProcessId aOtherProcess)
 {
   // There's only one compositor per child process.
   MOZ_ASSERT(!sCompositor);
 
   nsRefPtr<CompositorChild> child(new CompositorChild(nullptr));
   ProcessHandle handle;
   if (!base::OpenProcessHandle(aOtherProcess, &handle)) {
     // We can't go on without a compositor.
     NS_RUNTIMEABORT("Couldn't OpenProcessHandle() to parent process.");
-    return nullptr;
+    return false;
   }
   if (!child->Open(aTransport, handle, XRE_GetIOMessageLoop(),
                 AsyncChannel::Child)) {
     NS_RUNTIMEABORT("Couldn't Open() Compositor channel.");
-    return nullptr;
+    return false;
   }
   // We release this ref in ActorDestroy().
-  return sCompositor = child.forget().get();
+  sCompositor = child.forget().get();
+  return true;
 }
 
 /*static*/ PCompositorChild*
 CompositorChild::Get()
 {
   // This is only expected to be used in child processes.
   MOZ_ASSERT(XRE_GetProcessType() != GeckoProcessType_Default);
   return sCompositor;
--- a/gfx/layers/ipc/CompositorChild.h
+++ b/gfx/layers/ipc/CompositorChild.h
@@ -33,17 +33,17 @@ public:
 
   void Destroy();
 
   /**
    * We're asked to create a new Compositor in response to an Opens()
    * or Bridge() request from our parent process.  The Transport is to
    * the compositor's context.
    */
-  static PCompositorChild*
+  static bool
   Create(Transport* aTransport, ProcessId aOtherProcess);
 
   static PCompositorChild* Get();
 
   static bool ChildProcessHasCompositor() { return sCompositor != nullptr; }
 protected:
   virtual PLayerTransactionChild*
     AllocPLayerTransactionChild(const nsTArray<LayersBackend>& aBackendHints,
--- a/gfx/layers/ipc/CompositorParent.cpp
+++ b/gfx/layers/ipc/CompositorParent.cpp
@@ -900,34 +900,32 @@ static void
 OpenCompositor(CrossProcessCompositorParent* aCompositor,
                Transport* aTransport, ProcessHandle aHandle,
                MessageLoop* aIOLoop)
 {
   DebugOnly<bool> ok = aCompositor->Open(aTransport, aHandle, aIOLoop);
   MOZ_ASSERT(ok);
 }
 
-/*static*/ PCompositorParent*
+/*static*/ bool
 CompositorParent::Create(Transport* aTransport, ProcessId aOtherProcess)
 {
   nsRefPtr<CrossProcessCompositorParent> cpcp =
     new CrossProcessCompositorParent(aTransport);
   ProcessHandle handle;
   if (!base::OpenProcessHandle(aOtherProcess, &handle)) {
     // XXX need to kill |aOtherProcess|, it's boned
-    return nullptr;
+    return false;
   }
   cpcp->mSelfRef = cpcp;
   CompositorLoop()->PostTask(
     FROM_HERE,
     NewRunnableFunction(OpenCompositor, cpcp.get(),
                         aTransport, handle, XRE_GetIOMessageLoop()));
-  // The return value is just compared to null for success checking,
-  // we're not sharing a ref.
-  return cpcp.get();
+  return true;
 }
 
 static void
 UpdateIndirectTree(uint64_t aId, Layer* aRoot, const TargetConfig& aTargetConfig)
 {
   sIndirectLayerTrees[aId].mRoot = aRoot;
   sIndirectLayerTrees[aId].mTargetConfig = aTargetConfig;
 }
--- a/gfx/layers/ipc/CompositorParent.h
+++ b/gfx/layers/ipc/CompositorParent.h
@@ -167,17 +167,17 @@ public:
    * pan/zoom-related events can be sent.
    */
   static APZCTreeManager* GetAPZCTreeManager(uint64_t aLayersId);
 
   /**
    * A new child process has been configured to push transactions
    * directly to us.  Transport is to its thread context.
    */
-  static PCompositorParent*
+  static bool
   Create(Transport* aTransport, ProcessId aOtherProcess);
 
   /**
    * Setup external message loop and thread ID for Compositor.
    * Should be used when CompositorParent should work in existing thread/MessageLoop,
    * for example moving Compositor into native toolkit main thread will allow to avoid
    * extra synchronization and call ::Composite() right from toolkit::Paint event
    */
--- a/gfx/layers/ipc/ImageBridgeChild.cpp
+++ b/gfx/layers/ipc/ImageBridgeChild.cpp
@@ -516,39 +516,39 @@ ImageBridgeChild::EndTransaction()
     }
     default:
       NS_RUNTIMEABORT("not reached");
     }
   }
 }
 
 
-PImageBridgeChild*
+bool
 ImageBridgeChild::StartUpInChildProcess(Transport* aTransport,
                                         ProcessId aOtherProcess)
 {
   NS_ASSERTION(NS_IsMainThread(), "Should be on the main Thread!");
 
   ProcessHandle processHandle;
   if (!base::OpenProcessHandle(aOtherProcess, &processHandle)) {
-    return nullptr;
+    return false;
   }
 
   sImageBridgeChildThread = new Thread("ImageBridgeChild");
   if (!sImageBridgeChildThread->Start()) {
-    return nullptr;
+    return false;
   }
 
   sImageBridgeChildSingleton = new ImageBridgeChild();
   sImageBridgeChildSingleton->GetMessageLoop()->PostTask(
     FROM_HERE,
     NewRunnableFunction(ConnectImageBridgeInChildProcess,
                         aTransport, processHandle));
 
-  return sImageBridgeChildSingleton;
+  return true;
 }
 
 void ImageBridgeChild::ShutDown()
 {
   NS_ASSERTION(NS_IsMainThread(), "Should be on the main Thread!");
   if (ImageBridgeChild::IsCreated()) {
     ImageBridgeChild::DestroyBridge();
     delete sImageBridgeChildThread;
--- a/gfx/layers/ipc/ImageBridgeChild.h
+++ b/gfx/layers/ipc/ImageBridgeChild.h
@@ -109,17 +109,17 @@ public:
   /**
    * Creates the image bridge with a dedicated thread for ImageBridgeChild.
    *
    * We may want to use a specifi thread in the future. In this case, use
    * CreateWithThread instead.
    */
   static void StartUp();
 
-  static PImageBridgeChild*
+  static bool
   StartUpInChildProcess(Transport* aTransport, ProcessId aOtherProcess);
 
   /**
    * Destroys the image bridge by calling DestroyBridge, and destroys the
    * ImageBridge's thread.
    *
    * If you don't want to destroy the thread, call DestroyBridge directly
    * instead.
--- a/gfx/layers/ipc/ImageBridgeParent.cpp
+++ b/gfx/layers/ipc/ImageBridgeParent.cpp
@@ -98,31 +98,31 @@ static void
 ConnectImageBridgeInParentProcess(ImageBridgeParent* aBridge,
                                   Transport* aTransport,
                                   ProcessHandle aOtherProcess)
 {
   aBridge->Open(aTransport, aOtherProcess,
                 XRE_GetIOMessageLoop(), AsyncChannel::Parent);
 }
 
-/*static*/ PImageBridgeParent*
+/*static*/ bool
 ImageBridgeParent::Create(Transport* aTransport, ProcessId aOtherProcess)
 {
   ProcessHandle processHandle;
   if (!base::OpenProcessHandle(aOtherProcess, &processHandle)) {
-    return nullptr;
+    return false;
   }
 
   MessageLoop* loop = CompositorParent::CompositorLoop();
   nsRefPtr<ImageBridgeParent> bridge = new ImageBridgeParent(loop, aTransport);
   bridge->mSelfRef = bridge;
   loop->PostTask(FROM_HERE,
                  NewRunnableFunction(ConnectImageBridgeInParentProcess,
                                      bridge.get(), aTransport, processHandle));
-  return bridge.get();
+  return true;
 }
 
 bool ImageBridgeParent::RecvStop()
 {
   return true;
 }
 
 static  uint64_t GenImageContainerID() {
--- a/gfx/layers/ipc/ImageBridgeParent.h
+++ b/gfx/layers/ipc/ImageBridgeParent.h
@@ -39,17 +39,17 @@ public:
   typedef InfallibleTArray<CompositableOperation> EditArray;
   typedef InfallibleTArray<EditReply> EditReplyArray;
 
   ImageBridgeParent(MessageLoop* aLoop, Transport* aTransport);
   ~ImageBridgeParent();
 
   virtual void ActorDestroy(ActorDestroyReason aWhy) MOZ_OVERRIDE;
 
-  static PImageBridgeParent*
+  static bool
   Create(Transport* aTransport, ProcessId aOtherProcess);
 
   virtual PGrallocBufferParent*
   AllocPGrallocBufferParent(const gfxIntSize&, const uint32_t&, const uint32_t&,
                             MaybeMagicGrallocBufferHandle*) MOZ_OVERRIDE;
 
   virtual bool
   DeallocPGrallocBufferParent(PGrallocBufferParent* actor) MOZ_OVERRIDE;
--- a/gfx/layers/opengl/GrallocTextureHost.h
+++ b/gfx/layers/opengl/GrallocTextureHost.h
@@ -106,17 +106,17 @@ public:
 
   virtual already_AddRefed<gfxImageSurface> GetAsSurface() MOZ_OVERRIDE;
 
   virtual void SetCompositableQuirks(CompositableQuirks* aQuirks) MOZ_OVERRIDE;
 
   bool IsValid() const;
 
 #ifdef MOZ_LAYERS_HAVE_LOG
-  virtual const char* Name() { return "GrallocTextureHostOGL"; }
+  virtual const char* Name() MOZ_OVERRIDE { return "GrallocTextureHostOGL"; }
 #endif
 
 private:
   GrallocBufferActor* mGrallocActor;
   RefPtr<GrallocTextureSourceOGL> mTextureSource;
   gfx::IntSize mSize; // See comment in textureClientOGL.h
 };
 
--- a/gfx/src/AppUnits.h
+++ b/gfx/src/AppUnits.h
@@ -1,11 +1,15 @@
 /* -*- Mode: C++; 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/. */
 
-#ifndef _NS_APPUNITS_H_
-#define _NS_APPUNITS_H_
+#ifndef mozilla_AppUnits_h
+#define mozilla_AppUnits_h
+
+#include <stdint.h>
+
 namespace mozilla {
-static int32_t AppUnitsPerCSSPixel() { return 60; }
+inline int32_t AppUnitsPerCSSPixel() { return 60; }
+inline int32_t AppUnitsPerCSSInch() { return 96 * AppUnitsPerCSSPixel(); }
 }
 #endif /* _NS_APPUNITS_H_ */
--- a/gfx/src/gfxCrashReporterUtils.cpp
+++ b/gfx/src/gfxCrashReporterUtils.cpp
@@ -20,17 +20,17 @@
 #include "nsError.h"                    // for NS_OK, NS_FAILED, nsresult
 #include "nsExceptionHandler.h"         // for AppendAppNotesToCrashReport
 #include "nsID.h"
 #include "nsIEventTarget.h"             // for NS_DISPATCH_NORMAL
 #include "nsIObserver.h"                // for nsIObserver, etc
 #include "nsIObserverService.h"         // for nsIObserverService
 #include "nsIRunnable.h"                // for nsIRunnable
 #include "nsISupports.h"
-#include "nsStringGlue.h"               // for nsAutoCString, nsCString, etc
+#include "nsString.h"               // for nsAutoCString, nsCString, etc
 #include "nsTArray.h"                   // for nsTArray
 #include "nsThreadUtils.h"              // for NS_DispatchToMainThread, etc
 #include "nscore.h"                     // for NS_IMETHOD, NS_IMETHODIMP, etc
 
 namespace mozilla {
 
 static nsTArray<nsCString> *gFeaturesAlreadyReported = nullptr;
 
--- a/gfx/src/nsColor.cpp
+++ b/gfx/src/nsColor.cpp
@@ -7,17 +7,17 @@
 
 #include "nsColor.h"
 #include <sys/types.h>                  // for int32_t
 #include "mozilla/Util.h"               // for ArrayLength
 #include "mozilla/mozalloc.h"           // for operator delete, etc
 #include "nsColorNames.h"               // for nsColorNames
 #include "nsDebug.h"                    // for NS_ASSERTION, etc
 #include "nsStaticNameTable.h"
-#include "nsStringGlue.h"               // for nsAutoCString, nsString, etc
+#include "nsString.h"               // for nsAutoCString, nsString, etc
 #include "nscore.h"                     // for nsAString, etc
 
 using namespace mozilla;
 
 // define an array of all color names
 #define GFX_COLOR(_name, _value) #_name,
 static const char* const kColorNames[] = {
 #include "nsColorNameList.h"
--- a/gfx/src/nsDeviceContext.cpp
+++ b/gfx/src/nsDeviceContext.cpp
@@ -25,17 +25,17 @@
 #include "nsIObserverService.h"         // for nsIObserverService
 #include "nsIScreen.h"                  // for nsIScreen
 #include "nsIScreenManager.h"           // for nsIScreenManager
 #include "nsISupportsUtils.h"           // for NS_ADDREF, NS_RELEASE
 #include "nsIWidget.h"                  // for nsIWidget, NS_NATIVE_WINDOW
 #include "nsRect.h"                     // for nsRect
 #include "nsRenderingContext.h"         // for nsRenderingContext
 #include "nsServiceManagerUtils.h"      // for do_GetService
-#include "nsStringGlue.h"               // for nsDependentString
+#include "nsString.h"               // for nsDependentString
 #include "nsTArray.h"                   // for nsTArray, nsTArray_Impl
 #include "nsThreadUtils.h"              // for NS_IsMainThread
 #include "nsTraceRefcnt.h"              // for MOZ_COUNT_CTOR, etc
 
 #if !XP_MACOSX
 #include "gfxPDFSurface.h"
 #endif
 
--- a/gfx/src/nsDeviceContext.h
+++ b/gfx/src/nsDeviceContext.h
@@ -94,17 +94,17 @@ public:
      */
     int32_t AppUnitsPerPhysicalInch() const
     { return mAppUnitsPerPhysicalInch; }
 
     /**
      * Gets the number of app units in one CSS inch; this is
      * 96 times AppUnitsPerCSSPixel.
      */
-    static int32_t AppUnitsPerCSSInch() { return 96 * AppUnitsPerCSSPixel(); }
+    static int32_t AppUnitsPerCSSInch() { return mozilla::AppUnitsPerCSSInch(); }
 
     /**
      * Get the unscaled ratio of app units to dev pixels; useful if something
      * needs to be converted from to unscaled pixels
      */
     int32_t UnscaledAppUnitsPerDevPixel() const
     { return mAppUnitsPerDevNotScaledPixel; }
 
--- a/gfx/src/nsFont.h
+++ b/gfx/src/nsFont.h
@@ -8,17 +8,17 @@
 
 #include <stdint.h>                     // for uint8_t, uint16_t
 #include <sys/types.h>                  // for int16_t
 #include "gfxCore.h"                    // for NS_GFX
 #include "gfxFontFeatures.h"
 #include "nsAutoPtr.h"                  // for nsRefPtr
 #include "nsCoord.h"                    // for nscoord
 #include "nsStringFwd.h"                // for nsSubstring
-#include "nsStringGlue.h"               // for nsString
+#include "nsString.h"               // for nsString
 #include "nsTArray.h"                   // for nsTArray
 
 struct gfxFontStyle;
 
 // XXX we need a method to enumerate all of the possible fonts on the
 // system across family, weight, style, size, etc. But not here!
 
 // Enumerator callback function. Return false to stop
--- a/gfx/src/nsFontMetrics.cpp
+++ b/gfx/src/nsFontMetrics.cpp
@@ -11,17 +11,17 @@
 #include "gfxRect.h"                    // for gfxRect
 #include "gfxTypes.h"                   // for gfxFloat
 #include "nsBoundingMetrics.h"          // for nsBoundingMetrics
 #include "nsDebug.h"                    // for NS_ERROR, NS_ABORT_IF_FALSE
 #include "nsDeviceContext.h"            // for nsDeviceContext
 #include "nsIAtom.h"                    // for nsIAtom
 #include "nsMathUtils.h"                // for NS_round
 #include "nsRenderingContext.h"         // for nsRenderingContext
-#include "nsStringGlue.h"               // for nsString
+#include "nsString.h"               // for nsString
 #include "nsStyleConsts.h"              // for NS_STYLE_HYPHENS_NONE
 
 class gfxUserFontSet;
 
 namespace {
 
 class AutoTextRun {
 public:
--- a/gfx/src/nsRect.cpp
+++ b/gfx/src/nsRect.cpp
@@ -1,17 +1,17 @@
 /* -*- 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 "nsRect.h"
 #include "mozilla/gfx/Types.h"          // for NS_SIDE_BOTTOM, etc
 #include "nsDeviceContext.h"            // for nsDeviceContext
-#include "nsStringGlue.h"               // for nsAutoString, etc
+#include "nsString.h"               // for nsAutoString, etc
 #include "prtypes.h"                    // for PR_STATIC_ASSERT
 #include "nsMargin.h"                   // for nsMargin
 
 // the mozilla::css::Side sequence must match the nsMargin nscoord sequence
 PR_STATIC_ASSERT((NS_SIDE_TOP == 0) && (NS_SIDE_RIGHT == 1) && (NS_SIDE_BOTTOM == 2) && (NS_SIDE_LEFT == 3));
 
 #ifdef DEBUG
 // Diagnostics
--- a/gfx/src/nsRegion.h
+++ b/gfx/src/nsRegion.h
@@ -9,17 +9,17 @@
 #include <stddef.h>                     // for size_t
 #include <stdint.h>                     // for uint32_t, uint64_t
 #include <sys/types.h>                  // for int32_t
 #include "gfxCore.h"                    // for NS_GFX
 #include "nsCoord.h"                    // for nscoord
 #include "nsError.h"                    // for nsresult
 #include "nsPoint.h"                    // for nsIntPoint, nsPoint
 #include "nsRect.h"                     // for nsIntRect, nsRect
-#include "nsStringGlue.h"               // for nsCString
+#include "nsString.h"               // for nsCString
 #include "xpcom-config.h"               // for CPP_THROW_NEW
 
 class nsIntRegion;
 
 /**
  * Implementation of regions.
  * A region is represented as circular double-linked list of nsRegion::RgnRect structures.
  * Rectangles in this list do not overlap and are sorted by (y, x) coordinates.
--- a/gfx/src/nsRenderingContext.h
+++ b/gfx/src/nsRenderingContext.h
@@ -13,17 +13,17 @@
 #include "mozilla/gfx/UserData.h"       // for UserData, UserDataKey
 #include "nsAutoPtr.h"                  // for nsRefPtr
 #include "nsBoundingMetrics.h"          // for nsBoundingMetrics
 #include "nsColor.h"                    // for nscolor
 #include "nsCoord.h"                    // for nscoord, NSToIntRound
 #include "nsDeviceContext.h"            // for nsDeviceContext
 #include "nsFontMetrics.h"              // for nsFontMetrics
 #include "nsISupports.h"                // for NS_INLINE_DECL_REFCOUNTING, etc
-#include "nsStringGlue.h"               // for nsString
+#include "nsString.h"               // for nsString
 #include "nscore.h"                     // for PRUnichar
 
 class gfxASurface;
 class nsIntRegion;
 struct nsPoint;
 struct nsRect;
 
 typedef enum {
--- a/gfx/src/nsThebesFontEnumerator.cpp
+++ b/gfx/src/nsThebesFontEnumerator.cpp
@@ -8,17 +8,17 @@
 #include "gfxPlatform.h"                // for gfxPlatform
 #include "mozilla/Assertions.h"         // for MOZ_ASSERT_HELPER2
 #include "nsCOMPtr.h"                   // for nsCOMPtr
 #include "nsDebug.h"                    // for NS_ENSURE_ARG_POINTER
 #include "nsError.h"                    // for NS_OK, NS_FAILED, nsresult
 #include "nsIAtom.h"                    // for nsIAtom, do_GetAtom
 #include "nsID.h"
 #include "nsMemory.h"                   // for nsMemory
-#include "nsStringGlue.h"               // for nsAutoCString, nsAutoString, etc
+#include "nsString.h"               // for nsAutoCString, nsAutoString, etc
 #include "nsTArray.h"                   // for nsTArray, nsTArray_Impl, etc
 #include "nscore.h"                     // for PRUnichar, NS_IMETHODIMP
 
 NS_IMPL_ISUPPORTS1(nsThebesFontEnumerator, nsIFontEnumerator)
 
 nsThebesFontEnumerator::nsThebesFontEnumerator()
 {
 }
--- a/gfx/thebes/gfxASurface.cpp
+++ b/gfx/thebes/gfxASurface.cpp
@@ -44,17 +44,17 @@
 #include <limits.h>
 
 #include "imgIEncoder.h"
 #include "nsComponentManagerUtils.h"
 #include "nsISupportsUtils.h"
 #include "nsCOMPtr.h"
 #include "nsIConsoleService.h"
 #include "nsServiceManagerUtils.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 #include "nsIClipboardHelper.h"
 
 using namespace mozilla;
 
 static cairo_user_data_key_t gfxasurface_pointer_key;
 
 // Surfaces use refcounting that's tied to the cairo surface refcnt, to avoid
 // refcount mismatch issues.
--- a/gfx/thebes/gfxFT2FontList.cpp
+++ b/gfx/thebes/gfxFT2FontList.cpp
@@ -1,17 +1,17 @@
 /* -*- Mode: C++; tab-width: 20; 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 "mozilla/MemoryReporting.h"
 #include "mozilla/Util.h"
 
-#if defined(MOZ_WIDGET_GTK2)
+#if (MOZ_WIDGET_GTK == 2)
 #include "gfxPlatformGtk.h"
 #define gfxToolkitPlatform gfxPlatformGtk
 #elif defined(MOZ_WIDGET_QT)
 #include <qfontinfo.h>
 #include "gfxQtPlatform.h"
 #define gfxToolkitPlatform gfxQtPlatform
 #elif defined(XP_WIN)
 #include "gfxWindowsPlatform.h"
--- a/gfx/thebes/gfxPlatform.h
+++ b/gfx/thebes/gfxPlatform.h
@@ -3,17 +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 GFX_PLATFORM_H
 #define GFX_PLATFORM_H
 
 #include "prlog.h"
 #include "nsTArray.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 #include "nsIObserver.h"
 
 #include "gfxTypes.h"
 #include "gfxASurface.h"
 #include "gfxColor.h"
 
 #include "qcms.h"
 
--- a/image/decoders/icon/nsIconModule.cpp
+++ b/image/decoders/icon/nsIconModule.cpp
@@ -33,17 +33,17 @@ static const mozilla::Module::ContractID
 
 static const mozilla::Module::CategoryEntry kIconCategories[] = {
   { nullptr }
 };
 
 static void
 IconDecoderModuleDtor()
 {
-#ifdef MOZ_WIDGET_GTK2
+#if (MOZ_WIDGET_GTK == 2)
   nsIconChannel::Shutdown();
 #endif
 }
 
 static const mozilla::Module kIconModule = {
   mozilla::Module::kVersion,
   kIconCIDs,
   kIconContracts,
--- a/image/decoders/icon/nsIconURI.h
+++ b/image/decoders/icon/nsIconURI.h
@@ -4,17 +4,17 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef nsMozIconURI_h__
 #define nsMozIconURI_h__
 
 #include "nsIIconURI.h"
 #include "nsCOMPtr.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 
 #define NS_MOZICONURI_CID                            \
 {                                                    \
     0x43a88e0e,                                      \
     0x2d37,                                          \
     0x11d5,                                          \
     { 0x99, 0x7, 0x0, 0x10, 0x83, 0x1, 0xe, 0x9b }   \
 }
--- a/image/src/imgRequest.h
+++ b/image/src/imgRequest.h
@@ -9,17 +9,17 @@
 
 #include "nsIChannelEventSink.h"
 #include "nsIInterfaceRequestor.h"
 #include "nsIStreamListener.h"
 #include "nsIPrincipal.h"
 
 #include "nsAutoPtr.h"
 #include "nsCOMPtr.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 #include "nsError.h"
 #include "nsIAsyncVerifyRedirectCallback.h"
 
 class imgCacheValidator;
 class imgStatusTracker;
 class imgLoader;
 class imgRequestProxy;
 class imgCacheEntry;
--- a/intl/locale/public/nsCharsetAlias.h
+++ b/intl/locale/public/nsCharsetAlias.h
@@ -2,17 +2,17 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef nsCharsetAlias_h___
 #define nsCharsetAlias_h___
 
 #include "nscore.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 
 class nsCharsetConverterManager;
 class nsScriptableUnicodeConverter;
 
 class nsCharsetAlias
 {
    friend class nsCharsetConverterManager;
    friend class nsScriptableUnicodeConverter;
--- a/intl/locale/public/nsIDateTimeFormat.h
+++ b/intl/locale/public/nsIDateTimeFormat.h
@@ -5,17 +5,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 nsIDateTimeFormat_h__
 #define nsIDateTimeFormat_h__
 
 
 #include "nsISupports.h"
 #include "nscore.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 #include "nsILocale.h"
 #include "nsIScriptableDateFormat.h"
 #include "prtime.h"
 #include <time.h>
 
 
 // {2BBAA0B0-A591-11d2-9119-006008A6EDF6}
 #define NS_IDATETIMEFORMAT_IID \
--- a/intl/locale/public/nsIPlatformCharset.h
+++ b/intl/locale/public/nsIPlatformCharset.h
@@ -1,17 +1,17 @@
 /* -*- 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 nsIPlatformCharset_h__
 #define nsIPlatformCharset_h__
 
-#include "nsStringGlue.h"
+#include "nsString.h"
 #include "nsISupports.h"
 
 // Interface ID for our nsIPlatformCharset interface
 
 /* 778859d5-fc01-4f4b-bfaa-3c0d1b6c81d6 */
 #define NS_IPLATFORMCHARSET_IID \
 {   0x778859d5, \
     0xfc01, \
--- a/intl/uconv/idl/nsICharsetConverterManager.idl
+++ b/intl/uconv/idl/nsICharsetConverterManager.idl
@@ -4,17 +4,17 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsISupports.idl"
 #include "nsIAtom.idl"
 
 %{ C++
 #include "nsIUnicodeDecoder.h"
 #include "nsIUnicodeEncoder.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 
 
 // XXX change to NS_CHARSETCONVERTERMANAGER_CID
 #define NS_ICHARSETCONVERTERMANAGER_CID \
   {0x3c1c0163, 0x9bd0, 0x11d3, { 0x9d, 0x9, 0x0, 0x50, 0x4, 0x0, 0x7, 0xb2}}
 
 // XXX change to NS_CHARSETCONVERTERMANAGER_PID
 #define NS_CHARSETCONVERTERMANAGER_CONTRACTID "@mozilla.org/charset-converter-manager;1"
--- a/ipc/glue/IPCMessageUtils.h
+++ b/ipc/glue/IPCMessageUtils.h
@@ -15,17 +15,17 @@
 #include "mozilla/TimeStamp_windows.h"
 #endif
 #include "mozilla/Util.h"
 
 #include <stdint.h>
 
 #include "nsID.h"
 #include "nsMemory.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 #include "nsTArray.h"
 #include "js/StructuredClone.h"
 #include "nsCSSProperty.h"
 
 #ifdef _MSC_VER
 #pragma warning( disable : 4800 )
 #endif
 
--- a/ipc/glue/MessagePump.cpp
+++ b/ipc/glue/MessagePump.cpp
@@ -1,17 +1,17 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "MessagePump.h"
 
 #include "nsComponentManagerUtils.h"
 #include "nsServiceManagerUtils.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 #include "nsThreadUtils.h"
 #include "nsXULAppAPI.h"
 #include "prthread.h"
 
 #include "base/logging.h"
 #include "base/scoped_nsautorelease_pool.h"
 
 #ifdef MOZ_WIDGET_ANDROID
--- a/ipc/glue/ScopedXREEmbed.cpp
+++ b/ipc/glue/ScopedXREEmbed.cpp
@@ -6,17 +6,17 @@
 
 #include "base/command_line.h"
 #include "base/string_util.h"
 
 #include "nsIFile.h"
 
 #include "nsCOMPtr.h"
 #include "nsServiceManagerUtils.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 #include "nsXULAppAPI.h"
 
 using mozilla::ipc::ScopedXREEmbed;
 
 ScopedXREEmbed::ScopedXREEmbed()
 : mShouldKillEmbedding(false)
 {
   NS_LogInit();
--- a/ipc/glue/WindowsMessageLoop.cpp
+++ b/ipc/glue/WindowsMessageLoop.cpp
@@ -7,17 +7,17 @@
 
 #include "mozilla/DebugOnly.h"
 
 #include "WindowsMessageLoop.h"
 #include "RPCChannel.h"
 
 #include "nsAutoPtr.h"
 #include "nsServiceManagerUtils.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 #include "nsIXULAppInfo.h"
 
 #include "mozilla/PaintTracker.h"
 
 using namespace mozilla;
 using namespace mozilla::ipc;
 using namespace mozilla::ipc::windows;
 
--- a/ipc/ipdl/ipdl/lower.py
+++ b/ipc/ipdl/ipdl/lower.py
@@ -2713,17 +2713,17 @@ class _GenerateProtocolActorCode(ipdl.as
         for actor in channelOpenedActors:
             # add the Alloc interface for actors created when a
             # new channel is opened
             actortype = _cxxBareType(actor.asType(), actor.side)
             self.cls.addstmt(StmtDecl(MethodDecl(
                 _allocMethod(actor.ptype, actor.side).name,
                 params=[ Decl(Type('Transport', ptr=1), 'transport'),
                          Decl(Type('ProcessId'), 'otherProcess') ],
-                ret=actortype,
+                ret=Type.BOOL,
                 virtual=1, pure=1)))
 
         # optional ActorDestroy() method; default is no-op
         self.cls.addstmts([
             Whitespace.NL,
             MethodDefn(MethodDecl(
                 _destroyMethod().name,
                 params=[ Decl(_DestroyReason.Type(), 'why') ],
--- a/ipc/ipdl/test/cxx/TestBridgeMain.cpp
+++ b/ipc/ipdl/test/cxx/TestBridgeMain.cpp
@@ -20,30 +20,31 @@ namespace _ipdltest {
 // main process
 void
 TestBridgeMainParent::Main()
 {
     if (!SendStart())
         fail("sending Start");
 }
 
-PTestBridgeMainSubParent*
+bool
 TestBridgeMainParent::AllocPTestBridgeMainSubParent(Transport* transport,
                                                     ProcessId otherProcess)
 {
     ProcessHandle h;
     if (!base::OpenProcessHandle(otherProcess, &h)) {
         return nullptr;
     }
 
     nsAutoPtr<TestBridgeMainSubParent> a(new TestBridgeMainSubParent(transport));
     if (!a->Open(transport, h, XRE_GetIOMessageLoop(), AsyncChannel::Parent)) {
         return nullptr;
     }
-    return a.forget();
+    a.forget();
+    return true;
 }
 
 void
 TestBridgeMainParent::ActorDestroy(ActorDestroyReason why)
 {
     if (NormalShutdown != why)
         fail("unexpected destruction!");  
     passed("ok");
@@ -171,34 +172,35 @@ TestBridgeSubChild::TestBridgeSubChild()
 bool
 TestBridgeSubChild::RecvPing()
 {
     if (!SendBridgeEm())
         fail("sending BridgeEm");
     return true;
 }
 
-PTestBridgeMainSubChild*
+bool
 TestBridgeSubChild::AllocPTestBridgeMainSubChild(Transport* transport,
                                                  ProcessId otherProcess)
 {
     ProcessHandle h;
     if (!base::OpenProcessHandle(otherProcess, &h)) {
-        return nullptr;
+        return false;
     }
 
     nsAutoPtr<TestBridgeMainSubChild> a(new TestBridgeMainSubChild(transport));
     if (!a->Open(transport, h, XRE_GetIOMessageLoop(), AsyncChannel::Child)) {
-        return nullptr;
+        return false;
     }
 
     if (!a->SendHello())
         fail("sending Hello");
 
-    return a.forget();
+    a.forget();
+    return true;
 }
 
 void
 TestBridgeSubChild::ActorDestroy(ActorDestroyReason why)
 {
     if (NormalShutdown != why)
         fail("unexpected destruction!");
     QuitChild();
--- a/ipc/ipdl/test/cxx/TestBridgeMain.h
+++ b/ipc/ipdl/test/cxx/TestBridgeMain.h
@@ -26,17 +26,17 @@ public:
     virtual ~TestBridgeMainParent() {}
 
     static bool RunTestInProcesses() { return true; }
     static bool RunTestInThreads() { return false; }
 
     void Main();
 
 protected:
-    virtual PTestBridgeMainSubParent*
+    virtual bool
     AllocPTestBridgeMainSubParent(Transport* transport,
                                   ProcessId otherProcess) MOZ_OVERRIDE;
 
     virtual void ActorDestroy(ActorDestroyReason why) MOZ_OVERRIDE;
 };
 
 class TestBridgeMainSubParent :
     public PTestBridgeMainSubParent
@@ -100,17 +100,17 @@ class TestBridgeSubChild :
 {
 public:
     TestBridgeSubChild();
     virtual ~TestBridgeSubChild() {}
 
 protected:
     virtual bool RecvPing() MOZ_OVERRIDE;
 
-    virtual PTestBridgeMainSubChild*
+    virtual bool
     AllocPTestBridgeMainSubChild(Transport* transport,
                                  ProcessId otherProcess) MOZ_OVERRIDE;
 
     virtual void ActorDestroy(ActorDestroyReason why) MOZ_OVERRIDE;
 };
 
 class TestBridgeMainSubChild :
     public PTestBridgeMainSubChild
--- a/ipc/ipdl/test/cxx/TestOpens.cpp
+++ b/ipc/ipdl/test/cxx/TestOpens.cpp
@@ -59,37 +59,37 @@ OpenParent(TestOpensOpenedParent* aParen
     // Open the actor on the off-main thread to park it there.
     // Messages will be delivered to this thread's message loop
     // instead of the main thread's.
     if (!aParent->Open(aTransport, aOtherProcess,
                        XRE_GetIOMessageLoop(), AsyncChannel::Parent))
         fail("opening Parent");
 }
 
-PTestOpensOpenedParent*
+bool
 TestOpensParent::AllocPTestOpensOpenedParent(Transport* transport,
                                              ProcessId otherProcess)
 {
     gMainThread = MessageLoop::current();
 
     ProcessHandle h;
     if (!base::OpenProcessHandle(otherProcess, &h)) {
-        return nullptr;
+        return false;
     }
 
     gParentThread = new Thread("ParentThread");
     if (!gParentThread->Start())
         fail("starting parent thread");
 
     TestOpensOpenedParent* a = new TestOpensOpenedParent(transport);
     gParentThread->message_loop()->PostTask(
         FROM_HERE,
         NewRunnableFunction(OpenParent, a, transport, h));
 
-    return a;
+    return true;
 }
 
 void
 TestOpensParent::ActorDestroy(ActorDestroyReason why)
 {
     // Stops the thread and joins it
     delete gParentThread;
 
@@ -172,37 +172,37 @@ OpenChild(TestOpensOpenedChild* aChild,
                       XRE_GetIOMessageLoop(), AsyncChannel::Child))
         fail("opening Child");
 
     // Kick off the unit tests
     if (!aChild->SendHello())
         fail("sending Hello");
 }
 
-PTestOpensOpenedChild*
+bool
 TestOpensChild::AllocPTestOpensOpenedChild(Transport* transport,
                                            ProcessId otherProcess)
 {
     gMainThread = MessageLoop::current();
 
     ProcessHandle h;
     if (!base::OpenProcessHandle(otherProcess, &h)) {
-        return nullptr;
+        return false;
     }
 
     gChildThread = new Thread("ChildThread");
     if (!gChildThread->Start())
         fail("starting child thread");
 
     TestOpensOpenedChild* a = new TestOpensOpenedChild(transport);
     gChildThread->message_loop()->PostTask(
         FROM_HERE,
         NewRunnableFunction(OpenChild, a, transport, h));
 
-    return a;
+    return true;
 }
 
 void
 TestOpensChild::ActorDestroy(ActorDestroyReason why)
 {
     // Stops the thread and joins it
     delete gChildThread;
 
--- a/ipc/ipdl/test/cxx/TestOpens.h
+++ b/ipc/ipdl/test/cxx/TestOpens.h
@@ -22,17 +22,17 @@ public:
     virtual ~TestOpensParent() {}
 
     static bool RunTestInProcesses() { return true; }
     static bool RunTestInThreads() { return false; }
 
     void Main();
 
 protected:
-    virtual PTestOpensOpenedParent*
+    virtual bool
     AllocPTestOpensOpenedParent(Transport* transport, ProcessId otherProcess) MOZ_OVERRIDE;
 
     virtual void ActorDestroy(ActorDestroyReason why) MOZ_OVERRIDE;
 };
 
 } // namespace _ipdltest
 
 namespace _ipdltest2 {
@@ -65,17 +65,17 @@ class TestOpensChild : public PTestOpens
 {
 public:
     TestOpensChild();
     virtual ~TestOpensChild() {}
 
 protected:
     virtual bool RecvStart() MOZ_OVERRIDE;
 
-    virtual PTestOpensOpenedChild*
+    virtual bool
     AllocPTestOpensOpenedChild(Transport* transport, ProcessId otherProcess) MOZ_OVERRIDE;
 
     virtual void ActorDestroy(ActorDestroyReason why) MOZ_OVERRIDE;
 };
 
 } // namespace _ipdltest
 
 namespace _ipdltest2 {
--- a/ipc/testshell/TestShellParent.h
+++ b/ipc/testshell/TestShellParent.h
@@ -8,17 +8,17 @@
 #ifndef ipc_testshell_TestShellParent_h
 #define ipc_testshell_TestShellParent_h 1
 
 #include "mozilla/ipc/PTestShellParent.h"
 #include "mozilla/ipc/PTestShellCommandParent.h"
 
 #include "js/TypeDecls.h"
 #include "nsAutoJSValHolder.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 
 namespace mozilla {
 
 namespace ipc {
 
 class TestShellCommandParent;
 
 class TestShellParent : public PTestShellParent
--- a/ipc/testshell/XPCShellEnvironment.h
+++ b/ipc/testshell/XPCShellEnvironment.h
@@ -8,17 +8,17 @@
 #include "base/basictypes.h"
 
 #include <string>
 #include <stdio.h>
 
 #include "nsAutoJSValHolder.h"
 #include "nsCOMPtr.h"
 #include "nsDebug.h"
-#include "nsStringGlue.h"
+#include "nsString.h"
 #include "nsJSPrincipals.h"
 #include "nsContentUtils.h"
 #include "js/TypeDecls.h"
 
 struct JSPrincipals;
 
 namespace mozilla {
 namespace ipc {
--- a/js/public/RootingAPI.h
+++ b/js/public/RootingAPI.h
@@ -710,22 +710,25 @@ class MOZ_STACK_CLASS Rooted : public js
     Rooted(JSRuntime *rt, T initial
            MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
       : ptr(initial)
     {
         MOZ_GUARD_OBJECT_NOTIFIER_INIT;
         init(js::PerThreadDataFriendFields::getMainThread(rt));
     }
 
+    // Note that we need to let the compiler generate the default destructor in
+    // non-exact-rooting builds because of a bug in the instrumented PGO builds
+    // using MSVC, see bug 915735 for more details.
+#ifdef JSGC_TRACK_EXACT_ROOTS
     ~Rooted() {
-#ifdef JSGC_TRACK_EXACT_ROOTS
         JS_ASSERT(*stack == reinterpret_cast<Rooted<void*>*>(this));
         *stack = prev;
+    }
 #endif
-    }
 
 #ifdef JSGC_TRACK_EXACT_ROOTS
     Rooted<T> *previous() { return prev; }
 #endif
 
     /*
      * Important: Return a reference here so passing a Rooted<T> to
      * something that takes a |const T&| is not a GC hazard.
--- a/js/src/assembler/assembler/X86Assembler.h
+++ b/js/src/assembler/assembler/X86Assembler.h
@@ -1307,16 +1307,23 @@ public:
 #endif
     void cmpl_rm(RegisterID reg, const void* addr)
     {
         spew("cmpl       %s, %p",
              nameIReg(4, reg), addr);
         m_formatter.oneByteOp(OP_CMP_EvGv, reg, addr);
     }
 
+    void cmpl_rm_force32(RegisterID reg, const void* addr)
+    {
+        spew("cmpl       %s, %p",
+             nameIReg(4, reg), addr);
+        m_formatter.oneByteOp_disp32(OP_CMP_EvGv, reg, addr);
+    }
+
     void cmpl_im(int imm, const void* addr)
     {
         spew("cmpl       $0x%x, %p", imm, addr);
         if (CAN_SIGN_EXTEND_8_32(imm)) {
             m_formatter.oneByteOp(OP_GROUP1_EvIb, GROUP1_OP_CMP, addr);
             m_formatter.immediate8(imm);
         } else {
             m_formatter.oneByteOp(OP_GROUP1_EvIz, GROUP1_OP_CMP, addr);
@@ -3354,16 +3361,23 @@ private:
         }
 
         void oneByteOp(OneByteOpcodeID opcode, int reg, const void* address)
         {
             m_buffer.ensureSpace(maxInstructionSize);
             m_buffer.putByteUnchecked(opcode);
             memoryModRM(reg, address);
         }
+
+        void oneByteOp_disp32(OneByteOpcodeID opcode, int reg, const void* address)
+        {
+            m_buffer.ensureSpace(maxInstructionSize);
+            m_buffer.putByteUnchecked(opcode);
+            memoryModRM_disp32(reg, address);
+        }
 #if WTF_CPU_X86_64
         void oneByteRipOp(OneByteOpcodeID opcode, int reg, int ripOffset)
         {
             m_buffer.ensureSpace(maxInstructionSize);
             emitRexIfNeeded(reg, 0, 0);
             m_buffer.putByteUnchecked(opcode);
             putModRm(ModRmMemoryNoDisp, reg, noBase);
             m_buffer.putIntUnchecked(ripOffset);
@@ -3882,30 +3896,35 @@ private:
             //
             //   reg := [scaled index] + disp32 + [ebp]
             //
             // See Intel developer manual, Vol 2, 2.1.5, Table 2-3.
             putModRmSib(ModRmMemoryNoDisp, reg, noBase, index, scale);
             m_buffer.putIntUnchecked(offset);
         }
 
-        void memoryModRM(int reg, const void* address)
+        void memoryModRM_disp32(int reg, const void* address)
         {
             int32_t disp = addressImmediate(address);
 
 #if WTF_CPU_X86_64
             // On x64-64, non-RIP-relative absolute mode requires a SIB.
             putModRmSib(ModRmMemoryNoDisp, reg, noBase, noIndex, 0);
 #else
             // noBase + ModRmMemoryNoDisp means noBase + ModRmMemoryDisp32!
             putModRm(ModRmMemoryNoDisp, reg, noBase);
 #endif
             m_buffer.putIntUnchecked(disp);
         }
 
+        void memoryModRM(int reg, const void* address)
+        {
+            memoryModRM_disp32(reg, address);
+        }
+
         AssemblerBuffer m_buffer;
     } m_formatter;
 };
 
 } // namespace JSC
 
 #endif // ENABLE(ASSEMBLER) && CPU(X86)
 
--- a/js/src/config/config.mk
+++ b/js/src/config/config.mk
@@ -792,18 +792,18 @@ EXPAND_LIBNAME = $(foreach lib,$(1),$(LI
 endif
 EXPAND_LIBNAME_PATH = $(foreach lib,$(1),$(2)/$(LIB_PREFIX)$(lib).$(LIB_SUFFIX))
 EXPAND_MOZLIBNAME = $(foreach lib,$(1),$(DIST)/lib/$(LIB_PREFIX)$(lib).$(LIB_SUFFIX))
 
 PLY_INCLUDE = -I$(topsrcdir)/other-licenses/ply
 
 export CL_INCLUDES_PREFIX
 
-ifeq ($(MOZ_WIDGET_GTK),2)
-MOZ_GTK2_CFLAGS := -I$(topsrcdir)/widget/gtk2/compat $(MOZ_GTK2_CFLAGS)
+ifdef MOZ_GTK2_CFLAGS
+MOZ_GTK2_CFLAGS := -I$(topsrcdir)/widget/gtk/compat $(MOZ_GTK2_CFLAGS)
 endif
 
 DEFINES += -DNO_NSPR_10_SUPPORT
 
 # Run a named Python build action. The first argument is the name of the build
 # action. The second argument are the arguments to pass to the action (space
 # delimited arguments). e.g.
 #
--- a/js/src/config/makefiles/java-build.mk
+++ b/js/src/config/makefiles/java-build.mk
@@ -2,26 +2,26 @@
 # vim:set ts=8 sw=8 sts=8 noet:
 #
 # 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 INCLUDED_JAVA_BUILD_MK #{
 
-ifdef RES_FILES #{
+ifdef ANDROID_RESFILES #{
 res-dep := .deps-copy-java-res
 
 GENERATED_DIRS += res
 GARBAGE        += $(res-dep)
 
 export:: $(res-dep)
 
 res-dep-preqs := \
-  $(addprefix $(srcdir)/,$(RES_FILES)) \
+  $(addprefix $(srcdir)/,$(ANDROID_RESFILES)) \
   $(call mkdir_deps,res) \
   $(if $(IS_LANGUAGE_REPACK),FORCE) \
   $(NULL)
 
 # nop-build: only copy res/ files when needed
 $(res-dep): $(res-dep-preqs)
 	$(call copy_dir,$(srcdir)/res,$(CURDIR)/res)
 	@$(TOUCH) $@
--- a/js/src/config/rules.mk
+++ b/js/src/config/rules.mk
@@ -1220,17 +1220,17 @@ non-root-path = $(shell echo $(1) | sed 
 normalizepath = $(foreach p,$(1),$(if $(filter /%,$(1)),$(patsubst %/,%,$(shell cd $(call root-path,$(1)) && pwd -W))/$(call non-root-path,$(1)),$(1)))
 else
 normalizepath = $(1)
 endif
 
 ###############################################################################
 # Java rules
 ###############################################################################
-ifneq (,$(value JAVAFILES)$(value RESFILES))
+ifneq (,$(value JAVAFILES)$(value ANDROID_RESFILES))
   include $(topsrcdir)/config/makefiles/java-build.mk
 endif
 
 ###############################################################################
 # Update Files Managed by Build Backend
 ###############################################################################
 
 ifndef NO_MAKEFILE_RULE
--- a/js/src/devtools/rootAnalysis/analyze.py
+++ b/js/src/devtools/rootAnalysis/analyze.py
@@ -138,38 +138,42 @@ def out_indexes(command):
 def run_job(name, config):
     cmdspec, outfiles = JOBS[name]
     print("Running " + name + " to generate " + str(outfiles))
     if hasattr(cmdspec, '__call__'):
         cmdspec(config, outfiles)
     else:
         temp_map = {}
         cmdspec = fill(cmdspec, config)
-        temp = '%s.tmp' % name
         if isinstance(outfiles, basestring):
-            temp_map[temp] = outfiles
+            stdout_filename = '%s.tmp' % name
+            temp_map[stdout_filename] = outfiles
             print_command(cmdspec, outfile=outfiles, env=env(config))
         else:
+            stdout_filename = None
             pc = list(cmdspec)
             outfile = 0
             for (i, name) in out_indexes(cmdspec):
                 pc[i] = outfiles[outfile]
                 outfile += 1
             print_command(pc, env=env(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))
+        if stdout_filename is None:
+            subprocess.check_call(command, env=env(config))
+        else:
+            with open(stdout_filename, '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
 
 config = { 'ANALYSIS_SCRIPTDIR': os.path.dirname(__file__) }
new file mode 100644
--- /dev/null
+++ b/js/src/jit-test/tests/auto-regress/bug912379.js
@@ -0,0 +1,12 @@
+s = newGlobal();
+evalcx("\
+    try { \
+        throw StopIteration;\
+    } catch(a) {\
+        x = a;\
+    } \
+    wrap(x);\
+", s);
+evalcx("\
+    n = x;\
+", s);
--- a/js/src/jit/AsmJS.cpp
+++ b/js/src/jit/AsmJS.cpp
@@ -7,17 +7,16 @@
 #include "jit/AsmJS.h"
 
 #include "mozilla/Move.h"
 
 #ifdef MOZ_VTUNE
 # include "vtune/VTuneWrapper.h"
 #endif
 
-#include "jsmath.h"
 #include "jsprf.h"
 #include "jsworkers.h"
 #include "prmjtime.h"
 
 #include "frontend/Parser.h"
 #include "jit/AsmJSLink.h"
 #include "jit/AsmJSModule.h"
 #include "jit/AsmJSSignalHandlers.h"
@@ -1767,16 +1766,26 @@ class MOZ_STACK_CLASS ModuleCompiler
         // not need patching after deserialization.
         uint8_t *code = module_->codeBase();
         for (unsigned i = 0; i < globalAccesses_.length(); i++) {
             AsmJSGlobalAccess a = globalAccesses_[i];
             masm_.patchAsmJSGlobalAccess(a.patchAt, code, module_->globalData(), a.globalDataOffset);
         }
 #endif
 
+        // Absolute links
+        for (size_t i = 0; i < masm_.numAsmJSAbsoluteLinks(); i++) {
+            AsmJSAbsoluteLink src = masm_.asmJSAbsoluteLink(i);
+            AsmJSStaticLinkData::AbsoluteLink link;
+            link.patchAt = masm_.actualOffset(src.patchAt.offset());
+            link.target = src.target;
+            if (!linkData->absoluteLinks.append(link))
+                return false;
+        }
+
         *module = module_.forget();
         return true;
     }
 };
 
 } /* anonymous namespace */
 
 /*****************************************************************************/
@@ -2280,17 +2289,17 @@ class FunctionCompiler
         unsigned globalDataOffset = module().exitIndexToGlobalDataOffset(exitIndex);
 
         MAsmJSLoadFFIFunc *ptrFun = MAsmJSLoadFFIFunc::New(globalDataOffset);
         curBlock_->add(ptrFun);
 
         return callPrivate(MAsmJSCall::Callee(ptrFun), call, returnType, def);
     }
 
-    bool builtinCall(void *builtin, const Call &call, MIRType returnType, MDefinition **def)
+    bool builtinCall(AsmJSImmKind builtin, const Call &call, MIRType returnType, MDefinition **def)
     {
         return callPrivate(MAsmJSCall::Callee(builtin), call, returnType, def);
     }
 
     /*********************************************** Control flow generation */
 
     void returnExpr(MDefinition *expr)
     {
@@ -3763,58 +3772,46 @@ CheckFFICall(FunctionCompiler &f, ParseN
 
     if (!f.ffiCall(exitIndex, call, retType.toMIRType(), def))
         return false;
 
     *type = retType.toType();
     return true;
 }
 
-static inline void *
-UnaryMathFunCast(double (*pf)(double))
-{
-    return JS_FUNC_TO_DATA_PTR(void*, pf);
-}
-
-static inline void *
-BinaryMathFunCast(double (*pf)(double, double))
-{
-    return JS_FUNC_TO_DATA_PTR(void*, pf);
-}
-
 static bool
 CheckIsDoublish(FunctionCompiler &f, ParseNode *argNode, Type type)
 {
     if (!type.isDoublish())
         return f.failf(argNode, "%s is not a subtype of doublish", type.toChars());
     return true;
 }
 
 static bool
 CheckMathBuiltinCall(FunctionCompiler &f, ParseNode *callNode, AsmJSMathBuiltin mathBuiltin,
                      RetType retType, MDefinition **def, Type *type)
 {
     unsigned arity = 0;
-    void *callee = NULL;
+    AsmJSImmKind callee;
     switch (mathBuiltin) {
       case AsmJSMathBuiltin_imul:  return CheckMathIMul(f, callNode, retType, def, type);
       case AsmJSMathBuiltin_abs:   return CheckMathAbs(f, callNode, retType, def, type);
-      case AsmJSMathBuiltin_sin:   arity = 1; callee = UnaryMathFunCast(sin);        break;
-      case AsmJSMathBuiltin_cos:   arity = 1; callee = UnaryMathFunCast(cos);        break;
-      case AsmJSMathBuiltin_tan:   arity = 1; callee = UnaryMathFunCast(tan);        break;
-      case AsmJSMathBuiltin_asin:  arity = 1; callee = UnaryMathFunCast(asin);       break;
-      case AsmJSMathBuiltin_acos:  arity = 1; callee = UnaryMathFunCast(acos);       break;
-      case AsmJSMathBuiltin_atan:  arity = 1; callee = UnaryMathFunCast(atan);       break;
-      case AsmJSMathBuiltin_ceil:  arity = 1; callee = UnaryMathFunCast(ceil);       break;
-      case AsmJSMathBuiltin_floor: arity = 1; callee = UnaryMathFunCast(floor);      break;
-      case AsmJSMathBuiltin_exp:   arity = 1; callee = UnaryMathFunCast(exp);        break;
-      case AsmJSMathBuiltin_log:   arity = 1; callee = UnaryMathFunCast(log);        break;
       case AsmJSMathBuiltin_sqrt:  return CheckMathSqrt(f, callNode, retType, def, type);
-      case AsmJSMathBuiltin_pow:   arity = 2; callee = BinaryMathFunCast(ecmaPow);   break;
-      case AsmJSMathBuiltin_atan2: arity = 2; callee = BinaryMathFunCast(ecmaAtan2); break;
+      case AsmJSMathBuiltin_sin:   arity = 1; callee = AsmJSImm_SinD;   break;
+      case AsmJSMathBuiltin_cos:   arity = 1; callee = AsmJSImm_CosD;   break;
+      case AsmJSMathBuiltin_tan:   arity = 1; callee = AsmJSImm_TanD;   break;
+      case AsmJSMathBuiltin_asin:  arity = 1; callee = AsmJSImm_ASinD;  break;
+      case AsmJSMathBuiltin_acos:  arity = 1; callee = AsmJSImm_ACosD;  break;
+      case AsmJSMathBuiltin_atan:  arity = 1; callee = AsmJSImm_ATanD;  break;
+      case AsmJSMathBuiltin_ceil:  arity = 1; callee = AsmJSImm_CeilD;  break;
+      case AsmJSMathBuiltin_floor: arity = 1; callee = AsmJSImm_FloorD; break;
+      case AsmJSMathBuiltin_exp:   arity = 1; callee = AsmJSImm_ExpD;   break;
+      case AsmJSMathBuiltin_log:   arity = 1; callee = AsmJSImm_LogD;   break;
+      case AsmJSMathBuiltin_pow:   arity = 2; callee = AsmJSImm_PowD;   break;
+      case AsmJSMathBuiltin_atan2: arity = 2; callee = AsmJSImm_ATan2D; break;
     }
 
     FunctionCompiler::Call call(f, retType);
     if (!CheckCallArgs(f, callNode, CheckIsDoublish, &call))
         return false;
 
     if (call.sig().args().length() != arity)
         return f.failf(callNode, "call passed %u arguments, expected %u", call.sig().args().length(), arity);
@@ -5439,17 +5436,20 @@ static const RegisterSet AllRegsExceptSP
                 FloatRegisterSet(FloatRegisters::AllMask));
 static const RegisterSet NonVolatileRegs =
     RegisterSet(GeneralRegisterSet(Registers::NonVolatileMask),
                 FloatRegisterSet(FloatRegisters::NonVolatileMask));
 
 static void
 LoadAsmJSActivationIntoRegister(MacroAssembler &masm, Register reg)
 {
-    masm.loadPtr(AbsoluteAddress(GetIonContext()->runtime->mainThread.addressOfAsmJSActivationStackReadOnly()), reg);
+    masm.movePtr(AsmJSImm_Runtime, reg);
+    size_t offset = offsetof(JSRuntime, mainThread) +
+                    PerThreadData::offsetOfAsmJSActivationStackReadOnly();
+    masm.loadPtr(Address(reg, offset), reg);
 }
 
 static void
 LoadJSContextFromActivation(MacroAssembler &masm, Register activation, Register dest)
 {
     masm.loadPtr(Address(activation, AsmJSActivation::offsetOfContext()), dest);
 }
 
@@ -5640,34 +5640,36 @@ TryEnablingIon(JSContext *cx, AsmJSModul
     IonScript *ionScript = script->ionScript();
     if (!ionScript->addDependentAsmJSModule(cx, DependentAsmJSModuleExit(&module, exitIndex)))
         return false;
 
     module.exitIndexToGlobalDatum(exitIndex).exit = module.ionExitTrampoline(module.exit(exitIndex));
     return true;
 }
 
-static int32_t
+namespace js {
+
+int32_t
 InvokeFromAsmJS_Ignore(JSContext *cx, int32_t exitIndex, int32_t argc, Value *argv)
 {
     AsmJSModule &module = cx->mainThread().asmJSActivationStackFromOwnerThread()->module();
 
     RootedFunction fun(cx, module.exitIndexToGlobalDatum(exitIndex).fun);
     RootedValue fval(cx, ObjectValue(*fun));
     RootedValue rval(cx);
     if (!Invoke(cx, UndefinedValue(), fval, argc, argv, &rval))
         return false;
 
     if (!TryEnablingIon(cx, module, fun, exitIndex, argc, argv))
         return false;
 
     return true;
 }
 
-static int32_t
+int32_t
 InvokeFromAsmJS_ToInt32(JSContext *cx, int32_t exitIndex, int32_t argc, Value *argv)
 {
     AsmJSModule &module = cx->mainThread().asmJSActivationStackFromOwnerThread()->module();
 
     RootedFunction fun(cx, module.exitIndexToGlobalDatum(exitIndex).fun);
     RootedValue fval(cx, ObjectValue(*fun));
     RootedValue rval(cx);
     if (!Invoke(cx, UndefinedValue(), fval, argc, argv, &rval))
@@ -5679,17 +5681,17 @@ InvokeFromAsmJS_ToInt32(JSContext *cx, i
     int32_t i32;
     if (!ToInt32(cx, rval, &i32))
         return false;
     argv[0] = Int32Value(i32);
 
     return true;
 }
 
-static int32_t
+int32_t
 InvokeFromAsmJS_ToNumber(JSContext *cx, int32_t exitIndex, int32_t argc, Value *argv)
 {
     AsmJSModule &module = cx->mainThread().asmJSActivationStackFromOwnerThread()->module();
 
     RootedFunction fun(cx, module.exitIndexToGlobalDatum(exitIndex).fun);
     RootedValue fval(cx, ObjectValue(*fun));
     RootedValue rval(cx);
     if (!Invoke(cx, UndefinedValue(), fval, argc, argv, &rval))
@@ -5701,16 +5703,18 @@ InvokeFromAsmJS_ToNumber(JSContext *cx, 
     double dbl;
     if (!ToNumber(cx, rval, &dbl))
         return false;
     argv[0] = DoubleValue(dbl);
 
     return true;
 }
 
+}  // namespace js
+
 static void
 FillArgumentArray(ModuleCompiler &m, const VarTypeVector &argTypes,
                   unsigned offsetToArgs, unsigned offsetToCallerStackArgs,
                   Register scratch)
 {
     MacroAssembler &masm = m.masm();
 
     for (ABIArgTypeIter i(argTypes); !i.done(); i++) {
@@ -5818,26 +5822,26 @@ GenerateFFIInterpreterExit(ModuleCompile
     }
     i++;
     JS_ASSERT(i.done());
 
     // Make the call, test whether it succeeded, and extract the return value.
     AssertStackAlignment(masm);
     switch (exit.sig().retType().which()) {
       case RetType::Void:
-        masm.call(ImmPtr(InvokeFromAsmJS_Ignore));
+        masm.call(AsmJSImm_InvokeFromAsmJS_Ignore);
         masm.branchTest32(Assembler::Zero, ReturnReg, ReturnReg, throwLabel);
         break;
       case RetType::Signed:
-        masm.call(ImmPtr(InvokeFromAsmJS_ToInt32));
+        masm.call(AsmJSImm_InvokeFromAsmJS_ToInt32);
         masm.branchTest32(Assembler::Zero, ReturnReg, ReturnReg, throwLabel);
         masm.unboxInt32(argv, ReturnReg);
         break;
       case RetType::Double:
-        masm.call(ImmPtr(InvokeFromAsmJS_ToNumber));
+        masm.call(AsmJSImm_InvokeFromAsmJS_ToNumber);
         masm.branchTest32(Assembler::Zero, ReturnReg, ReturnReg, throwLabel);
         masm.loadDouble(argv, ReturnFloatReg);
         break;
     }
 
     // Note: the caller is IonMonkey code which means there are no non-volatile
     // registers to restore.
     masm.freeStack(stackDec);
@@ -5869,62 +5873,40 @@ GenerateFFIInterpreterExit(ModuleCompile
 
     // argument 3: argv
     Address argv(StackPointer, ShadowStackSpace);
     masm.lea(Operand(argv), IntArgReg3);
 
     AssertStackAlignment(masm);
     switch (exit.sig().retType().which()) {
       case RetType::Void:
-        masm.call(ImmPtr(InvokeFromAsmJS_Ignore));
+        masm.call(AsmJSImm_InvokeFromAsmJS_Ignore);
         masm.branchTest32(Assembler::Zero, ReturnReg, ReturnReg, throwLabel);
         break;
       case RetType::Signed:
-        masm.call(ImmPtr(InvokeFromAsmJS_ToInt32));
+        masm.call(AsmJSImm_InvokeFromAsmJS_ToInt32);
         masm.branchTest32(Assembler::Zero, ReturnReg, ReturnReg, throwLabel);
         masm.unboxInt32(argv, ReturnReg);
         break;
       case RetType::Double:
-        masm.call(ImmPtr(InvokeFromAsmJS_ToNumber));
+        masm.call(AsmJSImm_InvokeFromAsmJS_ToNumber);
         masm.branchTest32(Assembler::Zero, ReturnReg, ReturnReg, throwLabel);
 #if defined(JS_CPU_ARM) && !defined(JS_CPU_ARM_HARDFP)
         masm.loadValue(argv, softfpReturnOperand);
 #else
         masm.loadDouble(argv, ReturnFloatReg);
 #endif
         break;
     }
 
     masm.freeStack(reserveSize + sizeof(int32_t));
     masm.ret();
 #endif
 }
 
-static int32_t
-ValueToInt32(JSContext *cx, MutableHandleValue val)
-{
-    int32_t i32;
-    if (!ToInt32(cx, val, &i32))
-        return false;
-    val.set(Int32Value(i32));
-
-    return true;
-}
-
-static int32_t
-ValueToNumber(JSContext *cx, MutableHandleValue val)
-{
-    double dbl;
-    if (!ToNumber(cx, val, &dbl))
-        return false;
-    val.set(DoubleValue(dbl));
-
-    return true;
-}
-
 static void
 GenerateOOLConvert(ModuleCompiler &m, RetType retType, Label *throwLabel)
 {
     MacroAssembler &masm = m.masm();
 
     MIRType typeArray[] = { MIRType_Pointer,   // cx
                             MIRType_Pointer }; // argv
     MIRTypeVector callArgTypes(m.cx());
@@ -5965,55 +5947,37 @@ GenerateOOLConvert(ModuleCompiler &m, Re
         masm.storePtr(scratch, Address(StackPointer, i->offsetFromArgBase()));
     }
     i++;
     JS_ASSERT(i.done());
 
     // Call
     switch (retType.which()) {
       case RetType::Signed:
-          masm.call(ImmPtr(ValueToInt32));
+          masm.call(AsmJSImm_CoerceInPlace_ToInt32);
           masm.branchTest32(Assembler::Zero, ReturnReg, ReturnReg, throwLabel);
           masm.unboxInt32(Address(StackPointer, offsetToArgv), ReturnReg);
           break;
       case RetType::Double:
-          masm.call(ImmPtr(ValueToNumber));
+          masm.call(AsmJSImm_CoerceInPlace_ToNumber);
           masm.branchTest32(Assembler::Zero, ReturnReg, ReturnReg, throwLabel);
 #if defined(JS_CPU_ARM) && !defined(JS_CPU_ARM_HARDFP)
           masm.loadValue(Address(StackPointer, offsetToArgv), softfpReturnOperand);
 #else
           masm.loadDouble(Address(StackPointer, offsetToArgv), ReturnFloatReg);
 #endif
           break;
       default:
           MOZ_ASSUME_UNREACHABLE("Unsupported convert type");
     }
 
     masm.freeStack(stackDec);
 }
 
 static void
-EnableActivation(AsmJSActivation *activation)
-{
-    JSContext *cx = activation->cx();
-    Activation *act = cx->mainThread().activation();
-    JS_ASSERT(act->isJit());
-    act->asJit()->setActive(cx);
-}
-
-static void
-DisableActivation(AsmJSActivation *activation)
-{
-    JSContext *cx = activation->cx();
-    Activation *act = cx->mainThread().activation();
-    JS_ASSERT(act->isJit());
-    act->asJit()->setActive(cx, false);
-}
-
-static void
 GenerateFFIIonExit(ModuleCompiler &m, const ModuleCompiler::ExitDescriptor &exit,
                          unsigned exitIndex, Label *throwLabel)
 {
     MacroAssembler &masm = m.masm();
     masm.align(CodeAlignment);
     m.setIonExitOffset(exitIndex);
     masm.setFramePushed(0);
 
@@ -6092,17 +6056,17 @@ GenerateFFIIonExit(ModuleCompiler &m, co
 
     masm.loadPtr(Address(callee, JSFunction::offsetOfNativeOrScript()), scratch);
     masm.loadBaselineOrIonNoArgCheck(scratch, scratch, SequentialExecution, maybeDebugBreakpoint);
 
     LoadAsmJSActivationIntoRegister(masm, callee);
     masm.push(scratch);
     masm.setupUnalignedABICall(1, scratch);
     masm.passABIArg(callee);
-    masm.callWithABI(JS_FUNC_TO_DATA_PTR(void *, EnableActivation));
+    masm.callWithABI(AsmJSImm_EnableActivationFromAsmJS);
     masm.pop(scratch);
 
     // 2. Call
 #if defined(JS_CPU_ARM) && defined(DEBUG)
     // ARM still needs to push, before stack is aligned
     masm.Push(scratch);
 #endif
     AssertStackAlignment(masm);
@@ -6112,17 +6076,17 @@ GenerateFFIIonExit(ModuleCompiler &m, co
     masm.callIon(scratch);
     masm.freeStack(stackDec - extraBytes);
 
     masm.push(JSReturnReg_Type);
     masm.push(JSReturnReg_Data);
     LoadAsmJSActivationIntoRegister(masm, callee);
     masm.setupUnalignedABICall(1, scratch);
     masm.passABIArg(callee);
-    masm.callWithABI(JS_FUNC_TO_DATA_PTR(void *, DisableActivation));
+    masm.callWithABI(AsmJSImm_DisableActivationFromAsmJS);
     masm.pop(JSReturnReg_Data);
     masm.pop(JSReturnReg_Type);
 
 #ifdef DEBUG
     masm.branchTestMagicValue(Assembler::Equal, JSReturnOperand, JS_ION_ERROR, throwLabel);
     masm.branchTestMagic(Assembler::Equal, JSReturnOperand, &ionFailed);
 #else
     masm.branchTestMagic(Assembler::Equal, JSReturnOperand, throwLabel);
@@ -6198,18 +6162,17 @@ GenerateStackOverflowExit(ModuleCompiler
 #if defined(JS_CPU_X86)
     LoadAsmJSActivationIntoRegister(masm, eax);
     LoadJSContextFromActivation(masm, eax, eax);
     masm.storePtr(eax, Address(StackPointer, 0));
 #else
     LoadAsmJSActivationIntoRegister(masm, IntArgReg0);
     LoadJSContextFromActivation(masm, IntArgReg0, IntArgReg0);
 #endif
-    void (*reportOverRecursed)(JSContext*) = js_ReportOverRecursed;
-    masm.call(ImmPtr(reportOverRecursed));
+    masm.call(AsmJSImm_ReportOverRecursed);
     masm.jump(throwLabel);
 
     return !masm.oom();
 }
 
 // The operation-callback exit is called from arbitrarily-interrupted asm.js
 // code. That means we must first save *all* registers and restore *all*
 // registers (except the stack pointer) when we resume. The address to resume to
@@ -6256,17 +6219,17 @@ GenerateOperationCallbackExit(ModuleComp
     // argument 0: cx
 #if defined(JS_CPU_X86)
     LoadJSContextFromActivation(masm, activation, scratch);
     masm.storePtr(scratch, Address(StackPointer, 0));
 #elif defined(JS_CPU_X64)
     LoadJSContextFromActivation(masm, activation, IntArgReg0);
 #endif
 
-    masm.call(ImmPtr(js_HandleExecutionInterrupt));
+    masm.call(AsmJSImm_HandleExecutionInterrupt);
     masm.branchIfFalseBool(ReturnReg, throwLabel);
 
     // Restore the StackPointer to it's position before the call.
     masm.mov(ABIArgGenerator::NonVolatileReg, StackPointer);
 
     // Restore the machine state to before the interrupt.
     masm.PopRegsInMask(AllRegsExceptSP); // restore all GP/FP registers (except SP)
     masm.popFlags();              // after this, nothing that sets conditions
@@ -6287,17 +6250,17 @@ GenerateOperationCallbackExit(ModuleComp
     LoadAsmJSActivationIntoRegister(masm, IntArgReg0);
     masm.loadPtr(Address(IntArgReg0, AsmJSActivation::offsetOfResumePC()), IntArgReg1);
     masm.storePtr(IntArgReg1, Address(r6, 14 * sizeof(uint32_t*)));
 
     // argument 0: cx
     masm.loadPtr(Address(IntArgReg0, AsmJSActivation::offsetOfContext()), IntArgReg0);
 
     masm.PushRegsInMask(RegisterSet(GeneralRegisterSet(0), FloatRegisterSet(FloatRegisters::AllMask)));   // save all FP registers
-    masm.call(ImmPtr(js_HandleExecutionInterrupt));
+    masm.call(AsmJSImm_HandleExecutionInterrupt);
     masm.branchIfFalseBool(ReturnReg, throwLabel);
 
     // Restore the machine state to before the interrupt. this will set the pc!
     masm.PopRegsInMask(RegisterSet(GeneralRegisterSet(0), FloatRegisterSet(FloatRegisters::AllMask)));   // restore all FP registers
     masm.mov(r6,sp);
     masm.as_vmsr(r5);
     masm.as_msr(r4);
     // Restore all GP registers
@@ -6450,17 +6413,17 @@ CheckModule(ExclusiveContext *cx, AsmJSP
     TokenKind tk = PeekToken(m.parser());
     if (tk != TOK_EOF && tk != TOK_RC)
         return m.fail(NULL, "top-level export (return) must be the last statement");
 
     AsmJSStaticLinkData linkData(cx);
     if (!FinishModule(m, module, &linkData))
         return false;
 
-    (*module)->staticallyLink(linkData);
+    (*module)->staticallyLink(linkData, cx);
 
     m.buildCompilationTimeReport(compilationTimeReport);
     return true;
 }
 
 static bool
 Warn(AsmJSParser &parser, int errorNumber, const char *str)
 {
@@ -6484,22 +6447,22 @@ EstablishPreconditions(ExclusiveContext 
         return Warn(parser, JSMSG_USE_ASM_TYPE_FAIL, "Disabled by javascript.options.asmjs in about:config");
 
     if (!parser.options().compileAndGo)
         return Warn(parser, JSMSG_USE_ASM_TYPE_FAIL, "Temporarily disabled for event-handler and other cloneable scripts");
 
     if (cx->compartment()->debugMode())
         return Warn(parser, JSMSG_USE_ASM_TYPE_FAIL, "Disabled by debugger");
 
-# ifdef JS_WORKER_THREADS
+#ifdef JS_WORKER_THREADS
     if (ParallelCompilationEnabled(cx)) {
         if (!EnsureWorkerThreadsInitialized(cx))
             return Warn(parser, JSMSG_USE_ASM_TYPE_FAIL, "Failed compilation thread initialization");
     }
-# endif
+#endif
 
     return true;
 }
 
 static bool
 NoExceptionPending(ExclusiveContext *cx)
 {
     return !cx->isJSContext() || !cx->asJSContext()->isExceptionPending();
--- a/js/src/jit/AsmJSModule.cpp
+++ b/js/src/jit/AsmJSModule.cpp
@@ -6,16 +6,18 @@
 
 #include "jit/AsmJSModule.h"
 #include "jit/IonCode.h"
 
 #ifndef XP_WIN
 # include <sys/mman.h>
 #endif
 
+#include "jslibmath.h"
+#include "jsmath.h"
 #ifdef XP_WIN
 # include "jswin.h"
 #endif
 
 #include "js/MemoryMetrics.h"
 
 #include "jsobjinlines.h"
 
@@ -35,16 +37,17 @@ AsmJSModule::initHeap(Handle<ArrayBuffer
     uint8_t *heapOffset = heap->dataPointer();
     void *heapLength = (void*)heap->byteLength();
     for (unsigned i = 0; i < heapAccesses_.length(); i++) {
         const jit::AsmJSHeapAccess &access = heapAccesses_[i];
         if (access.hasLengthCheck())
             JSC::X86Assembler::setPointer(access.patchLengthAt(code_), heapLength);
         void *addr = access.patchOffsetAt(code_);
         uint32_t disp = reinterpret_cast<uint32_t>(JSC::X86Assembler::getPointer(addr));
+        JS_ASSERT(disp <= INT32_MAX);
         JSC::X86Assembler::setPointer(addr, (void *)(heapOffset + disp));
     }
 #elif defined(JS_CPU_ARM)
     uint32_t heapLength = heap->byteLength();
     for (unsigned i = 0; i < heapAccesses_.length(); i++) {
         jit::Assembler::updateBoundsCheck(heapLength,
                                           (jit::Instruction*)(heapAccesses_[i].offset() + code_));
     }
@@ -104,28 +107,175 @@ AsmJSModule::allocateAndCopyCode(Exclusi
     if (!code_)
         return false;
 
     JS_ASSERT(uintptr_t(code_) % AsmJSPageSize == 0);
     masm.executableCopy(code_);
     return true;
 }
 
+static int32_t
+CoerceInPlace_ToInt32(JSContext *cx, MutableHandleValue val)
+{
+    int32_t i32;
+    if (!ToInt32(cx, val, &i32))
+        return false;
+    val.set(Int32Value(i32));
+
+    return true;
+}
+
+static int32_t
+CoerceInPlace_ToNumber(JSContext *cx, MutableHandleValue val)
+{
+    double dbl;
+    if (!ToNumber(cx, val, &dbl))
+        return false;
+    val.set(DoubleValue(dbl));
+
+    return true;
+}
+
+static void
+EnableActivationFromAsmJS(AsmJSActivation *activation)
+{
+    JSContext *cx = activation->cx();
+    Activation *act = cx->mainThread().activation();
+    JS_ASSERT(act->isJit());
+    act->asJit()->setActive(cx);
+}
+
+static void
+DisableActivationFromAsmJS(AsmJSActivation *activation)
+{
+    JSContext *cx = activation->cx();
+    Activation *act = cx->mainThread().activation();
+    JS_ASSERT(act->isJit());
+    act->asJit()->setActive(cx, false);
+}
+
+namespace js {
+
+// Defined in AsmJS.cpp:
+
+int32_t
+InvokeFromAsmJS_Ignore(JSContext *cx, int32_t exitIndex, int32_t argc, Value *argv);
+
+int32_t
+InvokeFromAsmJS_ToInt32(JSContext *cx, int32_t exitIndex, int32_t argc, Value *argv);
+
+int32_t
+InvokeFromAsmJS_ToNumber(JSContext *cx, int32_t exitIndex, int32_t argc, Value *argv);
+
+}
+
+#if defined(JS_CPU_ARM)
+extern "C" {
+
+extern int
+__aeabi_idivmod(int, int);
+
+extern int
+__aeabi_uidivmod(int, int);
+
+}
+#endif
+
+template <class F>
+static inline void *
+FuncCast(F *pf)
+{
+    return JS_FUNC_TO_DATA_PTR(void *, pf);
+}
+
+static void *
+AddressOf(AsmJSImmKind kind, ExclusiveContext *cx)
+{
+    switch (kind) {
+      case AsmJSImm_Runtime:
+        return cx->runtimeAddressForJit();
+      case AsmJSImm_StackLimit:
+        return cx->stackLimitAddress(StackForUntrustedScript);
+      case AsmJSImm_ReportOverRecursed:
+        return FuncCast<void (JSContext*)>(js_ReportOverRecursed);
+      case AsmJSImm_HandleExecutionInterrupt:
+        return FuncCast(js_HandleExecutionInterrupt);
+      case AsmJSImm_InvokeFromAsmJS_Ignore:
+        return FuncCast(InvokeFromAsmJS_Ignore);
+      case AsmJSImm_InvokeFromAsmJS_ToInt32:
+        return FuncCast(InvokeFromAsmJS_ToInt32);
+      case AsmJSImm_InvokeFromAsmJS_ToNumber:
+        return FuncCast(InvokeFromAsmJS_ToNumber);
+      case AsmJSImm_CoerceInPlace_ToInt32:
+        return FuncCast(CoerceInPlace_ToInt32);
+      case AsmJSImm_CoerceInPlace_ToNumber:
+        return FuncCast(CoerceInPlace_ToNumber);
+      case AsmJSImm_ToInt32:
+        return FuncCast<int32_t (double)>(js::ToInt32);
+      case AsmJSImm_EnableActivationFromAsmJS:
+        return FuncCast(EnableActivationFromAsmJS);
+      case AsmJSImm_DisableActivationFromAsmJS:
+        return FuncCast(DisableActivationFromAsmJS);
+#if defined(JS_CPU_ARM)
+      case AsmJSImm_aeabi_idivmod:
+        return FuncCast(__aeabi_idivmod);
+      case AsmJSImm_aeabi_uidivmod:
+        return FuncCast(__aeabi_uidivmod);
+#endif
+      case AsmJSImm_ModD:
+        return FuncCast(NumberMod);
+      case AsmJSImm_SinD:
+        return FuncCast<double (double)>(sin);
+      case AsmJSImm_CosD:
+        return FuncCast<double (double)>(cos);
+      case AsmJSImm_TanD:
+        return FuncCast<double (double)>(tan);
+      case AsmJSImm_ASinD:
+        return FuncCast<double (double)>(asin);
+      case AsmJSImm_ACosD:
+        return FuncCast<double (double)>(acos);
+      case AsmJSImm_ATanD:
+        return FuncCast<double (double)>(atan);
+      case AsmJSImm_CeilD:
+        return FuncCast<double (double)>(ceil);
+      case AsmJSImm_FloorD:
+        return FuncCast<double (double)>(floor);
+      case AsmJSImm_ExpD:
+        return FuncCast<double (double)>(exp);
+      case AsmJSImm_LogD:
+        return FuncCast<double (double)>(log);
+      case AsmJSImm_PowD:
+        return FuncCast(ecmaPow);
+      case AsmJSImm_ATan2D:
+        return FuncCast(ecmaAtan2);
+    }
+
+    MOZ_ASSUME_UNREACHABLE("Bad AsmJSImmKind");
+    return NULL;
+}
+
 void
-AsmJSModule::staticallyLink(const AsmJSStaticLinkData &linkData)
+AsmJSModule::staticallyLink(const AsmJSStaticLinkData &linkData, ExclusiveContext *cx)
 {
     // Process AsmJSStaticLinkData:
 
     operationCallbackExit_ = code_ + linkData.operationCallbackExitOffset;
 
     for (size_t i = 0; i < linkData.relativeLinks.length(); i++) {
         AsmJSStaticLinkData::RelativeLink link = linkData.relativeLinks[i];
         *(void **)(code_ + link.patchAtOffset) = code_ + link.targetOffset;
     }
 
+    for (size_t i = 0; i < linkData.absoluteLinks.length(); i++) {
+        AsmJSStaticLinkData::AbsoluteLink link = linkData.absoluteLinks[i];
+        Assembler::patchDataWithValueCheck(code_ + link.patchAt.offset(),
+                                           PatchedImmPtr(AddressOf(link.target, cx)),
+                                           PatchedImmPtr((void*)-1));
+    }
+
     // Initialize global data segment
 
     for (size_t i = 0; i < exits_.length(); i++) {
         exitIndexToGlobalDatum(i).exit = interpExitTrampoline(exits_[i]);
         exitIndexToGlobalDatum(i).fun = NULL;
     }
 }
 
--- a/js/src/jit/AsmJSModule.h
+++ b/js/src/jit/AsmJSModule.h
@@ -49,21 +49,30 @@ struct AsmJSStaticLinkData
     struct RelativeLink
     {
         uint32_t patchAtOffset;
         uint32_t targetOffset;
     };
 
     typedef Vector<RelativeLink> RelativeLinkVector;
 
+    struct AbsoluteLink
+    {
+        jit::CodeOffsetLabel patchAt;
+        jit::AsmJSImmKind target;
+    };
+
+    typedef Vector<AbsoluteLink> AbsoluteLinkVector;
+
     size_t operationCallbackExitOffset;
     RelativeLinkVector relativeLinks;
+    AbsoluteLinkVector absoluteLinks;
 
     AsmJSStaticLinkData(ExclusiveContext *cx)
-      : relativeLinks(cx)
+      : relativeLinks(cx), absoluteLinks(cx)
     {}
 };
 
 // An asm.js module represents the collection of functions nested inside a
 // single outer "use asm" function. For example, this asm.js module:
 //   function() { "use asm"; function f() {} function g() {} return f }
 // contains the functions 'f' and 'g'.
 //
@@ -668,17 +677,17 @@ class AsmJSModule
         if (len > minHeapLength_)
             minHeapLength_ = len;
     }
     uint32_t minHeapLength() const {
         return minHeapLength_;
     }
 
     bool allocateAndCopyCode(ExclusiveContext *cx, jit::MacroAssembler &masm);
-    void staticallyLink(const AsmJSStaticLinkData &linkData);
+    void staticallyLink(const AsmJSStaticLinkData &linkData, ExclusiveContext *cx);
 
     uint8_t *codeBase() const {
         JS_ASSERT(code_);
         JS_ASSERT(uintptr_t(code_) % AsmJSPageSize == 0);
         return code_;
     }
 
     uint8_t *operationCallbackExit() const {
--- a/js/src/jit/BaselineFrame.h
+++ b/js/src/jit/BaselineFrame.h
@@ -153,18 +153,18 @@ class BaselineFrame
     Value &unaliasedVar(unsigned i, MaybeCheckAliasing checkAliasing = CHECK_ALIASING) const {
         JS_ASSERT_IF(checkAliasing, !script()->varIsAliased(i));
         JS_ASSERT(i < script()->nfixed);
         return *valueSlot(i);
     }
 
     Value &unaliasedFormal(unsigned i, MaybeCheckAliasing checkAliasing = CHECK_ALIASING) const {
         JS_ASSERT(i < numFormalArgs());
-        JS_ASSERT_IF(checkAliasing, !script()->argsObjAliasesFormals());
-        JS_ASSERT_IF(checkAliasing, !script()->formalIsAliased(i));
+        JS_ASSERT_IF(checkAliasing, !script()->argsObjAliasesFormals() &&
+                                    !script()->formalIsAliased(i));
         return argv()[i];
     }
 
     Value &unaliasedActual(unsigned i, MaybeCheckAliasing checkAliasing = CHECK_ALIASING) const {
         JS_ASSERT(i < numActualArgs());
         JS_ASSERT_IF(checkAliasing, !script()->argsObjAliasesFormals());
         JS_ASSERT_IF(checkAliasing && i < numFormalArgs(), !script()->formalIsAliased(i));
         return argv()[i];
--- a/js/src/jit/BaselineIC.cpp
+++ b/js/src/jit/BaselineIC.cpp
@@ -842,19 +842,23 @@ PrepareOsrTempData(JSContext *cx, ICUseC
 
     //
     // Initialize the fake StackFrame.
     //
 
     // Copy formal args and thisv.
     memcpy(stackFrameStart, frame->argv() - 1, (numFormalArgs + 1) * sizeof(Value));
 
-    // Initialize ScopeChain, Exec, and Flags fields in StackFrame struct.
+    // Initialize ScopeChain, Exec, ArgsObj, and Flags fields in StackFrame struct.
     uint8_t *stackFrame = info->stackFrame;
     *((JSObject **) (stackFrame + StackFrame::offsetOfScopeChain())) = frame->scopeChain();
+    if (frame->script()->needsArgsObj()) {
+        JS_ASSERT(frame->hasArgsObj());
+        *((JSObject **) (stackFrame + StackFrame::offsetOfArgumentsObject())) = &frame->argsObj();
+    }
     if (frame->isFunctionFrame()) {
         // Store the function in exec field, and StackFrame::FUNCTION for flags.
         *((JSFunction **) (stackFrame + StackFrame::offsetOfExec())) = frame->fun();
         *((uint32_t *) (stackFrame + StackFrame::offsetOfFlags())) = StackFrame::FUNCTION;
     } else {
         *((JSScript **) (stackFrame + StackFrame::offsetOfExec())) = frame->script();
         *((uint32_t *) (stackFrame + StackFrame::offsetOfFlags())) = 0;
     }
--- a/js/src/jit/CodeGenerator.cpp
+++ b/js/src/jit/CodeGenerator.cpp
@@ -141,16 +141,17 @@ MNewStringObject::templateObj() const {
 CodeGenerator::CodeGenerator(MIRGenerator *gen, LIRGraph *graph, MacroAssembler *masm)
   : CodeGeneratorSpecific(gen, graph, masm),
     unassociatedScriptCounts_(NULL)
 {
 }
 
 CodeGenerator::~CodeGenerator()
 {
+    JS_ASSERT_IF(!gen->compilingAsmJS(), masm.numAsmJSAbsoluteLinks() == 0);
     js_delete(unassociatedScriptCounts_);
 }
 
 typedef bool (*StringToNumberFn)(ThreadSafeContext *, JSString *, double *);
 typedef ParallelResult (*StringToNumberParFn)(ForkJoinSlice *, JSString *, double *);
 static const VMFunctionsModal StringToNumberInfo = VMFunctionsModal(
     FunctionInfo<StringToNumberFn>(StringToNumber),
     FunctionInfo<StringToNumberParFn>(StringToNumberPar));
@@ -1020,16 +1021,28 @@ CodeGenerator::visitOsrScopeChain(LOsrSc
 
     const ptrdiff_t frameOffset = StackFrame::offsetOfScopeChain();
 
     masm.loadPtr(Address(ToRegister(frame), frameOffset), ToRegister(object));
     return true;
 }
 
 bool
+CodeGenerator::visitOsrArgumentsObject(LOsrArgumentsObject *lir)
+{
+    const LAllocation *frame   = lir->getOperand(0);
+    const LDefinition *object  = lir->getDef(0);
+
+    const ptrdiff_t frameOffset = StackFrame::offsetOfArgumentsObject();
+
+    masm.loadPtr(Address(ToRegister(frame), frameOffset), ToRegister(object));
+    return true;
+}
+
+bool
 CodeGenerator::visitStackArgT(LStackArgT *lir)
 {
     const LAllocation *arg = lir->getArgument();
     MIRType argType = lir->mir()->getArgument()->type();
     uint32_t argslot = lir->argslot();
 
     int32_t stack_offset = StackOffsetOfPassedArg(argslot);
     Address dest(StackPointer, stack_offset);
@@ -1899,17 +1912,17 @@ CodeGenerator::emitCallToUncompiledScrip
 }
 
 bool
 CodeGenerator::visitCallKnown(LCallKnown *call)
 {
     Register calleereg = ToRegister(call->getFunction());
     Register objreg    = ToRegister(call->getTempObject());
     uint32_t unusedStack = StackOffsetOfPassedArg(call->argslot());
-    JSFunction *target = call->getSingleTarget();
+    DebugOnly<JSFunction *> target = call->getSingleTarget();
     ExecutionMode executionMode = gen->info().executionMode();
     Label end, uncompiled;
 
     // Native single targets are handled by LCallNative.
     JS_ASSERT(!target->isNative());
     // Missing arguments must have been explicitly appended by the IonBuilder.
     JS_ASSERT(target->nargs <= call->numStackArgs());
 
@@ -3815,17 +3828,20 @@ CodeGenerator::visitModD(LModD *ins)
     Register temp = ToRegister(ins->temp());
 
     JS_ASSERT(ToFloatRegister(ins->output()) == ReturnFloatReg);
 
     masm.setupUnalignedABICall(2, temp);
     masm.passABIArg(lhs);
     masm.passABIArg(rhs);
 
-    masm.callWithABI(JS_FUNC_TO_DATA_PTR(void *, NumberMod), MacroAssembler::DOUBLE);
+    if (gen->compilingAsmJS())
+        masm.callWithABI(AsmJSImm_ModD, MacroAssembler::DOUBLE);
+    else
+        masm.callWithABI(JS_FUNC_TO_DATA_PTR(void *, NumberMod), MacroAssembler::DOUBLE);
     return true;
 }
 
 typedef bool (*BinaryFn)(JSContext *, HandleScript, jsbytecode *,
                          MutableHandleValue, MutableHandleValue, Value *);
 typedef ParallelResult (*BinaryParFn)(ForkJoinSlice *, HandleValue, HandleValue,
                                       Value *);
 
@@ -7376,17 +7392,17 @@ CodeGenerator::visitAsmJSCall(LAsmJSCall
     switch (callee.which()) {
       case MAsmJSCall::Callee::Internal:
         masm.call(callee.internal());
         break;
       case MAsmJSCall::Callee::Dynamic:
         masm.call(ToRegister(ins->getOperand(mir->dynamicCalleeOperandIndex())));
         break;
       case MAsmJSCall::Callee::Builtin:
-        masm.call(ImmPtr(callee.builtin()));
+        masm.call(callee.builtin());
         break;
     }
 
     if (mir->spIncrement())
         masm.reserveStack(mir->spIncrement());
 
     postAsmJSCall(ins);
     return true;
@@ -7428,19 +7444,18 @@ CodeGenerator::visitAsmJSVoidReturn(LAsm
     if (current->mir() != *gen->graph().poBegin())
         masm.jump(&returnLabel_);
     return true;
 }
 
 bool
 CodeGenerator::visitAsmJSCheckOverRecursed(LAsmJSCheckOverRecursed *lir)
 {
-    uintptr_t *limitAddr = &GetIonContext()->runtime->mainThread.nativeStackLimit[StackForUntrustedScript];
     masm.branchPtr(Assembler::AboveOrEqual,
-                   AbsoluteAddress(limitAddr),
+                   AsmJSAbsoluteAddress(AsmJSImm_StackLimit),
                    StackPointer,
                    lir->mir()->onError());
     return true;
 }
 
 bool
 CodeGenerator::emitAssertRangeI(const Range *r, Register input)
 {
--- a/js/src/jit/CodeGenerator.h
+++ b/js/src/jit/CodeGenerator.h
@@ -61,16 +61,17 @@ class CodeGenerator : public CodeGenerat
     bool visitParameter(LParameter *lir);
     bool visitCallee(LCallee *lir);
     bool visitStart(LStart *lir);
     bool visitReturn(LReturn *ret);
     bool visitDefVar(LDefVar *lir);
     bool visitDefFun(LDefFun *lir);
     bool visitOsrEntry(LOsrEntry *lir);
     bool visitOsrScopeChain(LOsrScopeChain *lir);
+    bool visitOsrArgumentsObject(LOsrArgumentsObject *lir);
     bool visitStackArgT(LStackArgT *lir);
     bool visitStackArgV(LStackArgV *lir);
     bool visitMoveGroup(LMoveGroup *group);
     bool visitValueToInt32(LValueToInt32 *lir);
     bool visitValueToDouble(LValueToDouble *lir);
     bool visitValueToFloat32(LValueToFloat32 *lir);
     bool visitFloat32ToDouble(LFloat32ToDouble *lir);
     bool visitDoubleToFloat32(LDoubleToFloat32 *lir);
--- a/js/src/jit/Ion.cpp
+++ b/js/src/jit/Ion.cpp
@@ -1698,22 +1698,16 @@ CheckScript(JSContext *cx, JSScript *scr
         return false;
     }
 
     if (!script->analyzedArgsUsage() && !script->ensureRanAnalysis(cx)) {
         IonSpew(IonSpew_Abort, "OOM under ensureRanAnalysis");
         return false;
     }
 
-    if (osr && script->needsArgsObj()) {
-        // OSR-ing into functions with arguments objects is not supported.
-        IonSpew(IonSpew_Abort, "OSR script has argsobj");
-        return false;
-    }
-
     if (!script->compileAndGo) {
         IonSpew(IonSpew_Abort, "not compile-and-go");
         return false;
     }
 
     return true;
 }
 
--- a/js/src/jit/IonBuilder.cpp
+++ b/js/src/jit/IonBuilder.cpp
@@ -18,16 +18,18 @@
 #include "jit/BaselineInspector.h"
 #include "jit/ExecutionModeInlines.h"
 #include "jit/Ion.h"
 #include "jit/IonAnalysis.h"
 #include "jit/IonSpewer.h"
 #include "jit/Lowering.h"
 #include "jit/MIRGraph.h"
 
+#include "vm/ArgumentsObject.h"
+
 #include "jsinferinlines.h"
 #include "jsobjinlines.h"
 #include "jsscriptinlines.h"
 
 #include "jit/CompileInfo-inl.h"
 
 using namespace js;
 using namespace js::jit;
@@ -1028,17 +1030,17 @@ IonBuilder::maybeAddOsrTypeBarriers()
     for (uint32_t i = info().startArgSlot(); i < osrBlock->stackDepth(); i++, headerPhi++) {
 
         // Aliased slots are never accessed, since they need to go through
         // the callobject. The typebarriers are added there and can be
         // discared here.
         if (info().isSlotAliased(i))
             continue;
 
-        MInstruction *def = osrBlock->getSlot(i)->toOsrValue();
+        MInstruction *def = osrBlock->getSlot(i)->toInstruction();
 
         JS_ASSERT(headerPhi->slot() == i);
         MPhi *preheaderPhi = preheader->getSlot(i)->toPhi();
 
         MIRType type = headerPhi->type();
         types::TemporaryTypeSet *typeSet = headerPhi->resultTypeSet();
 
         if (!addOsrValueTypeBarrier(i, &def, type, typeSet))
@@ -5749,44 +5751,63 @@ IonBuilder::newOsrPreheader(MBasicBlock 
             // slot.
             scopev = MConstant::New(UndefinedValue());
         }
 
         osrBlock->add(scopev);
         osrBlock->initSlot(slot, scopev);
     }
 
-    // Initialize arguments object.  Ion will not allow OSR-ing into scripts
-    // with |needsArgsObj| set, so this can be undefined.
-    JS_ASSERT(!info().needsArgsObj());
+    // Initialize arguments object.
+    bool needsArgsObj = info().needsArgsObj();
+    MInstruction *argsObj = NULL;
     if (info().hasArguments()) {
-        MInstruction *argsObj = MConstant::New(UndefinedValue());
+        if (needsArgsObj)
+            argsObj = MOsrArgumentsObject::New(entry);
+        else
+            argsObj = MConstant::New(UndefinedValue());
         osrBlock->add(argsObj);
         osrBlock->initSlot(info().argsObjSlot(), argsObj);
     }
 
     if (info().fun()) {
         // Initialize |this| parameter.
         uint32_t slot = info().thisSlot();
         ptrdiff_t offset = StackFrame::offsetOfThis(info().fun());
 
         MOsrValue *thisv = MOsrValue::New(entry, offset);
         osrBlock->add(thisv);
         osrBlock->initSlot(slot, thisv);
 
         // Initialize arguments.
         for (uint32_t i = 0; i < info().nargs(); i++) {
-            // NB: Ion does not OSR into any function which |needsArgsObj|, so
-            // using argSlot() here instead of argSlotUnchecked() is ok.
-            uint32_t slot = info().argSlot(i);
-            ptrdiff_t offset = StackFrame::offsetOfFormalArg(info().fun(), i);
-
-            MOsrValue *osrv = MOsrValue::New(entry, offset);
-            osrBlock->add(osrv);
-            osrBlock->initSlot(slot, osrv);
+            uint32_t slot = needsArgsObj ? info().argSlotUnchecked(i) : info().argSlot(i);
+
+            if (needsArgsObj) {
+                JS_ASSERT(argsObj && argsObj->isOsrArgumentsObject());
+                // If this is an aliased formal, then the arguments object
+                // contains a hole at this index.  Any references to this
+                // variable in the jitcode will come from JSOP_*ALIASEDVAR
+                // opcodes, so the slot itself can be set to undefined.  If
+                // it's not aliased, it must be retrieved from the arguments
+                // object.
+                MInstruction *osrv;
+                if (script()->formalIsAliased(i))
+                    osrv = MConstant::New(UndefinedValue());
+                else
+                    osrv = MGetArgumentsObjectArg::New(argsObj, i);
+
+                osrBlock->add(osrv);
+                osrBlock->initSlot(slot, osrv);
+            } else {
+                ptrdiff_t offset = StackFrame::offsetOfFormalArg(info().fun(), i);
+                MOsrValue *osrv = MOsrValue::New(entry, offset);
+                osrBlock->add(osrv);
+                osrBlock->initSlot(slot, osrv);
+            }
         }
     }
 
     // Initialize locals.
     for (uint32_t i = 0; i < info().nlocals(); i++) {
         uint32_t slot = info().localSlot(i);
         ptrdiff_t offset = StackFrame::offsetOfFixed(i);
 
@@ -5829,17 +5850,17 @@ IonBuilder::newOsrPreheader(MBasicBlock 
 
     // Treat the OSR values as having the same type as the existing values
     // coming in to the loop. These will be fixed up with appropriate
     // unboxing and type barriers in finishLoop, once the possible types
     // at the loop header are known.
     for (uint32_t i = info().startArgSlot(); i < osrBlock->stackDepth(); i++) {
         MDefinition *existing = current->getSlot(i);
         MDefinition *def = osrBlock->getSlot(i);
-        JS_ASSERT(def->type() == MIRType_Value);
+        JS_ASSERT_IF(!needsArgsObj || !info().isSlotAliased(i), def->type() == MIRType_Value);
 
         // Aliased slots are never accessed, since they need to go through
         // the callobject. No need to type them here.
         if (info().isSlotAliased(i))
             continue;
 
         def->setResultType(existing->type());
         def->setResultTypeSet(existing->resultTypeSet());
@@ -5871,38 +5892,42 @@ IonBuilder::newPendingLoopHeader(MBasicB
         // header. The OSR frame may have unexpected types due to type changes
         // within the loop body or due to incomplete profiling information,
         // in which case this may avoid restarts of loop analysis or bailouts
         // during the OSR itself.
 
         // Unbox the MOsrValue if it is known to be unboxable.
         for (uint32_t i = info().startArgSlot(); i < block->stackDepth(); i++) {
 
-            // The value of aliased slots are in the callobject. So we can't
+            // The value of aliased args and slots are in the callobject. So we can't
             // the value from the baseline frame.
             if (info().isSlotAliased(i))
                 continue;
 
             // Don't bother with expression stack values. The stack should be
             // empty except for let variables (not Ion-compiled) or iterators.
             if (i >= info().firstStackSlot())
                 continue;
 
             MPhi *phi = block->getSlot(i)->toPhi();
 
             // Get the value from the baseline frame.
             Value existingValue;
             uint32_t arg = i - info().firstArgSlot();
             uint32_t var = i - info().firstLocalSlot();
-            if (info().fun() && i == info().thisSlot())
+            if (info().fun() && i == info().thisSlot()) {
                 existingValue = baselineFrame_->thisValue();
-            else if (arg < info().nargs())
-                existingValue = baselineFrame_->unaliasedFormal(arg);
-            else
+            } else if (arg < info().nargs()) {
+                if (info().needsArgsObj())
+                    existingValue = baselineFrame_->argsObj().arg(arg);
+                else
+                    existingValue = baselineFrame_->unaliasedFormal(arg);
+            } else {
                 existingValue = baselineFrame_->unaliasedVar(var);
+            }
 
             // Extract typeset from value.
             MIRType type = existingValue.isDouble()
                          ? MIRType_Double
                          : MIRTypeFromValueType(existingValue.extractNonDoubleType());
             types::Type ntype = types::GetValueType(existingValue);
             types::TemporaryTypeSet *typeSet =
                 GetIonContext()->temp->lifoAlloc()->new_<types::TemporaryTypeSet>(ntype);
--- a/js/src/jit/IonLinker.h
+++ b/js/src/jit/IonLinker.h
@@ -27,16 +27,18 @@ class Linker
         js_ReportOutOfMemory(cx);
         return NULL;
     }
 
     IonCode *newCode(JSContext *cx, JSC::ExecutableAllocator *execAlloc, JSC::CodeKind kind) {
         JS_ASSERT(kind == JSC::ION_CODE ||
                   kind == JSC::BASELINE_CODE ||
                   kind == JSC::OTHER_CODE);
+        JS_ASSERT(masm.numAsmJSAbsoluteLinks() == 0);
+
         gc::AutoSuppressGC suppressGC(cx);
         if (masm.oom())
             return fail(cx);
 
         JSC::ExecutablePool *pool;
         size_t bytesNeeded = masm.bytesNeeded() + sizeof(IonCode *) + CodeAlignment;
         if (bytesNeeded >= MAX_BUFFER_SIZE)
             return fail(cx);
--- a/js/src/jit/LIR-Common.h
+++ b/js/src/jit/LIR-Common.h
@@ -2796,16 +2796,32 @@ class LOsrScopeChain : public LInstructi
         setOperand(0, entry);
     }
 
     const MOsrScopeChain *mir() {
         return mir_->toOsrScopeChain();
     }
 };
 
+// Materialize a JSObject ArgumentsObject stored in an interpreter frame for OSR.
+class LOsrArgumentsObject : public LInstructionHelper<1, 1, 0>
+{
+  public:
+    LIR_HEADER(OsrArgumentsObject)
+
+    LOsrArgumentsObject(const LAllocation &entry)
+    {
+        setOperand(0, entry);
+    }
+
+    const MOsrArgumentsObject *mir() {
+        return mir_->toOsrArgumentsObject();
+    }
+};
+
 class LRegExp : public LCallInstructionHelper<1, 0, 0>
 {
   public:
     LIR_HEADER(RegExp)
 
     const MRegExp *mir() const {
         return mir_->toRegExp();
     }
--- a/js/src/jit/LOpcodes.h
+++ b/js/src/jit/LOpcodes.h
@@ -129,16 +129,17 @@
     _(DoubleToInt32)                \
     _(TruncateDToInt32)             \
     _(IntToString)                  \
     _(DoubleToString)               \
     _(Start)                        \
     _(OsrEntry)                     \
     _(OsrValue)                     \
     _(OsrScopeChain)                \
+    _(OsrArgumentsObject)           \
     _(RegExp)                       \
     _(RegExpTest)                   \
     _(Lambda)                       \
     _(LambdaForSingleton)           \
     _(LambdaPar)                    \
     _(ImplicitThis)                 \
     _(Slots)                        \
     _(Elements)                     \
--- a/js/src/jit/Lowering.cpp
+++ b/js/src/jit/Lowering.cpp
@@ -507,17 +507,17 @@ LIRGenerator::visitBail(MBail *bail)
     LBail *lir = new LBail();
     return assignSnapshot(lir) && add(lir, bail);
 }
 
 bool
 LIRGenerator::visitAssertFloat32(MAssertFloat32 *assertion)
 {
     MIRType type = assertion->input()->type();
-    bool checkIsFloat32 = assertion->mustBeFloat32();
+    DebugOnly<bool> checkIsFloat32 = assertion->mustBeFloat32();
 
     if (!allowFloat32Optimizations())
         return true;
 
     if (type != MIRType_Value && !js_IonOptions.eagerCompilation) {
         JS_ASSERT_IF(checkIsFloat32, type == MIRType_Float32);
         JS_ASSERT_IF(!checkIsFloat32, type != MIRType_Float32);
     }
@@ -1542,16 +1542,23 @@ LIRGenerator::visitOsrValue(MOsrValue *v
 bool
 LIRGenerator::visitOsrScopeChain(MOsrScopeChain *object)
 {
     LOsrScopeChain *lir = new LOsrScopeChain(useRegister(object->entry()));
     return define(lir, object);
 }
 
 bool
+LIRGenerator::visitOsrArgumentsObject(MOsrArgumentsObject *object)
+{
+    LOsrArgumentsObject *lir = new LOsrArgumentsObject(useRegister(object->entry()));
+    return define(lir, object);
+}
+
+bool
 LIRGenerator::visitToDouble(MToDouble *convert)
 {
     MDefinition *opd = convert->input();
     mozilla::DebugOnly<MToDouble::ConversionKind> conversion = convert->conversion();
 
     switch (opd->type()) {
       case MIRType_Value:
       {
@@ -1967,17 +1974,17 @@ LIRGenerator::visitTypeBarrier(MTypeBarr
 {
     // Requesting a non-GC pointer is safe here since we never re-enter C++
     // from inside a type barrier test.
 
     const types::TemporaryTypeSet *types = ins->resultTypeSet();
     bool needTemp = !types->unknownObject() && types->getObjectCount() > 0;
 
     MIRType inputType = ins->getOperand(0)->type();
-    MIRType outputType = ins->type();
+    DebugOnly<MIRType> outputType = ins->type();
 
     JS_ASSERT(inputType == outputType);
 
     // Handle typebarrier that will always bail.
     // (Emit LBail for visibility).
     if (ins->alwaysBails()) {
         LBail *bail = new LBail();
         if (!assignSnapshot(bail, ins->bailoutKind()))
@@ -2460,17 +2467,17 @@ LIRGenerator::visitLoadTypedArrayElement
 
 bool
 LIRGenerator::visitStoreTypedArrayElement(MStoreTypedArrayElement *ins)
 {
     JS_ASSERT(ins->elements()->type() == MIRType_Elements);
     JS_ASSERT(ins->index()->type() == MIRType_Int32);
 
     if (ins->isFloatArray()) {
-        bool optimizeFloat32 = allowFloat32Optimizations();
+        DebugOnly<bool> optimizeFloat32 = allowFloat32Optimizations();
         JS_ASSERT_IF(optimizeFloat32 && ins->arrayType() == ScalarTypeRepresentation::TYPE_FLOAT32,
                      ins->value()->type() == MIRType_Float32);
         JS_ASSERT_IF(!optimizeFloat32 || ins->arrayType() == ScalarTypeRepresentation::TYPE_FLOAT64,
                      ins->value()->type() == MIRType_Double);
     } else {
         JS_ASSERT(ins->value()->type() == MIRType_Int32);
     }
 
@@ -2489,17 +2496,17 @@ LIRGenerator::visitStoreTypedArrayElemen
 bool
 LIRGenerator::visitStoreTypedArrayElementHole(MStoreTypedArrayElementHole *ins)
 {
     JS_ASSERT(ins->elements()->type() == MIRType_Elements);
     JS_ASSERT(ins->index()->type() == MIRType_Int32);
     JS_ASSERT(ins->length()->type() == MIRType_Int32);
 
     if (ins->isFloatArray()) {
-        bool optimizeFloat32 = allowFloat32Optimizations();
+        DebugOnly<bool> optimizeFloat32 = allowFloat32Optimizations();
         JS_ASSERT_IF(optimizeFloat32 && ins->arrayType() == ScalarTypeRepresentation::TYPE_FLOAT32,
                      ins->value()->type() == MIRType_Float32);
         JS_ASSERT_IF(!optimizeFloat32 || ins->arrayType() == ScalarTypeRepresentation::TYPE_FLOAT64,
                      ins->value()->type() == MIRType_Double);
     } else {
         JS_ASSERT(ins->value()->type() == MIRType_Int32);
     }
 
--- a/js/src/jit/Lowering.h
+++ b/js/src/jit/Lowering.h
@@ -150,16 +150,17 @@ class LIRGenerator : public LIRGenerator
     bool visitConcatPar(MConcatPar *ins);
     bool visitCharCodeAt(MCharCodeAt *ins);
     bool visitFromCharCode(MFromCharCode *ins);
     bool visitStart(MStart *start);
     bool visitOsrEntry(MOsrEntry *entry);
     bool visitNop(MNop *nop);
     bool visitOsrValue(MOsrValue *value);
     bool visitOsrScopeChain(MOsrScopeChain *object);
+    bool visitOsrArgumentsObject(MOsrArgumentsObject *object);
     bool visitToDouble(MToDouble *convert);
     bool visitToFloat32(MToFloat32 *convert);
     bool visitToInt32(MToInt32 *convert);
     bool visitTruncateToInt32(MTruncateToInt32 *truncate);
     bool visitToString(MToString *convert);
     bool visitRegExp(MRegExp *ins);
     bool visitRegExpTest(MRegExpTest *ins);
     bool visitLambda(MLambda *ins);
--- a/js/src/jit/MIR.h
+++ b/js/src/jit/MIR.h
@@ -4281,16 +4281,38 @@ class MOsrScopeChain : public MUnaryInst
         return new MOsrScopeChain(entry);
     }
 
     MOsrEntry *entry() {
         return getOperand(0)->toOsrEntry();
     }
 };
 
+// MIR representation of a JSObject ArgumentsObject pointer on the OSR StackFrame.
+// The pointer is indexed off of OsrFrameReg.
+class MOsrArgumentsObject : public MUnaryInstruction
+{
+  private:
+    MOsrArgumentsObject(MOsrEntry *entry)
+      : MUnaryInstruction(entry)
+    {
+        setResultType(MIRType_Object);
+    }
+
+  public:
+    INSTRUCTION_HEADER(OsrArgumentsObject)
+    static MOsrArgumentsObject *New(MOsrEntry *entry) {
+        return new MOsrArgumentsObject(entry);
+    }
+
+    MOsrEntry *entry() {
+        return getOperand(0)->toOsrEntry();
+    }
+};
+
</