Merge last PGO-green changeset of mozilla-inbound to mozilla-central
authorEd Morley <emorley@mozilla.com>
Fri, 08 Jun 2012 11:23:53 +0100
changeset 100949 22bb7d46bb23aa7a63f626eac8b0a62d46b4eec3
parent 100855 a807b20be0bf0452eba439aa0d83215a14d61913 (current diff)
parent 100948 13ef4ab18b45c68aefe7a1feadf5b11b7b924076 (diff)
child 100967 b8ed7040597f91295d93d933c41dddb44ae2a05e
push id1316
push userakeybl@mozilla.com
push dateMon, 27 Aug 2012 22:37:00 +0000
treeherdermozilla-beta@db4b09302ee2 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone16.0a1
first release with
nightly linux32
22bb7d46bb23 / 16.0a1 / 20120608081921 / files
nightly linux64
22bb7d46bb23 / 16.0a1 / 20120608081921 / files
nightly mac
22bb7d46bb23 / 16.0a1 / 20120608081921 / files
nightly win32
22bb7d46bb23 / 16.0a1 / 20120608081921 / files
nightly win64
22bb7d46bb23 / 16.0a1 / 20120608081921 / files
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
releases
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Merge last PGO-green changeset of mozilla-inbound to mozilla-central
accessible/src/atk/nsHTMLTableAccessibleWrap.h
accessible/src/html/nsHTMLTableAccessible.cpp
accessible/src/html/nsHTMLTableAccessible.h
accessible/src/mac/nsHTMLTableAccessibleWrap.h
accessible/src/msaa/nsHTMLTableAccessibleWrap.cpp
accessible/src/msaa/nsHTMLTableAccessibleWrap.h
accessible/src/other/nsHTMLTableAccessibleWrap.h
dom/base/BrowserElementChild.js
dom/base/BrowserElementParent.js
dom/base/BrowserElementParent.manifest
dom/tests/mochitest/browser-frame/Makefile.in
dom/tests/mochitest/browser-frame/browserFrameHelpers.js
dom/tests/mochitest/browser-frame/file_empty.html
dom/tests/mochitest/browser-frame/file_focus.html
dom/tests/mochitest/browser-frame/test_browserFrame1.html
dom/tests/mochitest/browser-frame/test_browserFrame10.html
dom/tests/mochitest/browser-frame/test_browserFrame2.html
dom/tests/mochitest/browser-frame/test_browserFrame3.html
dom/tests/mochitest/browser-frame/test_browserFrame4.html
dom/tests/mochitest/browser-frame/test_browserFrame5.html
dom/tests/mochitest/browser-frame/test_browserFrame6.html
dom/tests/mochitest/browser-frame/test_browserFrame7.html
dom/tests/mochitest/browser-frame/test_browserFrame8.html
dom/tests/mochitest/browser-frame/test_browserFrame9.html
dom/tests/mochitest/browser-frame/test_browserFrame_keyEvents.html
js/src/jit-test/tests/arguments/e4x-descendants-with-arguments.js
js/src/jit-test/tests/basic/bug557168-1.js
js/src/jit-test/tests/basic/bug557168-2.js
js/src/jit-test/tests/basic/bug557168-3.js
js/src/jit-test/tests/basic/bug557168.js
js/src/jit-test/tests/basic/bug569843.js
js/src/jit-test/tests/basic/bug574280.js
js/src/jit-test/tests/basic/bug596502-version.js
js/src/jit-test/tests/basic/bug605200.js
js/src/jit-test/tests/basic/bug613151.js
js/src/jit-test/tests/basic/bug632206.js
js/src/jit-test/tests/basic/bug651966.js
js/src/jit-test/tests/basic/bug665812.js
js/src/jit-test/tests/basic/bug672153.js
js/src/jit-test/tests/basic/bug700799.js
js/src/jit-test/tests/basic/bug716713.js
js/src/jit-test/tests/basic/bug731724.js
js/src/jit-test/tests/basic/bug731745.js
js/src/jit-test/tests/basic/bug737251.js
js/src/jit-test/tests/basic/bug753885-1.js
js/src/jit-test/tests/basic/bug753885-2.js
js/src/jit-test/tests/basic/testXMLPropertyNames.js
mobile/android/base/GeckoActionBar.java
mobile/android/base/resources/drawable-hdpi/address_bar_pressed_texture_port.png
mobile/android/base/resources/drawable-hdpi/tab_selected.png
mobile/android/base/resources/drawable-hdpi/tabs_more.png
mobile/android/base/resources/drawable-hdpi/tabs_plus.png
mobile/android/base/resources/drawable-land-hdpi-v14/address_bar_pressed_texture_land.png
mobile/android/base/resources/drawable-land-hdpi-v14/tabs_more.png
mobile/android/base/resources/drawable-land-hdpi-v14/tabs_plus.png
mobile/android/base/resources/drawable-land-mdpi-v14/address_bar_pressed_texture_land.png
mobile/android/base/resources/drawable-land-mdpi-v14/tabs_more.png
mobile/android/base/resources/drawable-land-mdpi-v14/tabs_plus.png
mobile/android/base/resources/drawable-land-v14/address_bar_pressed_bg.xml
mobile/android/base/resources/drawable-land-xhdpi-v14/address_bar_pressed_texture_land.png
mobile/android/base/resources/drawable-land-xhdpi-v14/tabs_more.png
mobile/android/base/resources/drawable-land-xhdpi-v14/tabs_plus.png
mobile/android/base/resources/drawable-sw600dp-hdpi/address_bar_pressed_texture_tablet.png
mobile/android/base/resources/drawable-sw600dp-hdpi/tabs_more.png
mobile/android/base/resources/drawable-sw600dp-hdpi/tabs_plus.png
mobile/android/base/resources/drawable-sw600dp-mdpi/address_bar_pressed_texture_tablet.png
mobile/android/base/resources/drawable-sw600dp-mdpi/tabs_more.png
mobile/android/base/resources/drawable-sw600dp-mdpi/tabs_plus.png
mobile/android/base/resources/drawable-sw600dp-xhdpi/address_bar_pressed_texture_tablet.png
mobile/android/base/resources/drawable-sw600dp-xhdpi/tabs_more.png
mobile/android/base/resources/drawable-sw600dp-xhdpi/tabs_plus.png
mobile/android/base/resources/drawable-xhdpi-v11/address_bar_pressed_texture_port.png
mobile/android/base/resources/drawable-xhdpi-v11/tab_selected.png
mobile/android/base/resources/drawable-xhdpi-v11/tabs_more.png
mobile/android/base/resources/drawable-xhdpi-v11/tabs_plus.png
mobile/android/base/resources/drawable-xlarge-hdpi/address_bar_pressed_texture_tablet.png
mobile/android/base/resources/drawable-xlarge-hdpi/tabs_more.png
mobile/android/base/resources/drawable-xlarge-hdpi/tabs_plus.png
mobile/android/base/resources/drawable-xlarge-mdpi/address_bar_pressed_bg.xml
mobile/android/base/resources/drawable-xlarge-mdpi/address_bar_pressed_texture_tablet.png
mobile/android/base/resources/drawable-xlarge-mdpi/tabs_more.png
mobile/android/base/resources/drawable-xlarge-mdpi/tabs_plus.png
mobile/android/base/resources/drawable-xlarge-xhdpi/address_bar_pressed_texture_tablet.png
mobile/android/base/resources/drawable-xlarge-xhdpi/tabs_more.png
mobile/android/base/resources/drawable-xlarge-xhdpi/tabs_plus.png
mobile/android/base/resources/drawable/address_bar_pressed_bg.xml
mobile/android/base/resources/drawable/address_bar_pressed_texture_port.png
mobile/android/base/resources/drawable/remote_tabs_group_bg_repeat.xml
mobile/android/base/resources/drawable/tab_selected.png
mobile/android/base/resources/drawable/tabs_more.png
mobile/android/base/resources/drawable/tabs_plus.png
mobile/android/base/resources/drawable/tabs_tray_list_selector.xml
mobile/android/base/resources/layout-v11/gecko_app.xml
rename from accessible/src/atk/nsHTMLTableAccessibleWrap.h
rename to accessible/src/atk/HTMLTableAccessibleWrap.h
--- a/accessible/src/atk/nsHTMLTableAccessibleWrap.h
+++ b/accessible/src/atk/HTMLTableAccessibleWrap.h
@@ -1,17 +1,23 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set ts=2 et sw=2 tw=80: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-#ifndef _NSHTMLTABLEACCESSIBLEWRAP_H
-#define _NSHTMLTABLEACCESSIBLEWRAP_H
+#ifndef mozilla_a11y_HTMLTableAccessibleWrap_h__
+#define mozilla_a11y_HTMLTableAccessibleWrap_h__
+
+#include "HTMLTableAccessible.h"
 
-#include "nsHTMLTableAccessible.h"
+namespace mozilla {
+namespace a11y {
 
-typedef class nsHTMLTableAccessible nsHTMLTableAccessibleWrap;
-typedef class nsHTMLTableCellAccessible nsHTMLTableCellAccessibleWrap;
-typedef class nsHTMLTableHeaderCellAccessible nsHTMLTableHeaderCellAccessibleWrap;
+typedef class HTMLTableAccessible HTMLTableAccessibleWrap;
+typedef class HTMLTableCellAccessible HTMLTableCellAccessibleWrap;
+typedef class HTMLTableHeaderCellAccessible HTMLTableHeaderCellAccessibleWrap;
+
+} // namespace a11y
+} // namespace mozilla
 
 #endif
 
--- a/accessible/src/base/TextAttrs.cpp
+++ b/accessible/src/base/TextAttrs.cpp
@@ -96,31 +96,35 @@ TextAttrsMgr::GetAttributes(nsIPersisten
   FontSizeTextAttr fontSizeTextAttr(rootFrame, frame);
 
   // "font-style" text attribute
   FontStyleTextAttr fontStyleTextAttr(rootFrame, frame);
 
   // "font-weight" text attribute
   FontWeightTextAttr fontWeightTextAttr(rootFrame, frame);
 
+  // "auto-generated" text attribute
+  AutoGeneratedTextAttr autoGenTextAttr(mHyperTextAcc, mOffsetAcc);
+
   // "text-underline(line-through)-style(color)" text attributes
   TextDecorTextAttr textDecorTextAttr(rootFrame, frame);
 
   // "text-position" text attribute
   TextPosTextAttr textPosTextAttr(rootFrame, frame);
 
   TextAttr* attrArray[] =
   {
     &langTextAttr,
     &bgColorTextAttr,
     &colorTextAttr,
     &fontFamilyTextAttr,
     &fontSizeTextAttr,
     &fontStyleTextAttr,
     &fontWeightTextAttr,
+    &autoGenTextAttr,
     &textDecorTextAttr,
     &textPosTextAttr
   };
 
   // Expose text attributes if applicable.
   if (aAttributes) {
     for (PRUint32 idx = 0; idx < ArrayLength(attrArray); idx++)
       attrArray[idx]->Expose(aAttributes, mIncludeDefAttrs);
@@ -139,24 +143,20 @@ TextAttrsMgr::GetRange(TextAttr* aAttrAr
   for (PRInt32 childIdx = mOffsetAccIdx - 1; childIdx >= 0; childIdx--) {
     Accessible* currAcc = mHyperTextAcc->GetChildAt(childIdx);
 
     // Stop on embedded accessible since embedded accessibles are combined into
     // own range.
     if (nsAccUtils::IsEmbeddedObject(currAcc))
       break;
 
-    nsIContent* currElm = nsCoreUtils::GetDOMElementFor(currAcc->GetContent());
-    if (!currElm)
-      return;
-
     bool offsetFound = false;
     for (PRUint32 attrIdx = 0; attrIdx < aAttrArrayLen; attrIdx++) {
       TextAttr* textAttr = aAttrArray[attrIdx];
-      if (!textAttr->Equal(currElm)) {
+      if (!textAttr->Equal(currAcc)) {
         offsetFound = true;
         break;
       }
     }
 
     if (offsetFound)
       break;
 
@@ -165,27 +165,23 @@ TextAttrsMgr::GetRange(TextAttr* aAttrAr
 
   // Navigate forward from anchor accessible to find end offset.
   PRUint32 childLen = mHyperTextAcc->ChildCount();
   for (PRUint32 childIdx = mOffsetAccIdx + 1; childIdx < childLen; childIdx++) {
     Accessible* currAcc = mHyperTextAcc->GetChildAt(childIdx);
     if (nsAccUtils::IsEmbeddedObject(currAcc))
       break;
 
-    nsIContent* currElm = nsCoreUtils::GetDOMElementFor(currAcc->GetContent());
-    if (!currElm)
-      return;
-
     bool offsetFound = false;
     for (PRUint32 attrIdx = 0; attrIdx < aAttrArrayLen; attrIdx++) {
       TextAttr* textAttr = aAttrArray[attrIdx];
 
       // Alter the end offset when text attribute changes its value and stop
       // the search.
-      if (!textAttr->Equal(currElm)) {
+      if (!textAttr->Equal(currAcc)) {
         offsetFound = true;
         break;
       }
     }
 
     if (offsetFound)
       break;
 
@@ -201,61 +197,57 @@ TextAttrsMgr::GetRange(TextAttr* aAttrAr
 TextAttrsMgr::LangTextAttr::
   LangTextAttr(HyperTextAccessible* aRoot,
                nsIContent* aRootElm, nsIContent* aElm) :
   TTextAttr<nsString>(!aElm), mRootContent(aRootElm)
 {
   aRoot->Language(mRootNativeValue);
   mIsRootDefined =  !mRootNativeValue.IsEmpty();
 
-  if (aElm)
-    mIsDefined = GetLang(aElm, mNativeValue);
+  if (aElm) {
+    nsCoreUtils::GetLanguageFor(aElm, mRootContent, mNativeValue);
+    mIsDefined = !mNativeValue.IsEmpty();
+  }
 }
 
 bool
 TextAttrsMgr::LangTextAttr::
-  GetValueFor(nsIContent* aElm, nsString* aValue)
+  GetValueFor(Accessible* aAccessible, nsString* aValue)
 {
-  return GetLang(aElm, *aValue);
+  nsCoreUtils::GetLanguageFor(aAccessible->GetContent(), mRootContent, *aValue);
+  return !aValue->IsEmpty();
 }
 
 void
 TextAttrsMgr::LangTextAttr::
   ExposeValue(nsIPersistentProperties* aAttributes, const nsString& aValue)
 {
   nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::language, aValue);
 }
 
-bool
-TextAttrsMgr::LangTextAttr::
-  GetLang(nsIContent* aElm, nsAString& aLang)
-{
-  nsCoreUtils::GetLanguageFor(aElm, mRootContent, aLang);
-  return !aLang.IsEmpty();
-}
-
 
 ////////////////////////////////////////////////////////////////////////////////
 // BGColorTextAttr
 ////////////////////////////////////////////////////////////////////////////////
 
 TextAttrsMgr::BGColorTextAttr::
   BGColorTextAttr(nsIFrame* aRootFrame, nsIFrame* aFrame) :
   TTextAttr<nscolor>(!aFrame), mRootFrame(aRootFrame)
 {
   mIsRootDefined = GetColor(mRootFrame, &mRootNativeValue);
   if (aFrame)
     mIsDefined = GetColor(aFrame, &mNativeValue);
 }
 
 bool
 TextAttrsMgr::BGColorTextAttr::
-  GetValueFor(nsIContent* aElm, nscolor* aValue)
+  GetValueFor(Accessible* aAccessible, nscolor* aValue)
 {
-  nsIFrame* frame = aElm->GetPrimaryFrame();
+  nsIContent* elm = nsCoreUtils::GetDOMElementFor(aAccessible->GetContent());
+  nsIFrame* frame = elm->GetPrimaryFrame();
   return frame ? GetColor(frame, aValue) : false;
 }
 
 void
 TextAttrsMgr::BGColorTextAttr::
   ExposeValue(nsIPersistentProperties* aAttributes, const nscolor& aValue)
 {
   nsAutoString formattedValue;
@@ -305,19 +297,20 @@ TextAttrsMgr::ColorTextAttr::
   if (aFrame) {
     mNativeValue = aFrame->GetStyleColor()->mColor;
     mIsDefined = true;
   }
 }
 
 bool
 TextAttrsMgr::ColorTextAttr::
-  GetValueFor(nsIContent* aElm, nscolor* aValue)
+  GetValueFor(Accessible* aAccessible, nscolor* aValue)
 {
-  nsIFrame* frame = aElm->GetPrimaryFrame();
+  nsIContent* elm = nsCoreUtils::GetDOMElementFor(aAccessible->GetContent());
+  nsIFrame* frame = elm->GetPrimaryFrame();
   if (frame) {
     *aValue = frame->GetStyleColor()->mColor;
     return true;
   }
 
   return false;
 }
 
@@ -342,19 +335,20 @@ TextAttrsMgr::FontFamilyTextAttr::
   mIsRootDefined = GetFontFamily(aRootFrame, mRootNativeValue);
 
   if (aFrame)
     mIsDefined = GetFontFamily(aFrame, mNativeValue);
 }
 
 bool
 TextAttrsMgr::FontFamilyTextAttr::
-  GetValueFor(nsIContent* aElm, nsString* aValue)
+  GetValueFor(Accessible* aAccessible, nsString* aValue)
 {
-  nsIFrame* frame = aElm->GetPrimaryFrame();
+  nsIContent* elm = nsCoreUtils::GetDOMElementFor(aAccessible->GetContent());
+  nsIFrame* frame = elm->GetPrimaryFrame();
   return frame ? GetFontFamily(frame, *aValue) : false;
 }
 
 void
 TextAttrsMgr::FontFamilyTextAttr::
   ExposeValue(nsIPersistentProperties* aAttributes, const nsString& aValue)
 {
   nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::font_family, aValue);
@@ -391,19 +385,20 @@ TextAttrsMgr::FontSizeTextAttr::
   if (aFrame) {
     mNativeValue = aFrame->GetStyleFont()->mSize;
     mIsDefined = true;
   }
 }
 
 bool
 TextAttrsMgr::FontSizeTextAttr::
-  GetValueFor(nsIContent* aElm, nscoord* aValue)
+  GetValueFor(Accessible* aAccessible, nscoord* aValue)
 {
-  nsIFrame* frame = aElm->GetPrimaryFrame();
+  nsIContent* content = nsCoreUtils::GetDOMElementFor(aAccessible->GetContent());
+  nsIFrame* frame = content->GetPrimaryFrame();
   if (frame) {
     *aValue = frame->GetStyleFont()->mSize;
     return true;
   }
 
   return false;
 }
 
@@ -446,19 +441,20 @@ TextAttrsMgr::FontStyleTextAttr::
   if (aFrame) {
     mNativeValue = aFrame->GetStyleFont()->mFont.style;
     mIsDefined = true;
   }
 }
 
 bool
 TextAttrsMgr::FontStyleTextAttr::
-  GetValueFor(nsIContent* aContent, nscoord* aValue)
+  GetValueFor(Accessible* aAccessible, nscoord* aValue)
 {
-  nsIFrame* frame = aContent->GetPrimaryFrame();
+  nsIContent* elm = nsCoreUtils::GetDOMElementFor(aAccessible->GetContent());
+  nsIFrame* frame = elm->GetPrimaryFrame();
   if (frame) {
     *aValue = frame->GetStyleFont()->mFont.style;
     return true;
   }
 
   return false;
 }
 
@@ -487,19 +483,20 @@ TextAttrsMgr::FontWeightTextAttr::
   if (aFrame) {
     mNativeValue = GetFontWeight(aFrame);
     mIsDefined = true;
   }
 }
 
 bool
 TextAttrsMgr::FontWeightTextAttr::
-  GetValueFor(nsIContent* aElm, PRInt32* aValue)
+  GetValueFor(Accessible* aAccessible, PRInt32* aValue)
 {
-  nsIFrame* frame = aElm->GetPrimaryFrame();
+  nsIContent* elm = nsCoreUtils::GetDOMElementFor(aAccessible->GetContent());
+  nsIFrame* frame = elm->GetPrimaryFrame();
   if (frame) {
     *aValue = GetFontWeight(frame);
     return true;
   }
 
   return false;
 }
 
@@ -545,16 +542,46 @@ TextAttrsMgr::FontWeightTextAttr::
   // On Mac, font->GetStyle()->weight will just give the same number as
   // getComputedStyle(). fontEntry->Weight() will give the weight of the font
   // face used.
   gfxFontEntry *fontEntry = font->GetFontEntry();
   return fontEntry->Weight();
 #endif
 }
 
+////////////////////////////////////////////////////////////////////////////////
+// AutoGeneratedTextAttr
+////////////////////////////////////////////////////////////////////////////////
+TextAttrsMgr::AutoGeneratedTextAttr::
+  AutoGeneratedTextAttr(HyperTextAccessible* aHyperTextAcc,
+                        Accessible* aAccessible) :
+  TTextAttr<bool>(!aAccessible)
+{
+  mRootNativeValue = false;
+  mIsRootDefined = false;
+
+  if (aAccessible)
+    mIsDefined = mNativeValue = (aAccessible->NativeRole() == roles::STATICTEXT);
+}
+
+bool
+TextAttrsMgr::AutoGeneratedTextAttr::
+  GetValueFor(Accessible* aAccessible, bool* aValue)
+{
+  return *aValue = (aAccessible->NativeRole() == roles::STATICTEXT);
+}
+
+void
+TextAttrsMgr::AutoGeneratedTextAttr::
+  ExposeValue(nsIPersistentProperties* aAttributes, const bool& aValue)
+{
+  nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::auto_generated,
+                         aValue ? NS_LITERAL_STRING("true") : NS_LITERAL_STRING("false"));
+}
+
 
 ////////////////////////////////////////////////////////////////////////////////
 // TextDecorTextAttr
 ////////////////////////////////////////////////////////////////////////////////
 
 TextAttrsMgr::TextDecorValue::
   TextDecorValue(nsIFrame* aFrame)
 {
@@ -581,19 +608,20 @@ TextAttrsMgr::TextDecorTextAttr::
   if (aFrame) {
     mNativeValue = TextDecorValue(aFrame);
     mIsDefined = mNativeValue.IsDefined();
   }
 }
 
 bool
 TextAttrsMgr::TextDecorTextAttr::
-  GetValueFor(nsIContent* aContent, TextDecorValue* aValue)
+  GetValueFor(Accessible* aAccessible, TextDecorValue* aValue)
 {
-  nsIFrame* frame = aContent->GetPrimaryFrame();
+  nsIContent* elm = nsCoreUtils::GetDOMElementFor(aAccessible->GetContent());
+  nsIFrame* frame = elm->GetPrimaryFrame();
   if (frame) {
     *aValue = TextDecorValue(frame);
     return aValue->IsDefined();
   }
 
   return false;
 }
 
@@ -643,19 +671,20 @@ TextAttrsMgr::TextPosTextAttr::
   if (aFrame) {
     mNativeValue = GetTextPosValue(aFrame);
     mIsDefined = mNativeValue != eTextPosNone;
   }
 }
 
 bool
 TextAttrsMgr::TextPosTextAttr::
-  GetValueFor(nsIContent* aContent, TextPosValue* aValue)
+  GetValueFor(Accessible* aAccessible, TextPosValue* aValue)
 {
-  nsIFrame* frame = aContent->GetPrimaryFrame();
+  nsIContent* elm = nsCoreUtils::GetDOMElementFor(aAccessible->GetContent());
+  nsIFrame* frame = elm->GetPrimaryFrame();
   if (frame) {
     *aValue = GetTextPosValue(frame);
     return *aValue != eTextPosNone;
   }
 
   return false;
 }
 
--- a/accessible/src/base/TextAttrs.h
+++ b/accessible/src/base/TextAttrs.h
@@ -105,17 +105,17 @@ protected:
      */
     virtual void Expose(nsIPersistentProperties* aAttributes,
                         bool aIncludeDefAttrValue) = 0;
 
     /**
      * Return true if the text attribute value on the given element equals with
      * predefined attribute value.
      */
-    virtual bool Equal(nsIContent* aElm) = 0;
+    virtual bool Equal(Accessible* aAccessible) = 0;
   };
 
 
   /**
    * Base class to work with text attributes. See derived classes below.
    */
   template<class T>
   class TTextAttr : public TextAttr
@@ -138,20 +138,20 @@ protected:
           ExposeValue(aAttributes, mNativeValue);
         return;
       }
 
       if (aIncludeDefAttrValue && mIsRootDefined)
         ExposeValue(aAttributes, mRootNativeValue);
     }
 
-    virtual bool Equal(nsIContent* aElm)
+    virtual bool Equal(Accessible* aAccessible)
     {
       T nativeValue;
-      bool isDefined = GetValueFor(aElm, &nativeValue);
+      bool isDefined = GetValueFor(aAccessible, &nativeValue);
 
       if (!mIsDefined && !isDefined)
         return true;
 
       if (mIsDefined && isDefined)
         return nativeValue == mNativeValue;
 
       if (mIsDefined)
@@ -162,17 +162,17 @@ protected:
 
   protected:
 
     // Expose the text attribute with the given value to attribute set.
     virtual void ExposeValue(nsIPersistentProperties* aAttributes,
                              const T& aValue) = 0;
 
     // Return native value for the given DOM element.
-    virtual bool GetValueFor(nsIContent* aElm, T* aValue) = 0;
+    virtual bool GetValueFor(Accessible* aAccessible, T* aValue) = 0;
 
     // Indicates if root value should be exposed.
     bool mGetRootValue;
 
     // Native value and flag indicating if the value is defined (initialized in
     // derived classes). Note, undefined native value means it is inherited
     // from root.
     T mNativeValue;
@@ -193,39 +193,38 @@ protected:
   public:
     LangTextAttr(HyperTextAccessible* aRoot, nsIContent* aRootElm,
                  nsIContent* aElm);
     virtual ~LangTextAttr() { }
 
   protected:
 
     // TextAttr
-    virtual bool GetValueFor(nsIContent* aElm, nsString* aValue);
+    virtual bool GetValueFor(Accessible* aAccessible, nsString* aValue);
     virtual void ExposeValue(nsIPersistentProperties* aAttributes,
                              const nsString& aValue);
 
   private:
-    bool GetLang(nsIContent* aElm, nsAString& aLang);
     nsCOMPtr<nsIContent> mRootContent;
   };
 
 
   /**
    * Class is used for the work with 'background-color' text attribute.
    */
   class BGColorTextAttr : public TTextAttr<nscolor>
   {
   public:
     BGColorTextAttr(nsIFrame* aRootFrame, nsIFrame* aFrame);
     virtual ~BGColorTextAttr() { }
 
   protected:
 
     // TextAttr
-    virtual bool GetValueFor(nsIContent* aElm, nscolor* aValue);
+    virtual bool GetValueFor(Accessible* aAccessible, nscolor* aValue);
     virtual void ExposeValue(nsIPersistentProperties* aAttributes,
                              const nscolor& aValue);
 
   private:
     bool GetColor(nsIFrame* aFrame, nscolor* aColor);
     nsIFrame* mRootFrame;
   };
 
@@ -237,17 +236,17 @@ protected:
   {
   public:
     ColorTextAttr(nsIFrame* aRootFrame, nsIFrame* aFrame);
     virtual ~ColorTextAttr() { }
 
   protected:
 
     // TTextAttr
-    virtual bool GetValueFor(nsIContent* aElm, nscolor* aValue);
+    virtual bool GetValueFor(Accessible* aAccessible, nscolor* aValue);
     virtual void ExposeValue(nsIPersistentProperties* aAttributes,
                              const nscolor& aValue);
   };
 
 
   /**
    * Class is used for the work with "font-family" text attribute.
    */
@@ -255,17 +254,17 @@ protected:
   {
   public:
     FontFamilyTextAttr(nsIFrame* aRootFrame, nsIFrame* aFrame);
     virtual ~FontFamilyTextAttr() { }
 
   protected:
 
     // TTextAttr
-    virtual bool GetValueFor(nsIContent* aElm, nsString* aValue);
+    virtual bool GetValueFor(Accessible* aAccessible, nsString* aValue);
     virtual void ExposeValue(nsIPersistentProperties* aAttributes,
                              const nsString& aValue);
 
   private:
 
     bool GetFontFamily(nsIFrame* aFrame, nsString& aFamily);
   };
 
@@ -274,20 +273,20 @@ protected:
    * Class is used for the work with "font-size" text attribute.
    */
   class FontSizeTextAttr : public TTextAttr<nscoord>
   {
   public:
     FontSizeTextAttr(nsIFrame* aRootFrame, nsIFrame* aFrame);
     virtual ~FontSizeTextAttr() { }
 
-  protected:
+  protected: 
 
     // TTextAttr
-    virtual bool GetValueFor(nsIContent* aElm, nscoord* aValue);
+    virtual bool GetValueFor(Accessible* aAccessible, nscoord* aValue);
     virtual void ExposeValue(nsIPersistentProperties* aAttributes,
                              const nscoord& aValue);
 
   private:
     nsDeviceContext* mDC;
   };
 
 
@@ -298,17 +297,17 @@ protected:
   {
   public:
     FontStyleTextAttr(nsIFrame* aRootFrame, nsIFrame* aFrame);
     virtual ~FontStyleTextAttr() { }
 
   protected:
 
     // TTextAttr
-    virtual bool GetValueFor(nsIContent* aContent, nscoord* aValue);
+    virtual bool GetValueFor(Accessible* aContent, nscoord* aValue);
     virtual void ExposeValue(nsIPersistentProperties* aAttributes,
                              const nscoord& aValue);
   };
 
 
   /**
    * Class is used for the work with "font-weight" text attribute.
    */
@@ -316,24 +315,41 @@ protected:
   {
   public:
     FontWeightTextAttr(nsIFrame* aRootFrame, nsIFrame* aFrame);
     virtual ~FontWeightTextAttr() { }
 
   protected:
 
     // TTextAttr
-    virtual bool GetValueFor(nsIContent* aElm, PRInt32* aValue);
+    virtual bool GetValueFor(Accessible* aAccessible, PRInt32* aValue);
     virtual void ExposeValue(nsIPersistentProperties* aAttributes,
                              const PRInt32& aValue);
 
   private:
     PRInt32 GetFontWeight(nsIFrame* aFrame);
   };
 
+  /**
+   * Class is used for the work with 'auto-generated' text attribute.
+   */
+  class AutoGeneratedTextAttr : public TTextAttr<bool>
+  {
+  public:
+    AutoGeneratedTextAttr(HyperTextAccessible* aHyperTextAcc,
+                          Accessible* aAccessible);
+    virtual ~AutoGeneratedTextAttr() { }
+
+  protected:
+    // TextAttr
+    virtual bool GetValueFor(Accessible* aAccessible, bool* aValue);
+    virtual void ExposeValue(nsIPersistentProperties* aAttributes,
+                             const bool& aValue);
+  };
+
 
   /**
    * TextDecorTextAttr class is used for the work with
    * "text-line-through-style", "text-line-through-color",
    * "text-underline-style" and "text-underline-color" text attributes.
    */
 
   class TextDecorValue
@@ -370,17 +386,17 @@ protected:
   {
   public:
     TextDecorTextAttr(nsIFrame* aRootFrame, nsIFrame* aFrame);
     virtual ~TextDecorTextAttr() { }
 
   protected:
 
     // TextAttr
-    virtual bool GetValueFor(nsIContent* aElm, TextDecorValue* aValue);
+    virtual bool GetValueFor(Accessible* aAccessible, TextDecorValue* aValue);
     virtual void ExposeValue(nsIPersistentProperties* aAttributes,
                              const TextDecorValue& aValue);
   };
 
   /**
    * Class is used for the work with "text-position" text attribute.
    */
 
@@ -395,17 +411,17 @@ protected:
   {
   public:
     TextPosTextAttr(nsIFrame* aRootFrame, nsIFrame* aFrame);
     virtual ~TextPosTextAttr() { }
 
   protected:
 
     // TextAttr
-    virtual bool GetValueFor(nsIContent* aElm, TextPosValue* aValue);
+    virtual bool GetValueFor(Accessible* aAccessible, TextPosValue* aValue);
     virtual void ExposeValue(nsIPersistentProperties* aAttributes,
                              const TextPosValue& aValue);
 
   private:
     TextPosValue GetTextPosValue(nsIFrame* aFrame) const;
   };
 
 }; // TextAttrMgr
--- a/accessible/src/base/nsARIAMap.cpp
+++ b/accessible/src/base/nsARIAMap.cpp
@@ -30,550 +30,550 @@ using namespace mozilla::a11y::aria;
  *  In addition, in MSAA, the unmapped role will also be exposed as a BSTR string role.
  *
  *  There are no nsIAccessibleRole enums for the following landmark roles:
  *    banner, contentinfo, main, navigation, note, search, secondary, seealso, breadcrumbs
  */
 
 static nsRoleMapEntry sWAIRoleMaps[] =
 {
-  {
-    "alert",
+  { // alert
+    &nsGkAtoms::alert,
     roles::ALERT,
     kUseMapRole,
     eNoValue,
     eNoAction,
     eNoLiveAttr,
     kNoReqStates
   },
-  {
-    "alertdialog",
+  { // alertdialog
+    &nsGkAtoms::alertdialog,
     roles::DIALOG,
     kUseMapRole,
     eNoValue,
     eNoAction,
     eNoLiveAttr,
     kNoReqStates
   },
-  {
-    "application",
+  { // application
+    &nsGkAtoms::application,
     roles::APPLICATION,
     kUseMapRole,
     eNoValue,
     eNoAction,
     eNoLiveAttr,
     kNoReqStates
   },
-  {
-    "article",
+  { // article
+    &nsGkAtoms::article,
     roles::DOCUMENT,
     kUseMapRole,
     eNoValue,
     eNoAction,
     eNoLiveAttr,
     kNoReqStates,
     eReadonlyUntilEditable
   },
-  {
-    "button",
+  { // button
+    &nsGkAtoms::button,
     roles::PUSHBUTTON,
     kUseMapRole,
     eNoValue,
     ePressAction,
     eNoLiveAttr,
     kNoReqStates,
     eARIAPressed
   },
-  {
-    "checkbox",
+  { // checkbox
+    &nsGkAtoms::checkbox,
     roles::CHECKBUTTON,
     kUseMapRole,
     eNoValue,
     eCheckUncheckAction,
     eNoLiveAttr,
     kNoReqStates,
     eARIACheckableMixed,
     eARIAReadonly
   },
-  {
-    "columnheader",
+  { // columnheader
+    &nsGkAtoms::columnheader,
     roles::COLUMNHEADER,
     kUseMapRole,
     eNoValue,
     eSortAction,
     eNoLiveAttr,
     kNoReqStates,
     eARIASelectable,
     eARIAReadonly
   },
-  {
-    "combobox",
+  { // combobox
+    &nsGkAtoms::combobox,
     roles::COMBOBOX,
     kUseMapRole,
     eNoValue,
     eOpenCloseAction,
     eNoLiveAttr,
     states::COLLAPSED | states::HASPOPUP,
     eARIAAutoComplete,
     eARIAReadonly
   },
-  {
-    "dialog",
+  { // dialog
+    &nsGkAtoms::dialog,
     roles::DIALOG,
     kUseMapRole,
     eNoValue,
     eNoAction,
     eNoLiveAttr,
     kNoReqStates
   },
-  {
-    "directory",
+  { // directory
+    &nsGkAtoms::directory,
     roles::LIST,
     kUseMapRole,
     eNoValue,
     eNoAction,
     eNoLiveAttr,
     kNoReqStates
   },
-  {
-    "document",
+  { // document
+    &nsGkAtoms::document,
     roles::DOCUMENT,
     kUseMapRole,
     eNoValue,
     eNoAction,
     eNoLiveAttr,
     kNoReqStates,
     eReadonlyUntilEditable
   },
-  {
-    "form",
+  { // form
+    &nsGkAtoms::form,
     roles::FORM,
     kUseMapRole,
     eNoValue,
     eNoAction,
     eNoLiveAttr,
     kNoReqStates
   },
-  {
-    "grid",
+  { // grid
+    &nsGkAtoms::grid,
     roles::TABLE,
     kUseMapRole,
     eNoValue,
     eNoAction,
     eNoLiveAttr,
     states::FOCUSABLE,
     eARIAMultiSelectable,
     eARIAReadonly
   },
-  {
-    "gridcell",
+  { // gridcell
+    &nsGkAtoms::gridcell,
     roles::GRID_CELL,
     kUseMapRole,
     eNoValue,
     eNoAction,
     eNoLiveAttr,
     kNoReqStates,
     eARIASelectable,
     eARIAReadonly
   },
-  {
-    "group",
+  { // group
+    &nsGkAtoms::group,
     roles::GROUPING,
     kUseMapRole,
     eNoValue,
     eNoAction,
     eNoLiveAttr,
     kNoReqStates
   },
-  {
-    "heading",
+  { // heading
+    &nsGkAtoms::heading,
     roles::HEADING,
     kUseMapRole,
     eNoValue,
     eNoAction,
     eNoLiveAttr,
     kNoReqStates
   },
-  {
-    "img",
+  { // img
+    &nsGkAtoms::img,
     roles::GRAPHIC,
     kUseMapRole,
     eNoValue,
     eNoAction,
     eNoLiveAttr,
     kNoReqStates
   },
-  {
-    "link",
+  { // link
+    &nsGkAtoms::link,
     roles::LINK,
     kUseMapRole,
     eNoValue,
     eJumpAction,
     eNoLiveAttr,
     states::LINKED
   },
-  {
-    "list",
+  { // list
+    &nsGkAtoms::list,
     roles::LIST,
     kUseMapRole,
     eNoValue,
     eNoAction,
     eNoLiveAttr,
     states::READONLY
   },
-  {
-    "listbox",
+  { // listbox
+    &nsGkAtoms::listbox,
     roles::LISTBOX,
     kUseMapRole,
     eNoValue,
     eNoAction,
     eNoLiveAttr,
     kNoReqStates,
     eARIAMultiSelectable,
     eARIAReadonly
   },
-  {
-    "listitem",
+  { // listitem
+    &nsGkAtoms::listitem,
     roles::LISTITEM,
     kUseMapRole,
     eNoValue,
     eNoAction, // XXX: should depend on state, parent accessible
     eNoLiveAttr,
     states::READONLY
   },
-  {
-    "log",
+  { // log
+    &nsGkAtoms::log_,
     roles::NOTHING,
     kUseNativeRole,
     eNoValue,
     eNoAction,
     ePoliteLiveAttr,
     kNoReqStates
   },
-  {
-    "marquee",
+  { // marquee
+    &nsGkAtoms::marquee,
     roles::ANIMATION,
     kUseMapRole,
     eNoValue,
     eNoAction,
     eOffLiveAttr,
     kNoReqStates
   },
-  {
-    "math",
+  { // math
+    &nsGkAtoms::math,
     roles::FLAT_EQUATION,
     kUseMapRole,
     eNoValue,
     eNoAction,
     eNoLiveAttr,
     kNoReqStates
   },
-  {
-    "menu",
+  { // menu
+    &nsGkAtoms::menu,
     roles::MENUPOPUP,
     kUseMapRole,
     eNoValue,
     eNoAction, // XXX: technically accessibles of menupopup role haven't
                // any action, but menu can be open or close.
     eNoLiveAttr,
     kNoReqStates
   },
-  {
-    "menubar",
+  { // menubar
+    &nsGkAtoms::menubar,
     roles::MENUBAR,
     kUseMapRole,
     eNoValue,
     eNoAction,
     eNoLiveAttr,
     kNoReqStates
   },
-  {
-    "menuitem",
+  { // menuitem
+    &nsGkAtoms::menuitem,
     roles::MENUITEM,
     kUseMapRole,
     eNoValue,
     eClickAction,
     eNoLiveAttr,
     kNoReqStates,
     eARIACheckedMixed
   },
-  {
-    "menuitemcheckbox",
+  { // menuitemcheckbox
+    &nsGkAtoms::menuitemcheckbox,
     roles::CHECK_MENU_ITEM,
     kUseMapRole,
     eNoValue,
     eClickAction,
     eNoLiveAttr,
     kNoReqStates,
     eARIACheckableMixed
   },
-  {
-    "menuitemradio",
+  { // menuitemradio
+    &nsGkAtoms::menuitemradio,
     roles::RADIO_MENU_ITEM,
     kUseMapRole,
     eNoValue,
     eClickAction,
     eNoLiveAttr,
     kNoReqStates,
     eARIACheckableBool
   },
-  {
-    "note",
+  { // note
+    &nsGkAtoms::note_,
     roles::NOTE,
     kUseMapRole,
     eNoValue,
     eNoAction,
     eNoLiveAttr,
     kNoReqStates
   },
-  {
-    "option",
+  { // option
+    &nsGkAtoms::option,
     roles::OPTION,
     kUseMapRole,
     eNoValue,
     eSelectAction,
     eNoLiveAttr,
     kNoReqStates,
     eARIASelectable,
     eARIACheckedMixed
   },
-  {
-    "presentation",
+  { // presentation
+    &nsGkAtoms::presentation,
     roles::NOTHING,
     kUseMapRole,
     eNoValue,
     eNoAction,
     eNoLiveAttr,
     kNoReqStates
   },
-  {
-    "progressbar",
+  { // progressbar
+    &nsGkAtoms::progressbar,
     roles::PROGRESSBAR,
     kUseMapRole,
     eHasValueMinMax,
     eNoAction,
     eNoLiveAttr,
     states::READONLY,
     eIndeterminateIfNoValue
   },
-  {
-    "radio",
+  { // radio
+    &nsGkAtoms::radio,
     roles::RADIOBUTTON,
     kUseMapRole,
     eNoValue,
     eSelectAction,
     eNoLiveAttr,
     kNoReqStates,
     eARIACheckableBool
   },
-  {
-    "radiogroup",
+  { // radiogroup
+    &nsGkAtoms::radiogroup,
     roles::GROUPING,
     kUseMapRole,
     eNoValue,
     eNoAction,
     eNoLiveAttr,
     kNoReqStates
   },
-  {
-    "region",
+  { // region
+    &nsGkAtoms::region,
     roles::PANE,
     kUseMapRole,
     eNoValue,
     eNoAction,
     eNoLiveAttr,
     kNoReqStates
   },
-  {
-    "row",
+  { // row
+    &nsGkAtoms::row,
     roles::ROW,
     kUseMapRole,
     eNoValue,
     eNoAction,
     eNoLiveAttr,
     kNoReqStates,
     eARIASelectable
   },
-  {
-    "rowheader",
+  { // rowheader
+    &nsGkAtoms::rowheader,
     roles::ROWHEADER,
     kUseMapRole,
     eNoValue,
     eSortAction,
     eNoLiveAttr,
     kNoReqStates,
     eARIASelectable,
     eARIAReadonly
   },
-  {
-    "scrollbar",
+  { // scrollbar
+    &nsGkAtoms::scrollbar,
     roles::SCROLLBAR,
     kUseMapRole,
     eHasValueMinMax,
     eNoAction,
     eNoLiveAttr,
     kNoReqStates,
     eARIAOrientation,
     eARIAReadonly
   },
-  {
-    "separator",
+  { // separator
+    &nsGkAtoms::separator_,
     roles::SEPARATOR,
     kUseMapRole,
     eNoValue,
     eNoAction,
     eNoLiveAttr,
     kNoReqStates,
     eARIAOrientation
   },
-  {
-    "slider",
+  { // slider
+    &nsGkAtoms::slider,
     roles::SLIDER,
     kUseMapRole,
     eHasValueMinMax,
     eNoAction,
     eNoLiveAttr,
     kNoReqStates,
     eARIAOrientation,
     eARIAReadonly
   },
-  {
-    "spinbutton",
+  { // spinbutton
+    &nsGkAtoms::spinbutton,
     roles::SPINBUTTON,
     kUseMapRole,
     eHasValueMinMax,
     eNoAction,
     eNoLiveAttr,
     kNoReqStates,
     eARIAReadonly
   },
-  {
-    "status",
+  { // status
+    &nsGkAtoms::status,
     roles::STATUSBAR,
     kUseMapRole,
     eNoValue,
     eNoAction,
     ePoliteLiveAttr,
     kNoReqStates
   },
-  {
-    "tab",
+  { // tab
+    &nsGkAtoms::tab,
     roles::PAGETAB,
     kUseMapRole,
     eNoValue,
     eSwitchAction,
     eNoLiveAttr,
     kNoReqStates,
     eARIASelectable
   },
-  {
-    "tablist",
+  { // tablist
+    &nsGkAtoms::tablist,
     roles::PAGETABLIST,
     kUseMapRole,
     eNoValue,
     eNoAction,
     ePoliteLiveAttr,
     kNoReqStates
   },
-  {
-    "tabpanel",
+  { // tabpanel
+    &nsGkAtoms::tabpanel,
     roles::PROPERTYPAGE,
     kUseMapRole,
     eNoValue,
     eNoAction,
     eNoLiveAttr,
     kNoReqStates
   },
-  {
-    "textbox",
+  { // textbox
+    &nsGkAtoms::textbox,
     roles::ENTRY,
     kUseMapRole,
     eNoValue,
     eActivateAction,
     eNoLiveAttr,
     kNoReqStates,
     eARIAAutoComplete,
     eARIAMultiline,
     eARIAReadonlyOrEditable
   },
-  {
-    "timer",
+  { // timer
+    &nsGkAtoms::timer,
     roles::NOTHING,
     kUseNativeRole,
     eNoValue,
     eNoAction,
     eOffLiveAttr,
     kNoReqStates
   },
-  {
-    "toolbar",
+  { // toolbar
+    &nsGkAtoms::toolbar,
     roles::TOOLBAR,
     kUseMapRole,
     eNoValue,
     eNoAction,
     eNoLiveAttr,
     kNoReqStates
   },
-  {
-    "tooltip",
+  { // tooltip
+    &nsGkAtoms::tooltip,
     roles::TOOLTIP,
     kUseMapRole,
     eNoValue,
     eNoAction,
     eNoLiveAttr,
     kNoReqStates
   },
-  {
-    "tree",
+  { // tree
+    &nsGkAtoms::tree,
     roles::OUTLINE,
     kUseMapRole,
     eNoValue,
     eNoAction,
     eNoLiveAttr,
     kNoReqStates,
     eARIAReadonly,
     eARIAMultiSelectable
   },
-  {
-    "treegrid",
+  { // treegrid
+    &nsGkAtoms::treegrid,
     roles::TREE_TABLE,
     kUseMapRole,
     eNoValue,
     eNoAction,
     eNoLiveAttr,
     kNoReqStates,
     eARIAReadonly,
     eARIAMultiSelectable
   },
-  {
-    "treeitem",
+  { // treeitem
+    &nsGkAtoms::treeitem,
     roles::OUTLINEITEM,
     kUseMapRole,
     eNoValue,
     eActivateAction, // XXX: should expose second 'expand/collapse' action based
                      // on states
     eNoLiveAttr,
     kNoReqStates,
     eARIASelectable,
     eARIACheckedMixed
   }
 };
 
 static nsRoleMapEntry sLandmarkRoleMap = {
-  "",
+  &nsGkAtoms::_empty,
   roles::NOTHING,
   kUseNativeRole,
   eNoValue,
   eNoAction,
   eNoLiveAttr,
   kNoReqStates
 };
 
 nsRoleMapEntry nsARIAMap::gEmptyRoleMap = {
-  "",
+  &nsGkAtoms::_empty,
   roles::NOTHING,
   kUseMapRole,
   eNoValue,
   eNoAction,
   eNoLiveAttr,
   kNoReqStates
 };
 
@@ -636,34 +636,34 @@ nsAttributeCharacteristics nsARIAMap::gW
 };
 
 PRUint32 nsARIAMap::gWAIUnivAttrMapLength = NS_ARRAY_LENGTH(nsARIAMap::gWAIUnivAttrMap);
 
 nsRoleMapEntry*
 aria::GetRoleMap(nsINode* aNode)
 {
   nsIContent* content = nsCoreUtils::GetRoleContent(aNode);
-  nsAutoString roleString;
+  nsAutoString roles;
   if (!content ||
-      !content->GetAttr(kNameSpaceID_None, nsGkAtoms::role, roleString) ||
-      roleString.IsEmpty()) {
+      !content->GetAttr(kNameSpaceID_None, nsGkAtoms::role, roles) ||
+      roles.IsEmpty()) {
     // We treat role="" as if the role attribute is absent (per aria spec:8.1.1)
     return nsnull;
   }
 
-  nsWhitespaceTokenizer tokenizer(roleString);
+  nsWhitespaceTokenizer tokenizer(roles);
   while (tokenizer.hasMoreTokens()) {
     // Do a binary search through table for the next role in role list
-    NS_LossyConvertUTF16toASCII role(tokenizer.nextToken());
+    const nsDependentSubstring role = tokenizer.nextToken();
     PRUint32 low = 0;
     PRUint32 high = ArrayLength(sWAIRoleMaps);
     while (low < high) {
       PRUint32 idx = (low + high) / 2;
-      PRInt32 compare = strcmp(role.get(), sWAIRoleMaps[idx].roleString);
-      if (compare == 0) 
+      PRInt32 compare = Compare(role, sWAIRoleMaps[idx].ARIARoleString());
+      if (compare == 0)
         return sWAIRoleMaps + idx;
 
       if (compare < 0)
         high = idx;
       else
         low = idx + 1;
     }
   }
--- a/accessible/src/base/nsARIAMap.h
+++ b/accessible/src/base/nsARIAMap.h
@@ -6,17 +6,18 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef _nsARIAMap_H_
 #define _nsARIAMap_H_
 
 #include "ARIAStateMap.h"
 #include "mozilla/a11y/Role.h"
 
-class nsIAtom;
+#include "nsIAtom.h"
+
 class nsIContent;
 class nsINode;
 
 ////////////////////////////////////////////////////////////////////////////////
 // Value constants
 
 /**
  * Used to define if role requires to expose nsIAccessibleValue.
@@ -131,19 +132,31 @@ enum EDefaultStateRule
 ////////////////////////////////////////////////////////////////////////////////
 // Role map entry
 
 /**
  * For each ARIA role, this maps the nsIAccessible information.
  */
 struct nsRoleMapEntry
 {
+  /**
+   * Return true if matches to the given ARIA role.
+   */
+  bool Is(nsIAtom* aARIARole) const
+    { return *roleAtom == aARIARole; }
+
+  /**
+   * Return ARIA role.
+   */
+  const nsDependentAtomString ARIARoleString() const
+    { return nsDependentAtomString(*roleAtom); }
+
   // ARIA role: string representation such as "button"
-  const char *roleString;
-  
+  nsIAtom** roleAtom;
+
   // Role mapping rule: maps to this nsIAccessibleRole
   mozilla::a11y::role role;
   
   // Role rule: whether to use mapped role or native semantics
   bool roleRule;
   
   // Value mapping rule: how to compute nsIAccessible value
   EValueRule valueRule;
--- a/accessible/src/base/nsAccUtils.cpp
+++ b/accessible/src/base/nsAccUtils.cpp
@@ -147,19 +147,18 @@ nsAccUtils::SetLiveContainerAttributes(n
         ancestor->GetAttr(kNameSpaceID_None, nsGkAtoms::aria_live,
                           live);
       } else if (role) {
         GetLiveAttrValue(role->liveAttRule, live);
       }
       if (!live.IsEmpty()) {
         SetAccAttr(aAttributes, nsGkAtoms::containerLive, live);
         if (role) {
-          nsAccUtils::SetAccAttr(aAttributes,
-                                 nsGkAtoms::containerLiveRole,
-                                 NS_ConvertASCIItoUTF16(role->roleString));
+          nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::containerLiveRole,
+                                 role->ARIARoleString());
         }
       }
     }
 
     // container-atomic attribute
     if (atomic.IsEmpty() &&
         nsAccUtils::HasDefinedARIAToken(ancestor, nsGkAtoms::aria_atomic) &&
         ancestor->GetAttr(kNameSpaceID_None, nsGkAtoms::aria_atomic, atomic))
--- a/accessible/src/base/nsAccUtils.h
+++ b/accessible/src/base/nsAccUtils.h
@@ -19,17 +19,16 @@
 #include "nsIDOMNode.h"
 #include "nsIPersistentProperties2.h"
 #include "nsIPresShell.h"
 #include "nsPoint.h"
 
 class nsAccessNode;
 class Accessible;
 class HyperTextAccessible;
-class nsHTMLTableAccessible;
 class DocAccessible;
 struct nsRoleMapEntry;
 #ifdef MOZ_XUL
 class nsXULTreeAccessible;
 #endif
 
 class nsAccUtils
 {
--- a/accessible/src/base/nsAccessibilityService.cpp
+++ b/accessible/src/base/nsAccessibilityService.cpp
@@ -15,22 +15,22 @@
 #include "DocAccessible-inl.h"
 #include "FocusManager.h"
 #include "HTMLCanvasAccessible.h"
 #include "HTMLElementAccessibles.h"
 #include "HTMLImageMapAccessible.h"
 #include "HTMLLinkAccessible.h"
 #include "HTMLListAccessible.h"
 #include "HTMLSelectAccessible.h"
+#include "HTMLTableAccessibleWrap.h"
 #include "HyperTextAccessibleWrap.h"
 #include "nsAccessiblePivot.h"
 #include "nsAccUtils.h"
 #include "nsARIAMap.h"
 #include "nsIAccessibleProvider.h"
-#include "nsHTMLTableAccessibleWrap.h"
 #include "nsXFormsFormControlsAccessible.h"
 #include "nsXFormsWidgetsAccessible.h"
 #include "OuterDocAccessible.h"
 #include "Role.h"
 #include "RootAccessibleWrap.h"
 #include "States.h"
 #include "Statistics.h"
 #ifdef XP_WIN
@@ -380,27 +380,27 @@ nsAccessibilityService::CreateHTMLRadioB
   return accessible;
 }
 
 already_AddRefed<Accessible>
 nsAccessibilityService::CreateHTMLTableAccessible(nsIContent* aContent,
                                                   nsIPresShell* aPresShell)
 {
   Accessible* accessible =
-    new nsHTMLTableAccessibleWrap(aContent, GetDocAccessible(aPresShell));
+    new HTMLTableAccessibleWrap(aContent, GetDocAccessible(aPresShell));
   NS_ADDREF(accessible);
   return accessible;
 }
 
 already_AddRefed<Accessible>
 nsAccessibilityService::CreateHTMLTableCellAccessible(nsIContent* aContent,
                                                       nsIPresShell* aPresShell)
 {
   Accessible* accessible =
-    new nsHTMLTableCellAccessibleWrap(aContent, GetDocAccessible(aPresShell));
+    new HTMLTableCellAccessibleWrap(aContent, GetDocAccessible(aPresShell));
   NS_ADDREF(accessible);
   return accessible;
 }
 
 already_AddRefed<Accessible>
 nsAccessibilityService::CreateHTMLTableRowAccessible(nsIContent* aContent,
                                                      nsIPresShell* aPresShell)
 {
@@ -460,17 +460,17 @@ nsAccessibilityService::CreateHTMLBRAcce
   return accessible;
 }
 
 already_AddRefed<Accessible>
 nsAccessibilityService::CreateHTMLCaptionAccessible(nsIContent* aContent,
                                                     nsIPresShell* aPresShell)
 {
   Accessible* accessible =
-    new nsHTMLCaptionAccessible(aContent, GetDocAccessible(aPresShell));
+    new HTMLCaptionAccessible(aContent, GetDocAccessible(aPresShell));
   NS_ADDREF(accessible);
   return accessible;
 }
 
 void
 nsAccessibilityService::ContentRangeInserted(nsIPresShell* aPresShell,
                                              nsIContent* aContainer,
                                              nsIContent* aStartChild,
@@ -1021,17 +1021,17 @@ nsAccessibilityService::GetOrCreateAcces
 
     newAcc = new HyperTextAccessibleWrap(content, docAcc);
     if (docAcc->BindToDocument(newAcc, aria::GetRoleMap(aNode)))
       return newAcc;
     return nsnull;
   }
 
   nsRoleMapEntry* roleMapEntry = aria::GetRoleMap(aNode);
-  if (roleMapEntry && !nsCRT::strcmp(roleMapEntry->roleString, "presentation")) {
+  if (roleMapEntry && roleMapEntry->Is(nsGkAtoms::presentation)) {
     // Ignore presentation role if element is focusable (focus event shouldn't
     // be ever lost and should be sensible).
     if (content->IsFocusable())
       roleMapEntry = nsnull;
     else
       return nsnull;
   }
 
@@ -1068,18 +1068,17 @@ nsAccessibilityService::GetOrCreateAcces
                 roleMapEntry = &nsARIAMap::gEmptyRoleMap;
             }
 
             break;
           }
 
 #ifdef DEBUG
           nsRoleMapEntry* tableRoleMapEntry = aria::GetRoleMap(tableContent);
-          NS_ASSERTION(tableRoleMapEntry &&
-                       !nsCRT::strcmp(tableRoleMapEntry->roleString, "presentation"),
+          NS_ASSERTION(tableRoleMapEntry && tableRoleMapEntry->Is(nsGkAtoms::presentation),
                        "No accessible for parent table and it didn't have role of presentation");
 #endif
 
           if (!roleMapEntry && !content->IsFocusable()) {
             // Table-related descendants of presentation table are also
             // presentation if they aren't focusable and have not explicit ARIA
             // role (don't create accessibles for them unless they need to fire
             // focus events).
@@ -1655,18 +1654,17 @@ nsAccessibilityService::CreateHTMLAccess
       tag == nsGkAtoms::h6 ||
       tag == nsGkAtoms::q) {
     Accessible* accessible = new HyperTextAccessibleWrap(aContent, aDoc);
     NS_IF_ADDREF(accessible);
     return accessible;
   }
 
   if (nsCoreUtils::IsHTMLTableHeader(aContent)) {
-    Accessible* accessible = new nsHTMLTableHeaderCellAccessibleWrap(aContent,
-                                                                     aDoc);
+    Accessible* accessible = new HTMLTableHeaderCellAccessibleWrap(aContent, aDoc);
     NS_IF_ADDREF(accessible);
     return accessible;
   }
 
   if (tag == nsGkAtoms::output) {
     Accessible* accessible = new HTMLOutputAccessible(aContent, aDoc);
     NS_IF_ADDREF(accessible);
     return accessible;
--- a/accessible/src/generic/TextLeafAccessible.cpp
+++ b/accessible/src/generic/TextLeafAccessible.cpp
@@ -46,25 +46,13 @@ TextLeafAccessible::AppendTextTo(nsAStri
 ENameValueFlag
 TextLeafAccessible::Name(nsString& aName)
 {
   // Text node, ARIA can't be used.
   aName = mText;
   return eNameOK;
 }
 
-nsresult
-TextLeafAccessible::GetAttributesInternal(nsIPersistentProperties *aAttributes)
-{
-  if (NativeRole() == roles::STATICTEXT) {
-    nsAutoString oldValueUnused;
-    aAttributes->SetStringProperty(NS_LITERAL_CSTRING("auto-generated"),
-                                  NS_LITERAL_STRING("true"), oldValueUnused);
-  }
-
-  return NS_OK;
-}
-
 void
 TextLeafAccessible::CacheChildren()
 {
   // No children for text accessible.
 }
--- a/accessible/src/generic/TextLeafAccessible.h
+++ b/accessible/src/generic/TextLeafAccessible.h
@@ -20,17 +20,16 @@ public:
   TextLeafAccessible(nsIContent* aContent, DocAccessible* aDoc);
   virtual ~TextLeafAccessible();
 
   // Accessible
   virtual mozilla::a11y::role NativeRole();
   virtual void AppendTextTo(nsAString& aText, PRUint32 aStartOffset = 0,
                             PRUint32 aLength = PR_UINT32_MAX);
   virtual ENameValueFlag Name(nsString& aName);
-  virtual nsresult GetAttributesInternal(nsIPersistentProperties* aAttributes);
 
   // TextLeafAccessible
   void SetText(const nsAString& aText) { mText = aText; }
   const nsString& Text() const { return mText; }
 
 protected:
   // Accessible
   virtual void CacheChildren();
rename from accessible/src/html/nsHTMLTableAccessible.cpp
rename to accessible/src/html/HTMLTableAccessible.cpp
--- a/accessible/src/html/nsHTMLTableAccessible.cpp
+++ b/accessible/src/html/HTMLTableAccessible.cpp
@@ -1,14 +1,14 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-#include "nsHTMLTableAccessible.h"
+#include "HTMLTableAccessible.h"
 
 #include "Accessible-inl.h"
 #include "nsAccessibilityService.h"
 #include "nsAccTreeWalker.h"
 #include "nsAccUtils.h"
 #include "DocAccessible.h"
 #include "nsTextEquivUtils.h"
 #include "Relation.h"
@@ -34,63 +34,63 @@
 #include "nsFrameSelection.h"
 #include "nsLayoutErrors.h"
 #include "nsArrayUtils.h"
 #include "nsComponentManagerUtils.h"
 
 using namespace mozilla::a11y;
 
 ////////////////////////////////////////////////////////////////////////////////
-// nsHTMLTableCellAccessible
+// HTMLTableCellAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
-nsHTMLTableCellAccessible::
-  nsHTMLTableCellAccessible(nsIContent* aContent, DocAccessible* aDoc) :
+HTMLTableCellAccessible::
+  HTMLTableCellAccessible(nsIContent* aContent, DocAccessible* aDoc) :
   HyperTextAccessibleWrap(aContent, aDoc)
 {
 }
 
 ////////////////////////////////////////////////////////////////////////////////
-// nsHTMLTableCellAccessible: nsISupports implementation
+// HTMLTableCellAccessible: nsISupports implementation
 
-NS_IMPL_ISUPPORTS_INHERITED1(nsHTMLTableCellAccessible,
+NS_IMPL_ISUPPORTS_INHERITED1(HTMLTableCellAccessible,
                              HyperTextAccessible,
                              nsIAccessibleTableCell)
 
 ////////////////////////////////////////////////////////////////////////////////
-// nsHTMLTableCellAccessible: Accessible implementation
+// HTMLTableCellAccessible: Accessible implementation
 
 role
-nsHTMLTableCellAccessible::NativeRole()
+HTMLTableCellAccessible::NativeRole()
 {
   return roles::CELL;
 }
 
 PRUint64
-nsHTMLTableCellAccessible::NativeState()
+HTMLTableCellAccessible::NativeState()
 {
   PRUint64 state = HyperTextAccessibleWrap::NativeState();
 
   nsIFrame *frame = mContent->GetPrimaryFrame();
   NS_ASSERTION(frame, "No frame for valid cell accessible!");
 
   if (frame && frame->IsSelected())
     state |= states::SELECTED;
 
   return state;
 }
 
 PRUint64
-nsHTMLTableCellAccessible::NativeInteractiveState() const
+HTMLTableCellAccessible::NativeInteractiveState() const
 {
   return HyperTextAccessibleWrap::NativeInteractiveState() | states::SELECTABLE;
 }
 
 nsresult
-nsHTMLTableCellAccessible::GetAttributesInternal(nsIPersistentProperties *aAttributes)
+HTMLTableCellAccessible::GetAttributesInternal(nsIPersistentProperties* aAttributes)
 {
   if (IsDefunct())
     return NS_ERROR_FAILURE;
 
   nsresult rv = HyperTextAccessibleWrap::GetAttributesInternal(aAttributes);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // table-cell-index attribute
@@ -134,119 +134,119 @@ nsHTMLTableCellAccessible::GetAttributes
   mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::axis, axisText);
   if (!axisText.IsEmpty())
     nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::axis, axisText);
 
   return NS_OK;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
-// nsHTMLTableCellAccessible: nsIAccessibleTableCell implementation
+// HTMLTableCellAccessible: nsIAccessibleTableCell implementation
 
 NS_IMETHODIMP
-nsHTMLTableCellAccessible::GetTable(nsIAccessibleTable **aTable)
+HTMLTableCellAccessible::GetTable(nsIAccessibleTable** aTable)
 {
   NS_ENSURE_ARG_POINTER(aTable);
   *aTable = nsnull;
 
   if (IsDefunct())
     return NS_OK;
 
   nsCOMPtr<nsIAccessibleTable> table = GetTableAccessible();
   table.swap(*aTable);
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsHTMLTableCellAccessible::GetColumnIndex(PRInt32 *aColumnIndex)
+HTMLTableCellAccessible::GetColumnIndex(PRInt32* aColumnIndex)
 {
   NS_ENSURE_ARG_POINTER(aColumnIndex);
   *aColumnIndex = -1;
 
   if (IsDefunct())
     return NS_ERROR_FAILURE;
 
   nsITableCellLayout* cellLayout = GetCellLayout();
   NS_ENSURE_STATE(cellLayout);
 
   return cellLayout->GetColIndex(*aColumnIndex);
 }
 
 NS_IMETHODIMP
-nsHTMLTableCellAccessible::GetRowIndex(PRInt32 *aRowIndex)
+HTMLTableCellAccessible::GetRowIndex(PRInt32* aRowIndex)
 {
   NS_ENSURE_ARG_POINTER(aRowIndex);
   *aRowIndex = -1;
 
   if (IsDefunct())
     return NS_ERROR_FAILURE;
 
   nsITableCellLayout* cellLayout = GetCellLayout();
   NS_ENSURE_STATE(cellLayout);
 
   return cellLayout->GetRowIndex(*aRowIndex);
 }
 
 NS_IMETHODIMP
-nsHTMLTableCellAccessible::GetColumnExtent(PRInt32 *aExtentCount)
+HTMLTableCellAccessible::GetColumnExtent(PRInt32* aExtentCount)
 {
   NS_ENSURE_ARG_POINTER(aExtentCount);
   *aExtentCount = 1;
 
   PRInt32 rowIdx = -1, colIdx = -1;
   GetCellIndexes(rowIdx, colIdx);
 
   nsCOMPtr<nsIAccessibleTable> table = GetTableAccessible();
   NS_ENSURE_STATE(table);
 
   return table->GetColumnExtentAt(rowIdx, colIdx, aExtentCount);
 }
 
 NS_IMETHODIMP
-nsHTMLTableCellAccessible::GetRowExtent(PRInt32 *aExtentCount)
+HTMLTableCellAccessible::GetRowExtent(PRInt32* aExtentCount)
 {
   NS_ENSURE_ARG_POINTER(aExtentCount);
   *aExtentCount = 1;
 
   PRInt32 rowIdx = -1, colIdx = -1;
   GetCellIndexes(rowIdx, colIdx);
 
   nsCOMPtr<nsIAccessibleTable> table = GetTableAccessible();
   NS_ENSURE_STATE(table);
 
   return table->GetRowExtentAt(rowIdx, colIdx, aExtentCount);
 }
 
 NS_IMETHODIMP
-nsHTMLTableCellAccessible::GetColumnHeaderCells(nsIArray **aHeaderCells)
+HTMLTableCellAccessible::GetColumnHeaderCells(nsIArray** aHeaderCells)
 {
   NS_ENSURE_ARG_POINTER(aHeaderCells);
   *aHeaderCells = nsnull;
 
   if (IsDefunct())
     return NS_ERROR_FAILURE;
 
   return GetHeaderCells(nsAccUtils::eColumnHeaderCells, aHeaderCells);
 }
 
 NS_IMETHODIMP
-nsHTMLTableCellAccessible::GetRowHeaderCells(nsIArray **aHeaderCells)
+HTMLTableCellAccessible::GetRowHeaderCells(nsIArray** aHeaderCells)
 {
   NS_ENSURE_ARG_POINTER(aHeaderCells);
   *aHeaderCells = nsnull;
 
   if (IsDefunct())
     return NS_ERROR_FAILURE;
 
   return GetHeaderCells(nsAccUtils::eRowHeaderCells, aHeaderCells);
 }
 
 NS_IMETHODIMP
-nsHTMLTableCellAccessible::IsSelected(bool *aIsSelected)
+HTMLTableCellAccessible::IsSelected(bool* aIsSelected)
 {
   NS_ENSURE_ARG_POINTER(aIsSelected);
   *aIsSelected = false;
 
   if (IsDefunct())
     return NS_ERROR_FAILURE;
 
   PRInt32 rowIdx = -1, colIdx = -1;
@@ -254,59 +254,58 @@ nsHTMLTableCellAccessible::IsSelected(bo
 
   nsCOMPtr<nsIAccessibleTable> table = GetTableAccessible();
   NS_ENSURE_STATE(table);
 
   return table->IsCellSelected(rowIdx, colIdx, aIsSelected);
 }
 
 ////////////////////////////////////////////////////////////////////////////////
-// nsHTMLTableCellAccessible: protected implementation
+// HTMLTableCellAccessible: protected implementation
 
 already_AddRefed<nsIAccessibleTable>
-nsHTMLTableCellAccessible::GetTableAccessible()
+HTMLTableCellAccessible::GetTableAccessible()
 {
   Accessible* parent = this;
   while ((parent = parent->Parent())) {
     roles::Role role = parent->Role();
     if (role == roles::TABLE || role == roles::TREE_TABLE) {
       nsIAccessibleTable* tableAcc = nsnull;
       CallQueryInterface(parent, &tableAcc);
       return tableAcc;
     }
   }
 
   return nsnull;
 }
 
 nsITableCellLayout*
-nsHTMLTableCellAccessible::GetCellLayout()
+HTMLTableCellAccessible::GetCellLayout()
 {
   nsIFrame *frame = mContent->GetPrimaryFrame();
   NS_ASSERTION(frame, "The frame cannot be obtaied for HTML table cell.");
   if (!frame)
     return nsnull;
 
   nsITableCellLayout *cellLayout = do_QueryFrame(frame);
   return cellLayout;
 }
 
 nsresult
-nsHTMLTableCellAccessible::GetCellIndexes(PRInt32& aRowIndex,
-                                          PRInt32& aColIndex)
+HTMLTableCellAccessible::GetCellIndexes(PRInt32& aRowIndex, PRInt32& aColIndex)
 {
   nsITableCellLayout *cellLayout = GetCellLayout();
   NS_ENSURE_STATE(cellLayout);
 
   return cellLayout->GetCellIndexes(aRowIndex, aColIndex);
 }
 
 nsresult
-nsHTMLTableCellAccessible::GetHeaderCells(PRInt32 aRowOrColumnHeaderCell,
-                                          nsIArray **aHeaderCells)
+HTMLTableCellAccessible::GetHeaderCells(PRInt32 aRowOrColumnHeaderCell,
+                                        nsIArray** aHeaderCells)
 {
   // Get header cells from @header attribute.
   IDRefsIterator iter(mDoc, mContent, nsGkAtoms::headers);
   nsIContent* headerCellElm = iter.NextElem();
   if (headerCellElm) {
     nsresult rv = NS_OK;
     nsCOMPtr<nsIMutableArray> headerCells =
       do_CreateInstance(NS_ARRAY_CONTRACTID, &rv);
@@ -336,31 +335,30 @@ nsHTMLTableCellAccessible::GetHeaderCell
     return nsAccUtils::GetHeaderCellsFor(table, this, aRowOrColumnHeaderCell,
                                          aHeaderCells);
   }
 
   return NS_OK;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
-// nsHTMLTableHeaderAccessible
+// HTMLTableHeaderCellAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
-nsHTMLTableHeaderCellAccessible::
-  nsHTMLTableHeaderCellAccessible(nsIContent* aContent,
-                                  DocAccessible* aDoc) :
-  nsHTMLTableCellAccessible(aContent, aDoc)
+HTMLTableHeaderCellAccessible::
+  HTMLTableHeaderCellAccessible(nsIContent* aContent, DocAccessible* aDoc) :
+  HTMLTableCellAccessible(aContent, aDoc)
 {
 }
 
 ////////////////////////////////////////////////////////////////////////////////
-// nsHTMLTableHeaderAccessible: Accessible implementation
+// HTMLTableHeaderCellAccessible: Accessible implementation
 
 role
-nsHTMLTableHeaderCellAccessible::NativeRole()
+HTMLTableHeaderCellAccessible::NativeRole()
 {
   // Check value of @scope attribute.
   static nsIContent::AttrValuesArray scopeValues[] =
     {&nsGkAtoms::col, &nsGkAtoms::row, nsnull};
   PRInt32 valueIdx =
     mContent->FindAttrValueIn(kNameSpaceID_None, nsGkAtoms::scope,
                               scopeValues, eCaseMatters);
 
@@ -396,47 +394,47 @@ nsHTMLTableHeaderCellAccessible::NativeR
   }
 
   // No elements in siblings what means the table has one column only. Therefore
   // it should be column header.
   return roles::COLUMNHEADER;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
-// nsHTMLTableAccessible
+// HTMLTableAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
-nsHTMLTableAccessible::
-  nsHTMLTableAccessible(nsIContent* aContent, DocAccessible* aDoc) :
+HTMLTableAccessible::
+  HTMLTableAccessible(nsIContent* aContent, DocAccessible* aDoc) :
   AccessibleWrap(aContent, aDoc), xpcAccessibleTable(this)
 {
 }
 
 ////////////////////////////////////////////////////////////////////////////////
-// nsHTMLTableAccessible: nsISupports implementation
+// HTMLTableAccessible: nsISupports implementation
 
-NS_IMPL_ISUPPORTS_INHERITED1(nsHTMLTableAccessible, Accessible,
+NS_IMPL_ISUPPORTS_INHERITED1(HTMLTableAccessible, Accessible,
                              nsIAccessibleTable)
 
 ////////////////////////////////////////////////////////////////////////////////
 //nsAccessNode
 
 void
-nsHTMLTableAccessible::Shutdown()
+HTMLTableAccessible::Shutdown()
 {
   mTable = nsnull;
   AccessibleWrap::Shutdown();
 }
 
 
 ////////////////////////////////////////////////////////////////////////////////
-// nsHTMLTableAccessible: Accessible implementation
+// HTMLTableAccessible: Accessible implementation
 
 void
-nsHTMLTableAccessible::CacheChildren()
+HTMLTableAccessible::CacheChildren()
 {
   // Move caption accessible so that it's the first child. Check for the first
   // caption only, because nsAccessibilityService ensures we don't create
   // accessibles for the other captions, since only the first is actually
   // visible.
   nsAccTreeWalker walker(mDoc, mContent, CanHaveAnonChildren());
 
   Accessible* child = nsnull;
@@ -446,29 +444,29 @@ nsHTMLTableAccessible::CacheChildren()
       while ((child = walker.NextChild()) && AppendChild(child));
       break;
     }
     AppendChild(child);
   }
 }
 
 role
-nsHTMLTableAccessible::NativeRole()
+HTMLTableAccessible::NativeRole()
 {
   return roles::TABLE;
 }
 
 PRUint64
-nsHTMLTableAccessible::NativeState()
+HTMLTableAccessible::NativeState()
 {
   return Accessible::NativeState() | states::READONLY;
 }
 
 nsresult
-nsHTMLTableAccessible::GetNameInternal(nsAString& aName)
+HTMLTableAccessible::GetNameInternal(nsAString& aName)
 {
   Accessible::GetNameInternal(aName);
   if (!aName.IsEmpty())
     return NS_OK;
 
   // Use table caption as a name.
   Accessible* caption = Caption();
   if (caption) {
@@ -481,88 +479,88 @@ nsHTMLTableAccessible::GetNameInternal(n
   }
 
   // If no caption then use summary as a name.
   mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::summary, aName);
   return NS_OK;
 }
 
 nsresult
-nsHTMLTableAccessible::GetAttributesInternal(nsIPersistentProperties *aAttributes)
+HTMLTableAccessible::GetAttributesInternal(nsIPersistentProperties* aAttributes)
 {
   nsresult rv = AccessibleWrap::GetAttributesInternal(aAttributes);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (IsProbablyLayoutTable()) {
     nsAutoString oldValueUnused;
     aAttributes->SetStringProperty(NS_LITERAL_CSTRING("layout-guess"),
                                    NS_LITERAL_STRING("true"), oldValueUnused);
   }
 
   return NS_OK;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
-// nsHTMLTableAccessible: nsIAccessible implementation
+// HTMLTableAccessible: nsIAccessible implementation
 
 Relation
-nsHTMLTableAccessible::RelationByType(PRUint32 aType)
+HTMLTableAccessible::RelationByType(PRUint32 aType)
 {
   Relation rel = AccessibleWrap::RelationByType(aType);
   if (aType == nsIAccessibleRelation::RELATION_LABELLED_BY)
     rel.AppendTarget(Caption());
 
   return rel;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
-// nsHTMLTableAccessible: nsIAccessibleTable implementation
+// HTMLTableAccessible: nsIAccessibleTable implementation
 
 Accessible*
-nsHTMLTableAccessible::Caption()
+HTMLTableAccessible::Caption()
 {
   Accessible* child = mChildren.SafeElementAt(0, nsnull);
   return child && child->Role() == roles::CAPTION ? child : nsnull;
 }
 
 void
-nsHTMLTableAccessible::Summary(nsString& aSummary)
+HTMLTableAccessible::Summary(nsString& aSummary)
 {
   nsCOMPtr<nsIDOMHTMLTableElement> table(do_QueryInterface(mContent));
 
   if (table)
     table->GetSummary(aSummary);
 }
 
 PRUint32
-nsHTMLTableAccessible::ColCount()
+HTMLTableAccessible::ColCount()
 {
   nsITableLayout* tableLayout = GetTableLayout();
   if (!tableLayout)
     return 0;
 
   PRInt32 rowCount = 0, colCount = 0;
   tableLayout->GetTableSize(rowCount, colCount);
   return colCount;
 }
 
 PRUint32
-nsHTMLTableAccessible::RowCount()
+HTMLTableAccessible::RowCount()
 {
   nsITableLayout* tableLayout = GetTableLayout();
   if (!tableLayout)
     return 0;
 
   PRInt32 rowCount = 0, colCount = 0;
   tableLayout->GetTableSize(rowCount, colCount);
   return rowCount;
 }
 
 NS_IMETHODIMP
-nsHTMLTableAccessible::GetSelectedCellCount(PRUint32* aCount)
+HTMLTableAccessible::GetSelectedCellCount(PRUint32* aCount)
 {
   NS_ENSURE_ARG_POINTER(aCount);
   *aCount = 0;
 
   PRInt32 rowCount = 0;
   nsresult rv = GetRowCount(&rowCount);
   NS_ENSURE_SUCCESS(rv, rv);
 
@@ -595,17 +593,17 @@ nsHTMLTableAccessible::GetSelectedCellCo
       }
     }
   }
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsHTMLTableAccessible::GetSelectedColumnCount(PRUint32* aCount)
+HTMLTableAccessible::GetSelectedColumnCount(PRUint32* aCount)
 {
   NS_ENSURE_ARG_POINTER(aCount);
   *aCount = 0;
 
   PRInt32 count = 0;
   nsresult rv = GetColumnCount(&count);
   NS_ENSURE_SUCCESS(rv, rv);
 
@@ -618,17 +616,17 @@ nsHTMLTableAccessible::GetSelectedColumn
     if (state)
       (*aCount)++;
   }
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsHTMLTableAccessible::GetSelectedRowCount(PRUint32* aCount)
+HTMLTableAccessible::GetSelectedRowCount(PRUint32* aCount)
 {
   NS_ENSURE_ARG_POINTER(aCount);
   *aCount = 0;
 
   PRInt32 count = 0;
   nsresult rv = GetRowCount(&count);
   NS_ENSURE_SUCCESS(rv, rv);
 
@@ -641,17 +639,17 @@ nsHTMLTableAccessible::GetSelectedRowCou
     if (state)
       (*aCount)++;
   }
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsHTMLTableAccessible::GetSelectedCells(nsIArray **aCells)
+HTMLTableAccessible::GetSelectedCells(nsIArray** aCells)
 {
   NS_ENSURE_ARG_POINTER(aCells);
   *aCells = nsnull;
 
   PRInt32 rowCount = 0;
   nsresult rv = GetRowCount(&rowCount);
   NS_ENSURE_SUCCESS(rv, rv);
 
@@ -691,18 +689,18 @@ nsHTMLTableAccessible::GetSelectedCells(
     }
   }
 
   NS_ADDREF(*aCells = selCells);
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsHTMLTableAccessible::GetSelectedCellIndices(PRUint32 *aNumCells,
-                                              PRInt32 **aCells)
+HTMLTableAccessible::GetSelectedCellIndices(PRUint32* aNumCells,
+                                            PRInt32** aCells)
 {
   NS_ENSURE_ARG_POINTER(aNumCells);
   *aNumCells = 0;
   NS_ENSURE_ARG_POINTER(aCells);
   *aCells = nsnull;
 
   PRInt32 rowCount = 0;
   nsresult rv = GetRowCount(&rowCount);
@@ -761,18 +759,18 @@ nsHTMLTableAccessible::GetSelectedCellIn
     }
   }
 
   *aCells = cellsArray;
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsHTMLTableAccessible::GetSelectedColumnIndices(PRUint32 *aNumColumns,
-                                                PRInt32 **aColumns)
+HTMLTableAccessible::GetSelectedColumnIndices(PRUint32* aNumColumns,
+                                              PRInt32** aColumns)
 {
   nsresult rv = NS_OK;
 
   PRInt32 columnCount;
   rv = GetColumnCount(&columnCount);
   NS_ENSURE_SUCCESS(rv, rv);
 
   bool *states = new bool[columnCount];
@@ -803,18 +801,18 @@ nsHTMLTableAccessible::GetSelectedColumn
   }
 
   delete []states;
   *aColumns = outArray;
   return rv;
 }
 
 NS_IMETHODIMP
-nsHTMLTableAccessible::GetSelectedRowIndices(PRUint32 *aNumRows,
-                                             PRInt32 **aRows)
+HTMLTableAccessible::GetSelectedRowIndices(PRUint32* aNumRows,
+                                           PRInt32** aRows)
 {
   nsresult rv = NS_OK;
 
   PRInt32 rowCount;
   rv = GetRowCount(&rowCount);
   NS_ENSURE_SUCCESS(rv, rv);
 
   bool *states = new bool[rowCount];
@@ -845,17 +843,17 @@ nsHTMLTableAccessible::GetSelectedRowInd
   }
 
   delete []states;
   *aRows = outArray;
   return rv;
 }
 
 Accessible*
-nsHTMLTableAccessible::CellAt(PRUint32 aRowIndex, PRUint32 aColumnIndex)
+HTMLTableAccessible::CellAt(PRUint32 aRowIndex, PRUint32 aColumnIndex)
 { 
   nsCOMPtr<nsIDOMElement> cellElement;
   GetCellAt(aRowIndex, aColumnIndex, *getter_AddRefs(cellElement));
   if (!cellElement)
     return nsnull;
 
   nsCOMPtr<nsIContent> cellContent(do_QueryInterface(cellElement));
   if (!cellContent)
@@ -864,27 +862,27 @@ nsHTMLTableAccessible::CellAt(PRUint32 a
   Accessible* cell = mDoc->GetAccessible(cellContent);
 
   // XXX bug 576838: crazy tables (like table6 in tables/test_table2.html) may
   // return itself as a cell what makes Orca hang.
   return cell == this ? nsnull : cell;
 }
 
 PRInt32
-nsHTMLTableAccessible::CellIndexAt(PRUint32 aRowIdx, PRUint32 aColIdx)
+HTMLTableAccessible::CellIndexAt(PRUint32 aRowIdx, PRUint32 aColIdx)
 {
   nsITableLayout* tableLayout = GetTableLayout();
 
   PRInt32 index = -1;
   tableLayout->GetIndexByRowAndColumn(aRowIdx, aColIdx, &index);
   return index;
 }
 
 NS_IMETHODIMP
-nsHTMLTableAccessible::GetColumnIndexAt(PRInt32 aIndex, PRInt32 *aColumn)
+HTMLTableAccessible::GetColumnIndexAt(PRInt32 aIndex, PRInt32* aColumn)
 {
   NS_ENSURE_ARG_POINTER(aColumn);
 
   if (IsDefunct())
     return NS_ERROR_FAILURE;
 
   nsITableLayout *tableLayout = GetTableLayout();
   NS_ENSURE_STATE(tableLayout);
@@ -892,17 +890,17 @@ nsHTMLTableAccessible::GetColumnIndexAt(
   PRInt32 row;
   nsresult rv = tableLayout->GetRowAndColumnByIndex(aIndex, &row, aColumn);
   NS_ENSURE_SUCCESS(rv, rv);
 
   return (row == -1 || *aColumn == -1) ? NS_ERROR_INVALID_ARG : NS_OK;
 }
 
 NS_IMETHODIMP
-nsHTMLTableAccessible::GetRowIndexAt(PRInt32 aIndex, PRInt32 *aRow)
+HTMLTableAccessible::GetRowIndexAt(PRInt32 aIndex, PRInt32* aRow)
 {
   NS_ENSURE_ARG_POINTER(aRow);
 
   if (IsDefunct())
     return NS_ERROR_FAILURE;
 
   nsITableLayout *tableLayout = GetTableLayout();
   NS_ENSURE_STATE(tableLayout);
@@ -910,19 +908,19 @@ nsHTMLTableAccessible::GetRowIndexAt(PRI
   PRInt32 column;
   nsresult rv = tableLayout->GetRowAndColumnByIndex(aIndex, aRow, &column);
   NS_ENSURE_SUCCESS(rv, rv);
 
   return (*aRow == -1 || column == -1) ? NS_ERROR_INVALID_ARG : NS_OK;
 }
 
 NS_IMETHODIMP
-nsHTMLTableAccessible::GetRowAndColumnIndicesAt(PRInt32 aIndex,
-                                                PRInt32* aRowIdx,
-                                                PRInt32* aColumnIdx)
+HTMLTableAccessible::GetRowAndColumnIndicesAt(PRInt32 aIndex,
+                                              PRInt32* aRowIdx,
+                                              PRInt32* aColumnIdx)
 {
   NS_ENSURE_ARG_POINTER(aRowIdx);
   *aRowIdx = -1;
   NS_ENSURE_ARG_POINTER(aColumnIdx);
   *aColumnIdx = -1;
 
   if (IsDefunct())
     return NS_ERROR_FAILURE;
@@ -930,17 +928,17 @@ nsHTMLTableAccessible::GetRowAndColumnIn
   nsITableLayout* tableLayout = GetTableLayout();
   if (tableLayout)
     tableLayout->GetRowAndColumnByIndex(aIndex, aRowIdx, aColumnIdx);
 
   return (*aRowIdx == -1 || *aColumnIdx == -1) ? NS_ERROR_INVALID_ARG : NS_OK;
 }
 
 PRUint32
-nsHTMLTableAccessible::ColExtentAt(PRUint32 aRowIdx, PRUint32 aColIdx)
+HTMLTableAccessible::ColExtentAt(PRUint32 aRowIdx, PRUint32 aColIdx)
 {
   nsITableLayout* tableLayout = GetTableLayout();
   if (!tableLayout)
     return 0;
 
   nsCOMPtr<nsIDOMElement> domElement;
   PRInt32 startRowIndex, startColIndex, rowSpan, colSpan, actualRowSpan;
   bool isSelected;
@@ -950,17 +948,17 @@ nsHTMLTableAccessible::ColExtentAt(PRUin
     GetCellDataAt(aRowIdx, aColIdx, *getter_AddRefs(domElement),
                   startRowIndex, startColIndex, rowSpan, colSpan,
                   actualRowSpan, columnExtent, isSelected);
 
   return columnExtent;
 }
 
 PRUint32
-nsHTMLTableAccessible::RowExtentAt(PRUint32 aRowIdx, PRUint32 aColIdx)
+HTMLTableAccessible::RowExtentAt(PRUint32 aRowIdx, PRUint32 aColIdx)
 {
   nsITableLayout* tableLayout = GetTableLayout();
   if (!tableLayout)
     return 0;
 
   nsCOMPtr<nsIDOMElement> domElement;
   PRInt32 startRowIndex, startColIndex, rowSpan, colSpan, actualColSpan;
   bool isSelected;
@@ -970,29 +968,29 @@ nsHTMLTableAccessible::RowExtentAt(PRUin
     GetCellDataAt(aRowIdx, aColIdx, *getter_AddRefs(domElement),
                   startRowIndex, startColIndex, rowSpan, colSpan,
                   rowExtent, actualColSpan, isSelected);
 
   return rowExtent;
 }
 
 NS_IMETHODIMP
-nsHTMLTableAccessible::GetColumnDescription(PRInt32 aColumn, nsAString &_retval)
+HTMLTableAccessible::GetColumnDescription(PRInt32 aColumn, nsAString& _retval)
 {
   return NS_ERROR_NOT_IMPLEMENTED;
 }
 
 NS_IMETHODIMP
-nsHTMLTableAccessible::GetRowDescription(PRInt32 aRow, nsAString &_retval)
+HTMLTableAccessible::GetRowDescription(PRInt32 aRow, nsAString& _retval)
 {
   return NS_ERROR_NOT_IMPLEMENTED;
 }
 
 NS_IMETHODIMP
-nsHTMLTableAccessible::IsColumnSelected(PRInt32 aColumn, bool *aIsSelected)
+HTMLTableAccessible::IsColumnSelected(PRInt32 aColumn, bool* aIsSelected)
 {
   NS_ENSURE_ARG_POINTER(aIsSelected);
   *aIsSelected = false;
 
   PRInt32 colCount = 0;
   nsresult rv = GetColumnCount(&colCount);
   NS_ENSURE_SUCCESS(rv, rv);
 
@@ -1012,17 +1010,17 @@ nsHTMLTableAccessible::IsColumnSelected(
         break;
     }
   }
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsHTMLTableAccessible::IsRowSelected(PRInt32 aRow, bool *aIsSelected)
+HTMLTableAccessible::IsRowSelected(PRInt32 aRow, bool* aIsSelected)
 {
   NS_ENSURE_ARG_POINTER(aIsSelected);
   *aIsSelected = false;
 
   PRInt32 rowCount = 0;
   nsresult rv = GetRowCount(&rowCount);
   NS_ENSURE_SUCCESS(rv, rv);
 
@@ -1042,18 +1040,18 @@ nsHTMLTableAccessible::IsRowSelected(PRI
         break;
     }
   }
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsHTMLTableAccessible::IsCellSelected(PRInt32 aRow, PRInt32 aColumn,
-                                      bool *aIsSelected)
+HTMLTableAccessible::IsCellSelected(PRInt32 aRow, PRInt32 aColumn,
+                                    bool* aIsSelected)
 {
   NS_ENSURE_ARG_POINTER(aIsSelected);
   *aIsSelected = false;
 
   nsITableLayout *tableLayout = GetTableLayout();
   NS_ENSURE_STATE(tableLayout);
 
   nsCOMPtr<nsIDOMElement> domElement;
@@ -1066,66 +1064,65 @@ nsHTMLTableAccessible::IsCellSelected(PR
                   actualRowSpan, actualColSpan, *aIsSelected);
 
   if (rv == NS_TABLELAYOUT_CELL_NOT_FOUND)
     return NS_ERROR_INVALID_ARG;
   return rv;
 }
 
 NS_IMETHODIMP
-nsHTMLTableAccessible::SelectRow(PRInt32 aRow)
+HTMLTableAccessible::SelectRow(PRInt32 aRow)
 {
   if (IsDefunct())
     return NS_ERROR_FAILURE;
 
   nsresult rv =
     RemoveRowsOrColumnsFromSelection(aRow,
                                      nsISelectionPrivate::TABLESELECTION_ROW,
                                      true);
   NS_ENSURE_SUCCESS(rv, rv);
 
   return AddRowOrColumnToSelection(aRow,
                                    nsISelectionPrivate::TABLESELECTION_ROW);
 }
 
 NS_IMETHODIMP
-nsHTMLTableAccessible::SelectColumn(PRInt32 aColumn)
+HTMLTableAccessible::SelectColumn(PRInt32 aColumn)
 {
   if (IsDefunct())
     return NS_ERROR_FAILURE;
 
   nsresult rv =
     RemoveRowsOrColumnsFromSelection(aColumn,
                                      nsISelectionPrivate::TABLESELECTION_COLUMN,
                                      true);
   NS_ENSURE_SUCCESS(rv, rv);
 
   return AddRowOrColumnToSelection(aColumn,
                                    nsISelectionPrivate::TABLESELECTION_COLUMN);
 }
 
 void
-nsHTMLTableAccessible::UnselectRow(PRUint32 aRowIdx)
+HTMLTableAccessible::UnselectRow(PRUint32 aRowIdx)
 {
   RemoveRowsOrColumnsFromSelection(aRowIdx,
                                    nsISelectionPrivate::TABLESELECTION_ROW,
                                    false);
 }
 
 void
-nsHTMLTableAccessible::UnselectCol(PRUint32 aColIdx)
+HTMLTableAccessible::UnselectCol(PRUint32 aColIdx)
 {
   RemoveRowsOrColumnsFromSelection(aColIdx,
                                    nsISelectionPrivate::TABLESELECTION_COLUMN,
                                    false);
 }
 
 nsresult
-nsHTMLTableAccessible::AddRowOrColumnToSelection(PRInt32 aIndex,
-                                                 PRUint32 aTarget)
+HTMLTableAccessible::AddRowOrColumnToSelection(PRInt32 aIndex, PRUint32 aTarget)
 {
   bool doSelectRow = (aTarget == nsISelectionPrivate::TABLESELECTION_ROW);
 
   nsITableLayout *tableLayout = GetTableLayout();
   NS_ENSURE_STATE(tableLayout);
 
   nsCOMPtr<nsIDOMElement> cellElm;
   PRInt32 startRowIdx, startColIdx, rowSpan, colSpan,
@@ -1161,19 +1158,19 @@ nsHTMLTableAccessible::AddRowOrColumnToS
       NS_ENSURE_SUCCESS(rv, rv);
     }
   }
 
   return NS_OK;
 }
 
 nsresult
-nsHTMLTableAccessible::RemoveRowsOrColumnsFromSelection(PRInt32 aIndex,
-                                                        PRUint32 aTarget,
-                                                        bool aIsOuter)
+HTMLTableAccessible::RemoveRowsOrColumnsFromSelection(PRInt32 aIndex,
+                                                      PRUint32 aTarget,
+                                                      bool aIsOuter)
 {
   nsITableLayout *tableLayout = GetTableLayout();
   NS_ENSURE_STATE(tableLayout);
 
   nsIPresShell* presShell(mDoc->PresShell());
   nsRefPtr<nsFrameSelection> tableSelection =
     const_cast<nsFrameSelection*>(presShell->ConstFrameSelection());
 
@@ -1193,30 +1190,29 @@ nsHTMLTableAccessible::RemoveRowsOrColum
                                                     endRowIdx, endColIdx);
 
   return tableSelection->RemoveCellsFromSelection(mContent,
                                                   startRowIdx, startColIdx,
                                                   endRowIdx, endColIdx);
 }
 
 nsITableLayout*
-nsHTMLTableAccessible::GetTableLayout()
+HTMLTableAccessible::GetTableLayout()
 {
   nsIFrame *frame = mContent->GetPrimaryFrame();
   if (!frame)
     return nsnull;
 
   nsITableLayout *tableLayout = do_QueryFrame(frame);
   return tableLayout;
 }
 
 nsresult
-nsHTMLTableAccessible::GetCellAt(PRInt32        aRowIndex,
-                                 PRInt32        aColIndex,
-                                 nsIDOMElement* &aCell)
+HTMLTableAccessible::GetCellAt(PRInt32 aRowIndex, PRInt32 aColIndex,
+                               nsIDOMElement*& aCell)
 {
   PRInt32 startRowIndex = 0, startColIndex = 0,
           rowSpan, colSpan, actualRowSpan, actualColSpan;
   bool isSelected;
 
   nsITableLayout *tableLayout = GetTableLayout();
   NS_ENSURE_STATE(tableLayout);
 
@@ -1225,17 +1221,17 @@ nsHTMLTableAccessible::GetCellAt(PRInt32
                   rowSpan, colSpan, actualRowSpan, actualColSpan, isSelected);
 
   if (rv == NS_TABLELAYOUT_CELL_NOT_FOUND)
     return NS_ERROR_INVALID_ARG;
   return rv;
 }
 
 void
-nsHTMLTableAccessible::Description(nsString& aDescription)
+HTMLTableAccessible::Description(nsString& aDescription)
 {
   // Helpful for debugging layout vs. data tables
   aDescription.Truncate();
   Accessible::Description(aDescription);
   if (!aDescription.IsEmpty())
     return;
 
   // Use summary as description if it weren't used as a name.
@@ -1260,18 +1256,17 @@ nsHTMLTableAccessible::Description(nsStr
     bool isProbablyForLayout = IsProbablyLayoutTable();
     aDescription = mLayoutHeuristic;
   }
   printf("\nTABLE: %s\n", NS_ConvertUTF16toUTF8(mLayoutHeuristic).get());
 #endif
 }
 
 bool
-nsHTMLTableAccessible::HasDescendant(const nsAString& aTagName,
-                                     bool aAllowEmpty)
+HTMLTableAccessible::HasDescendant(const nsAString& aTagName, bool aAllowEmpty)
 {
   nsCOMPtr<nsIDOMElement> tableElt(do_QueryInterface(mContent));
   NS_ENSURE_TRUE(tableElt, false);
 
   nsCOMPtr<nsIDOMNodeList> nodeList;
   tableElt->GetElementsByTagName(aTagName, getter_AddRefs(nodeList));
   NS_ENSURE_TRUE(nodeList, false);
 
@@ -1294,23 +1289,23 @@ nsHTMLTableAccessible::HasDescendant(con
     return true;
 
   // If we found more than one node then return true not depending on
   // aAllowEmpty flag.
   // XXX it might be dummy but bug 501375 where we changed this addresses
   // performance problems only. Note, currently 'aAllowEmpty' flag is used for
   // caption element only. On another hand we create accessible object for
   // the first entry of caption element (see
-  // nsHTMLTableAccessible::CacheChildren).
+  // HTMLTableAccessible::CacheChildren).
   nodeList->Item(1, getter_AddRefs(foundItem));
   return !!foundItem;
 }
 
 bool
-nsHTMLTableAccessible::IsProbablyLayoutTable()
+HTMLTableAccessible::IsProbablyLayoutTable()
 {
   // Implement a heuristic to determine if table is most likely used for layout
   // XXX do we want to look for rowspan or colspan, especialy that span all but a couple cells
   // at the beginning or end of a row/col, and especially when they occur at the edge of a table?
   // XXX expose this info via object attributes to AT-SPI
 
   // XXX For now debugging descriptions are always on via SHOW_LAYOUT_HEURISTIC
   // This will allow release trunk builds to be used by testers to refine the algorithm
@@ -1504,26 +1499,26 @@ nsHTMLTableAccessible::IsProbablyLayoutT
     RETURN_LAYOUT_ANSWER(true, "Has no borders, and has iframe, object, applet or iframe, typical of advertisements");
   }
 
   RETURN_LAYOUT_ANSWER(false, "no layout factor strong enough, so will guess data");
 }
 
 
 ////////////////////////////////////////////////////////////////////////////////
-// nsHTMLCaptionAccessible
+// HTMLCaptionAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 Relation
-nsHTMLCaptionAccessible::RelationByType(PRUint32 aType)
+HTMLCaptionAccessible::RelationByType(PRUint32 aType)
 {
   Relation rel = HyperTextAccessible::RelationByType(aType);
   if (aType == nsIAccessibleRelation::RELATION_LABEL_FOR)
     rel.AppendTarget(Parent());
 
   return rel;
 }
 
 role
-nsHTMLCaptionAccessible::NativeRole()
+HTMLCaptionAccessible::NativeRole()
 {
   return roles::CAPTION;
 }
rename from accessible/src/html/nsHTMLTableAccessible.h
rename to accessible/src/html/HTMLTableAccessible.h
--- a/accessible/src/html/nsHTMLTableAccessible.h
+++ b/accessible/src/html/HTMLTableAccessible.h
@@ -1,41 +1,44 @@
 /* -*- 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 _nsHTMLTableAccessible_H_
-#define _nsHTMLTableAccessible_H_
+#ifndef mozilla_a11y_HTMLTableAccessible_h__
+#define mozilla_a11y_HTMLTableAccessible_h__
 
 #include "HyperTextAccessibleWrap.h"
 #include "nsIAccessibleTable.h"
 #include "TableAccessible.h"
 #include "xpcAccessibleTable.h"
 
 class nsITableLayout;
 class nsITableCellLayout;
 
+namespace mozilla {
+namespace a11y {
+
 /**
  * HTML table cell accessible (html:td).
  */
-class nsHTMLTableCellAccessible : public HyperTextAccessibleWrap,
-                                  public nsIAccessibleTableCell
+class HTMLTableCellAccessible : public HyperTextAccessibleWrap,
+                                public nsIAccessibleTableCell
 {
 public:
-  nsHTMLTableCellAccessible(nsIContent* aContent, DocAccessible* aDoc);
+  HTMLTableCellAccessible(nsIContent* aContent, DocAccessible* aDoc);
 
   // nsISupports
   NS_DECL_ISUPPORTS_INHERITED
 
   // nsIAccessibleTableCell
   NS_DECL_NSIACCESSIBLETABLECELL
 
   // Accessible
-  virtual mozilla::a11y::role NativeRole();
+  virtual a11y::role NativeRole();
   virtual PRUint64 NativeState();
   virtual PRUint64 NativeInteractiveState() const;
   virtual nsresult GetAttributesInternal(nsIPersistentProperties *aAttributes);
 
 protected:
   /**
    * Return host table accessible.
    */
@@ -57,43 +60,42 @@ protected:
   nsresult GetHeaderCells(PRInt32 aRowOrColumnHeaderCell,
                           nsIArray **aHeaderCells);
 };
 
 
 /**
  * HTML table row/column header accessible (html:th or html:td@scope).
  */
-class nsHTMLTableHeaderCellAccessible : public nsHTMLTableCellAccessible
+class HTMLTableHeaderCellAccessible : public HTMLTableCellAccessible
 {
 public:
-  nsHTMLTableHeaderCellAccessible(nsIContent* aContent,
-                                  DocAccessible* aDoc);
+  HTMLTableHeaderCellAccessible(nsIContent* aContent, DocAccessible* aDoc);
 
   // Accessible
-  virtual mozilla::a11y::role NativeRole();
+  virtual a11y::role NativeRole();
 };
 
 
 /**
  * HTML table accessible (html:table).
  */
 
 // To turn on table debugging descriptions define SHOW_LAYOUT_HEURISTIC
 // This allow release trunk builds to be used by testers to refine the
 // data vs. layout heuristic
 // #define SHOW_LAYOUT_HEURISTIC
 
-class nsHTMLTableAccessible : public AccessibleWrap,
-                              public xpcAccessibleTable,
-                              public nsIAccessibleTable,
-                              public mozilla::a11y::TableAccessible
+class HTMLTableAccessible : public AccessibleWrap,
+                            public xpcAccessibleTable,
+                            public nsIAccessibleTable,
+                            public TableAccessible
 {
 public:
-  nsHTMLTableAccessible(nsIContent* aContent, DocAccessible* aDoc);
+  HTMLTableAccessible(nsIContent* aContent, DocAccessible* aDoc);
 
   NS_DECL_ISUPPORTS_INHERITED
 
   // nsIAccessible Table
   NS_DECL_OR_FORWARD_NSIACCESSIBLETABLE_WITH_XPCACCESSIBLETABLE
 
   // TableAccessible
   virtual Accessible* Caption();
@@ -110,22 +112,22 @@ public:
 
   // nsAccessNode
   virtual void Shutdown();
 
   // Accessible
   virtual mozilla::a11y::TableAccessible* AsTable() { return this; }
   virtual void Description(nsString& aDescription);
   virtual nsresult GetNameInternal(nsAString& aName);
-  virtual mozilla::a11y::role NativeRole();
+  virtual a11y::role NativeRole();
   virtual PRUint64 NativeState();
   virtual nsresult GetAttributesInternal(nsIPersistentProperties *aAttributes);
   virtual Relation RelationByType(PRUint32 aRelationType);
 
-  // nsHTMLTableAccessible
+  // HTMLTableAccessible
 
   /**
    * Retun cell element at the given row and column index.
    */
   nsresult GetCellAt(PRInt32 aRowIndex, PRInt32 aColIndex,
                      nsIDOMElement* &aCell);
 
   /**
@@ -133,17 +135,17 @@ public:
    */
   nsITableLayout* GetTableLayout();
 
 protected:
 
   // Accessible
   virtual void CacheChildren();
 
-  // nsHTMLTableAccessible
+  // HTMLTableAccessible
 
   /**
    * Add row or column to selection.
    *
    * @param aIndex   [in] index of row or column to be selected
    * @param aTarget  [in] indicates what should be selected, either row or column
    *                  (see nsISelectionPrivate)
    */
@@ -174,23 +176,26 @@ protected:
 #ifdef SHOW_LAYOUT_HEURISTIC
   nsString mLayoutHeuristic;
 #endif
 };
 
 /**
  * HTML caption accessible (html:caption).
  */
-class nsHTMLCaptionAccessible : public HyperTextAccessibleWrap
+class HTMLCaptionAccessible : public HyperTextAccessibleWrap
 {
 public:
-  nsHTMLCaptionAccessible(nsIContent* aContent, DocAccessible* aDoc) :
+  HTMLCaptionAccessible(nsIContent* aContent, DocAccessible* aDoc) :
     HyperTextAccessibleWrap(aContent, aDoc) { }
-  virtual ~nsHTMLCaptionAccessible() { }
+  virtual ~HTMLCaptionAccessible() { }
 
   // nsIAccessible
 
   // Accessible
-  virtual mozilla::a11y::role NativeRole();
+  virtual a11y::role NativeRole();
   virtual Relation RelationByType(PRUint32 aRelationType);
 };
 
-#endif  
+} // namespace a11y
+} // namespace mozilla
+
+#endif
--- a/accessible/src/html/Makefile.in
+++ b/accessible/src/html/Makefile.in
@@ -19,17 +19,17 @@ LIBXUL_LIBRARY = 1
 CPPSRCS = \
   HTMLCanvasAccessible.cpp \
   HTMLElementAccessibles.cpp \
   HTMLFormControlAccessible.cpp \
   HTMLImageMapAccessible.cpp \
   HTMLLinkAccessible.cpp \
   HTMLListAccessible.cpp \
   HTMLSelectAccessible.cpp \
-  nsHTMLTableAccessible.cpp \
+  HTMLTableAccessible.cpp \
   $(NULL)
 
 # we don't want the shared lib, but we want to force the creation of a static lib.
 FORCE_STATIC_LIB = 1
 
 include $(topsrcdir)/config/rules.mk
 
 LOCAL_INCLUDES = \
--- a/accessible/src/mac/AccessibleWrap.h
+++ b/accessible/src/mac/AccessibleWrap.h
@@ -104,13 +104,9 @@ private:
   /**
    * We have created our native. This does not mean there is one.
    * This can never go back to false.
    * We need it because checking whether we need a native object cost time.
    */
   bool mNativeInited;  
 };
 
-// Define unsupported wrap classes here
-typedef class nsHTMLTableCellAccessible    nsHTMLTableCellAccessibleWrap;
-typedef class nsHTMLTableAccessible        nsHTMLTableAccessibleWrap;
-
 #endif
rename from accessible/src/mac/nsHTMLTableAccessibleWrap.h
rename to accessible/src/mac/HTMLTableAccessibleWrap.h
--- a/accessible/src/mac/nsHTMLTableAccessibleWrap.h
+++ b/accessible/src/mac/HTMLTableAccessibleWrap.h
@@ -1,18 +1,24 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim:expandtab:shiftwidth=2:tabstop=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 _NSHTMLTABLEACCESSIBLEWRAP_H
-#define _NSHTMLTABLEACCESSIBLEWRAP_H
+#ifndef mozilla_a11y_HTMLTableAccessibleWrap_h__
+#define mozilla_a11y_HTMLTableAccessibleWrap_h__
+
+#include "HTMLTableAccessible.h"
 
-#include "nsHTMLTableAccessible.h"
+namespace mozilla {
+namespace a11y {
 
-typedef class nsHTMLTableAccessible nsHTMLTableAccessibleWrap;
-typedef class nsHTMLTableCellAccessible nsHTMLTableCellAccessibleWrap;
-typedef class nsHTMLTableHeaderCellAccessible nsHTMLTableHeaderCellAccessibleWrap;
+typedef class HTMLTableAccessible HTMLTableAccessibleWrap;
+typedef class HTMLTableCellAccessible HTMLTableCellAccessibleWrap;
+typedef class HTMLTableHeaderCellAccessible HTMLTableHeaderCellAccessibleWrap;
+
+} // namespace a11y
+} // namespace mozilla
 
 #endif
 
rename from accessible/src/msaa/nsHTMLTableAccessibleWrap.cpp
rename to accessible/src/msaa/HTMLTableAccessibleWrap.cpp
--- a/accessible/src/msaa/nsHTMLTableAccessibleWrap.cpp
+++ b/accessible/src/msaa/HTMLTableAccessibleWrap.cpp
@@ -1,43 +1,45 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim:expandtab:shiftwidth=2:tabstop=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 "nsHTMLTableAccessibleWrap.h"
+#include "HTMLTableAccessibleWrap.h"
+
+using namespace mozilla::a11y;
 
 ////////////////////////////////////////////////////////////////////////////////
-// nsHTMLTableAccessibleWrap
+// HTMLTableAccessibleWrap
 ////////////////////////////////////////////////////////////////////////////////
 
-NS_IMPL_ISUPPORTS_INHERITED0(nsHTMLTableAccessibleWrap,
-                             nsHTMLTableAccessible)
+NS_IMPL_ISUPPORTS_INHERITED0(HTMLTableAccessibleWrap,
+                             HTMLTableAccessible)
 
-IMPL_IUNKNOWN_INHERITED1(nsHTMLTableAccessibleWrap,
+IMPL_IUNKNOWN_INHERITED1(HTMLTableAccessibleWrap,
                          AccessibleWrap,
                          CAccessibleTable)
 
 
 ////////////////////////////////////////////////////////////////////////////////
-// nsHTMLTableCellAccessibleWrap
+// HTMLTableCellAccessibleWrap
 ////////////////////////////////////////////////////////////////////////////////
 
-NS_IMPL_ISUPPORTS_INHERITED0(nsHTMLTableCellAccessibleWrap,
-                             nsHTMLTableCellAccessible)
+NS_IMPL_ISUPPORTS_INHERITED0(HTMLTableCellAccessibleWrap,
+                             HTMLTableCellAccessible)
 
-IMPL_IUNKNOWN_INHERITED1(nsHTMLTableCellAccessibleWrap,
+IMPL_IUNKNOWN_INHERITED1(HTMLTableCellAccessibleWrap,
                          HyperTextAccessibleWrap,
                          CAccessibleTableCell)
 
 
 ////////////////////////////////////////////////////////////////////////////////
-// nsHTMLTableCellAccessibleWrap
+// HTMLTableCellAccessibleWrap
 ////////////////////////////////////////////////////////////////////////////////
 
-NS_IMPL_ISUPPORTS_INHERITED0(nsHTMLTableHeaderCellAccessibleWrap,
-                             nsHTMLTableHeaderCellAccessible)
+NS_IMPL_ISUPPORTS_INHERITED0(HTMLTableHeaderCellAccessibleWrap,
+                             HTMLTableHeaderCellAccessible)
 
-IMPL_IUNKNOWN_INHERITED1(nsHTMLTableHeaderCellAccessibleWrap,
+IMPL_IUNKNOWN_INHERITED1(HTMLTableHeaderCellAccessibleWrap,
                          HyperTextAccessibleWrap,
                          CAccessibleTableCell)
rename from accessible/src/msaa/nsHTMLTableAccessibleWrap.h
rename to accessible/src/msaa/HTMLTableAccessibleWrap.h
--- a/accessible/src/msaa/nsHTMLTableAccessibleWrap.h
+++ b/accessible/src/msaa/HTMLTableAccessibleWrap.h
@@ -1,74 +1,80 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim:expandtab:shiftwidth=2:tabstop=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 _NSHTMLTABLEACCESSIBLEWRAP_H
-#define _NSHTMLTABLEACCESSIBLEWRAP_H
+#ifndef mozilla_a11y_HTMLTableAccessibleWrap_h__
+#define mozilla_a11y_HTMLTableAccessibleWrap_h__
 
-#include "nsHTMLTableAccessible.h"
+#include "HTMLTableAccessible.h"
 
 #include "CAccessibleTable.h"
 #include "CAccessibleTableCell.h"
 
+namespace mozilla {
+namespace a11y {
+
 /**
- * IA2 wrapper class for nsHTMLTableAccessible implementing IAccessibleTable
+ * IA2 wrapper class for HTMLTableAccessible implementing IAccessibleTable
  * and IAccessibleTable2 interfaces.
  */
-class nsHTMLTableAccessibleWrap : public nsHTMLTableAccessible,
-                                  public CAccessibleTable
+class HTMLTableAccessibleWrap : public HTMLTableAccessible,
+                                public CAccessibleTable
 {
 public:
-  nsHTMLTableAccessibleWrap(nsIContent* aContent, DocAccessible* aDoc) :
-    nsHTMLTableAccessible(aContent, aDoc) {}
+  HTMLTableAccessibleWrap(nsIContent* aContent, DocAccessible* aDoc) :
+    HTMLTableAccessible(aContent, aDoc) {}
 
   // IUnknown
   DECL_IUNKNOWN_INHERITED
 
   // nsISupports
   NS_DECL_ISUPPORTS_INHERITED
 };
 
 
 /**
- * IA2 wrapper class for nsHTMLTableCellAccessible implementing
+ * IA2 wrapper class for HTMLTableCellAccessible implementing
  * IAccessibleTableCell interface.
  */
-class nsHTMLTableCellAccessibleWrap : public nsHTMLTableCellAccessible,
-                                      public CAccessibleTableCell
+class HTMLTableCellAccessibleWrap : public HTMLTableCellAccessible,
+                                    public CAccessibleTableCell
 {
 public:
-  nsHTMLTableCellAccessibleWrap(nsIContent* aContent, DocAccessible* aDoc) :
-    nsHTMLTableCellAccessible(aContent, aDoc) {}
+  HTMLTableCellAccessibleWrap(nsIContent* aContent, DocAccessible* aDoc) :
+    HTMLTableCellAccessible(aContent, aDoc) {}
 
   // IUnknown
   DECL_IUNKNOWN_INHERITED
 
   // nsISupports
   NS_DECL_ISUPPORTS_INHERITED
 };
 
 
 /**
- * IA2 wrapper class for nsHTMLTableHeaderCellAccessible implementing
+ * IA2 wrapper class for HTMLTableHeaderCellAccessible implementing
  * IAccessibleTableCell interface.
  */
-class nsHTMLTableHeaderCellAccessibleWrap : public nsHTMLTableHeaderCellAccessible,
-                                            public CAccessibleTableCell
+class HTMLTableHeaderCellAccessibleWrap : public HTMLTableHeaderCellAccessible,
+                                          public CAccessibleTableCell
 {
 public:
-  nsHTMLTableHeaderCellAccessibleWrap(nsIContent* aContent,
-                                      DocAccessible* aDoc) :
-    nsHTMLTableHeaderCellAccessible(aContent, aDoc) {}
+  HTMLTableHeaderCellAccessibleWrap(nsIContent* aContent,
+                                    DocAccessible* aDoc) :
+    HTMLTableHeaderCellAccessible(aContent, aDoc) {}
 
   // IUnknown
   DECL_IUNKNOWN_INHERITED
 
   // nsISupports
   NS_DECL_ISUPPORTS_INHERITED
 };
 
+} // namespace a11y
+} // namespace mozilla
+
 #endif
 
--- a/accessible/src/msaa/Makefile.in
+++ b/accessible/src/msaa/Makefile.in
@@ -15,24 +15,24 @@ EXPORT_LIBRARY = ..
 LIBXUL_LIBRARY = 1
 
 
 CPPSRCS = \
   AccessibleWrap.cpp \
   ApplicationAccessibleWrap.cpp \
   ARIAGridAccessibleWrap.cpp \
   DocAccessibleWrap.cpp \
+  HTMLTableAccessibleWrap.cpp \
   HyperTextAccessibleWrap.cpp \
   ImageAccessibleWrap.cpp \
   nsAccessNodeWrap.cpp \
   nsHTMLWin32ObjectAccessible.cpp \
   nsXULMenuAccessibleWrap.cpp \
   nsXULListboxAccessibleWrap.cpp \
   nsXULTreeGridAccessibleWrap.cpp \
-  nsHTMLTableAccessibleWrap.cpp \
   nsWinUtils.cpp \
   CAccessibleText.cpp \
   CAccessibleEditableText.cpp \
   CAccessibleHyperlink.cpp \
   CAccessibleTable.cpp \
   CAccessibleTableCell.cpp \
   CAccessibleValue.cpp \
   Compatibility.cpp \
rename from accessible/src/other/nsHTMLTableAccessibleWrap.h
rename to accessible/src/other/HTMLTableAccessibleWrap.h
--- a/accessible/src/other/nsHTMLTableAccessibleWrap.h
+++ b/accessible/src/other/HTMLTableAccessibleWrap.h
@@ -1,18 +1,24 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim:expandtab:shiftwidth=2:tabstop=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 _NSHTMLTABLEACCESSIBLEWRAP_H
-#define _NSHTMLTABLEACCESSIBLEWRAP_H
+#ifndef mozilla_a11y_HTMLTableAccessibleWrap_h__
+#define mozilla_a11y_HTMLTableAccessibleWrap_h__
+
+#include "HTMLTableAccessible.h"
 
-#include "nsHTMLTableAccessible.h"
+namespace mozilla {
+namespace a11y {
 
-typedef class nsHTMLTableAccessible nsHTMLTableAccessibleWrap;
-typedef class nsHTMLTableCellAccessible nsHTMLTableCellAccessibleWrap;
-typedef class nsHTMLTableHeaderCellAccessible nsHTMLTableHeaderCellAccessibleWrap;
+typedef class HTMLTableAccessible HTMLTableAccessibleWrap;
+typedef class HTMLTableCellAccessible HTMLTableCellAccessibleWrap;
+typedef class HTMLTableHeaderCellAccessible HTMLTableHeaderCellAccessibleWrap;
+
+} // namespace a11y
+} // namespace mozilla
 
 #endif
 
--- a/accessible/tests/mochitest/attributes/test_text.html
+++ b/accessible/tests/mochitest/attributes/test_text.html
@@ -1,15 +1,20 @@
 <html>
 
 <head>
   <title>Text attributes tests</title>
   <meta charset="utf-8" />
   <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css" />
 
+  <style type="text/css">
+    .gencontent:before { content: "*"; }
+    .gencontent:after  { content: "*"; }
+  </style>
+
   <script type="application/javascript"
           src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
 
   <script type="application/javascript"
           src="../common.js"></script>
   <script type="application/javascript"
           src="../attributes.js"></script>
   <script type="application/javascript"
@@ -501,16 +506,29 @@
       testTextAttrs(ID, 34, attrs, defAttrs, 34, 39);
 
       attrs = {
         "text-line-through-style": "wavy",
         "text-line-through-color": "rgb(0, 0, 0)",
       };
       testTextAttrs(ID, 39, attrs, defAttrs, 39, 44);
 
+      //////////////////////////////////////////////////////////////////////////
+      // area18, "auto-generation text" tests
+      ID = "area18";
+      defAttrs = buildDefaultTextAttrs(ID, "12pt");
+      testDefaultTextAttrs(ID, defAttrs);
+
+      var attrs = {
+        "auto-generated": "true"
+      };
+      testTextAttrs(ID, 0, attrs, defAttrs, 0, 2);
+      testTextAttrs(ID, 2, { }, defAttrs, 2, 6);
+      testTextAttrs(ID, 6, attrs, defAttrs, 6, 7);
+
       SimpleTest.finish();
     }
 
     SimpleTest.waitForExplicitFinish();
     addA11yLoadEvent(doTest);
   </script>
 </head>
 <body style="font-size: 12pt">
@@ -535,16 +553,21 @@
      title="expose text-underline-color and text-line-through-color text attributes">
     Mozilla Bug 523304
   </a>
   <a target="_blank"
      href="https://bugzilla.mozilla.org/show_bug.cgi?id=735645"
      title="expose sub and sup elements in text attributes">
     Mozilla Bug 735645
   </a>
+  <a target="_blank"
+     href="https://bugzilla.mozilla.org/show_bug.cgi?id=445516"
+     title="Support auto-generated text attribute on bullet lists">
+    Mozilla Bug 445516
+  </a>
   <p id="display"></p>
   <div id="content" style="display: none"></div>
   <pre id="test">
   </pre>
 
   <p id="area1" style="font-size: smaller">Normal <b>Bold</b> Normal</p>
   <p id="area2" style="font-size: 120%">Normal <b>Bold <i>Italic </i>Bold</b> Normal</p>
   <p id="area3" style="background-color: blue;">
@@ -639,10 +662,15 @@
     <span style="-moz-text-decoration-line: underline;">underline
     </span><span style="text-decoration: underline; -moz-text-decoration-color: blue;">blue
     </span><span style="text-decoration: underline; -moz-text-decoration-style: dotted;">dotted
     </span><span style="-moz-text-decoration-line: line-through;">linethrough
     </span><span style="text-decoration: line-through; -moz-text-decoration-color: blue;">blue
     </span><span style="text-decoration: line-through; -moz-text-decoration-style: wavy;">wavy
     </span>
   </p>
+
+  <ul>
+    <li id="area18" class="gencontent">item</li>
+  </ul>
+
 </body>
 </html>
--- a/accessible/tests/mochitest/role.js
+++ b/accessible/tests/mochitest/role.js
@@ -6,16 +6,17 @@ const ROLE_ANIMATION = nsIAccessibleRole
 const ROLE_APPLICATION = nsIAccessibleRole.ROLE_APPLICATION;
 const ROLE_APP_ROOT = nsIAccessibleRole.ROLE_APP_ROOT;
 const ROLE_AUTOCOMPLETE = nsIAccessibleRole.ROLE_AUTOCOMPLETE;
 const ROLE_BUTTONDROPDOWNGRID = nsIAccessibleRole.ROLE_BUTTONDROPDOWNGRID;
 const ROLE_CANVAS = nsIAccessibleRole.ROLE_CANVAS;
 const ROLE_CAPTION = nsIAccessibleRole.ROLE_CAPTION;
 const ROLE_CELL = nsIAccessibleRole.ROLE_CELL;
 const ROLE_CHECKBUTTON = nsIAccessibleRole.ROLE_CHECKBUTTON;
+const ROLE_CHECK_MENU_ITEM = nsIAccessibleRole.ROLE_CHECK_MENU_ITEM;
 const ROLE_CHROME_WINDOW = nsIAccessibleRole.ROLE_CHROME_WINDOW;
 const ROLE_COMBOBOX = nsIAccessibleRole.ROLE_COMBOBOX;
 const ROLE_COMBOBOX_LIST = nsIAccessibleRole.ROLE_COMBOBOX_LIST;
 const ROLE_COMBOBOX_OPTION = nsIAccessibleRole.ROLE_COMBOBOX_OPTION;
 const ROLE_COLUMNHEADER = nsIAccessibleRole.ROLE_COLUMNHEADER;
 const ROLE_DEFINITION = nsIAccessibleRole.ROLE_DEFINITION;
 const ROLE_DEFINITION_LIST = nsIAccessibleRole.ROLE_DEFINITION_LIST;
 const ROLE_DIALOG = nsIAccessibleRole.ROLE_DIALOG;
@@ -33,16 +34,17 @@ const ROLE_HEADER = nsIAccessibleRole.RO
 const ROLE_HEADING = nsIAccessibleRole.ROLE_HEADING;
 const ROLE_IMAGE_MAP = nsIAccessibleRole.ROLE_IMAGE_MAP;
 const ROLE_INTERNAL_FRAME = nsIAccessibleRole.ROLE_INTERNAL_FRAME;
 const ROLE_LABEL = nsIAccessibleRole.ROLE_LABEL;
 const ROLE_LINK = nsIAccessibleRole.ROLE_LINK;
 const ROLE_LIST = nsIAccessibleRole.ROLE_LIST;
 const ROLE_LISTBOX = nsIAccessibleRole.ROLE_LISTBOX;
 const ROLE_LISTITEM = nsIAccessibleRole.ROLE_LISTITEM;
+const ROLE_MENUBAR = nsIAccessibleRole.ROLE_MENUBAR;
 const ROLE_MENUITEM = nsIAccessibleRole.ROLE_MENUITEM;
 const ROLE_MENUPOPUP = nsIAccessibleRole.ROLE_MENUPOPUP;
 const ROLE_NOTHING = nsIAccessibleRole.ROLE_NOTHING;
 const ROLE_NOTE = nsIAccessibleRole.ROLE_NOTE;
 const ROLE_OPTION = nsIAccessibleRole.ROLE_OPTION;
 const ROLE_OUTLINE = nsIAccessibleRole.ROLE_OUTLINE;
 const ROLE_OUTLINEITEM = nsIAccessibleRole.ROLE_OUTLINEITEM;
 const ROLE_PAGETAB = nsIAccessibleRole.ROLE_PAGETAB;
@@ -50,24 +52,27 @@ const ROLE_PAGETABLIST = nsIAccessibleRo
 const ROLE_PANE = nsIAccessibleRole.ROLE_PANE;
 const ROLE_PARAGRAPH = nsIAccessibleRole.ROLE_PARAGRAPH;
 const ROLE_PARENT_MENUITEM = nsIAccessibleRole.ROLE_PARENT_MENUITEM;
 const ROLE_PASSWORD_TEXT = nsIAccessibleRole.ROLE_PASSWORD_TEXT;
 const ROLE_PROGRESSBAR = nsIAccessibleRole.ROLE_PROGRESSBAR;
 const ROLE_PROPERTYPAGE = nsIAccessibleRole.ROLE_PROPERTYPAGE;
 const ROLE_PUSHBUTTON = nsIAccessibleRole.ROLE_PUSHBUTTON;
 const ROLE_RADIOBUTTON = nsIAccessibleRole.ROLE_RADIOBUTTON;
+const ROLE_RADIO_MENU_ITEM = nsIAccessibleRole.ROLE_RADIO_MENU_ITEM;
 const ROLE_RICH_OPTION = nsIAccessibleRole.ROLE_RICH_OPTION;
 const ROLE_ROW = nsIAccessibleRole.ROLE_ROW;
 const ROLE_ROWHEADER = nsIAccessibleRole.ROLE_ROWHEADER;
 const ROLE_SCROLLBAR = nsIAccessibleRole.ROLE_SCROLLBAR;
 const ROLE_SECTION = nsIAccessibleRole.ROLE_SECTION;
 const ROLE_SEPARATOR = nsIAccessibleRole.ROLE_SEPARATOR;
 const ROLE_SLIDER = nsIAccessibleRole.ROLE_SLIDER;
+const ROLE_SPINBUTTON = nsIAccessibleRole.ROLE_SPINBUTTON;
 const ROLE_STATICTEXT = nsIAccessibleRole.ROLE_STATICTEXT;
+const ROLE_STATUSBAR = nsIAccessibleRole.ROLE_STATUSBAR;
 const ROLE_TABLE = nsIAccessibleRole.ROLE_TABLE;
 const ROLE_TERM = nsIAccessibleRole.ROLE_TERM;
 const ROLE_TEXT_CONTAINER = nsIAccessibleRole.ROLE_TEXT_CONTAINER;
 const ROLE_TEXT_LEAF = nsIAccessibleRole.ROLE_TEXT_LEAF;
 const ROLE_TOGGLE_BUTTON = nsIAccessibleRole.ROLE_TOGGLE_BUTTON;
 const ROLE_TOOLBAR = nsIAccessibleRole.ROLE_TOOLBAR;
 const ROLE_TOOLTIP = nsIAccessibleRole.ROLE_TOOLTIP;
 const ROLE_TREE_TABLE = nsIAccessibleRole.ROLE_TREE_TABLE;
--- a/accessible/tests/mochitest/role/test_aria.html
+++ b/accessible/tests/mochitest/role/test_aria.html
@@ -12,16 +12,70 @@
           src="../common.js"></script>
   <script type="application/javascript"
           src="../role.js"></script>
 
   <script type="application/javascript">
 
     function doTest()
     {
+      // ARIA role map.
+      testRole("aria_alert", ROLE_ALERT);
+      testRole("aria_alertdialog", ROLE_DIALOG);
+      testRole("aria_application", ROLE_APPLICATION);
+      testRole("aria_article", ROLE_DOCUMENT);
+      testRole("aria_button", ROLE_PUSHBUTTON);
+      testRole("aria_checkbox", ROLE_CHECKBUTTON);
+      testRole("aria_columnheader", ROLE_COLUMNHEADER);
+      testRole("aria_combobox", ROLE_COMBOBOX);
+      testRole("aria_dialog", ROLE_DIALOG);
+      testRole("aria_directory", ROLE_LIST);
+      testRole("aria_document", ROLE_DOCUMENT);
+      testRole("aria_form", ROLE_FORM);
+      testRole("aria_grid", ROLE_TABLE);
+      testRole("aria_gridcell", ROLE_GRID_CELL);
+      testRole("aria_group", ROLE_GROUPING);
+      testRole("aria_heading", ROLE_HEADING);
+      testRole("aria_img", ROLE_GRAPHIC);
+      testRole("aria_link", ROLE_LINK);
+      testRole("aria_list", ROLE_LIST);
+      testRole("aria_listbox", ROLE_LISTBOX);
+      testRole("aria_listitem", ROLE_LISTITEM);
+      testRole("aria_log", ROLE_TEXT_CONTAINER); // weak role
+      testRole("aria_marquee", ROLE_ANIMATION);
+      testRole("aria_math", ROLE_FLAT_EQUATION);
+      testRole("aria_menu", ROLE_MENUPOPUP);
+      testRole("aria_menubar", ROLE_MENUBAR);
+      testRole("aria_menuitem", ROLE_MENUITEM);
+      testRole("aria_menuitemcheckbox", ROLE_CHECK_MENU_ITEM);
+      testRole("aria_menuitemradio", ROLE_RADIO_MENU_ITEM);
+      testRole("aria_note", ROLE_NOTE);
+      testRole("aria_presentation", ROLE_TEXT_CONTAINER); // weak role
+      testRole("aria_progressbar", ROLE_PROGRESSBAR);
+      testRole("aria_radio", ROLE_RADIOBUTTON);
+      testRole("aria_radiogroup", ROLE_GROUPING);
+      testRole("aria_region", ROLE_PANE);
+      testRole("aria_row", ROLE_ROW);
+      testRole("aria_rowheader", ROLE_ROWHEADER);
+      testRole("aria_scrollbar", ROLE_SCROLLBAR);
+      testRole("aria_separator", ROLE_SEPARATOR);
+      testRole("aria_slider", ROLE_SLIDER);
+      testRole("aria_spinbutton", ROLE_SPINBUTTON);
+      testRole("aria_status", ROLE_STATUSBAR);
+      testRole("aria_tab", ROLE_PAGETAB);
+      testRole("aria_tablist", ROLE_PAGETABLIST);
+      testRole("aria_tabpanel", ROLE_PROPERTYPAGE);
+      testRole("aria_textbox", ROLE_ENTRY);
+      testRole("aria_timer", ROLE_TEXT_CONTAINER); // weak role
+      testRole("aria_toolbar", ROLE_TOOLBAR);
+      testRole("aria_tooltip", ROLE_TOOLTIP);
+      testRole("aria_tree", ROLE_OUTLINE);
+      testRole("aria_treegrid", ROLE_TREE_TABLE);
+      testRole("aria_treeitem", ROLE_OUTLINEITEM);
+
       // Note:
       // The phrase "weak foo" here means that there is no good foo-to-platform
       // role mapping. Similarly "strong foo" means there is a good foo-to-
       // platform role mapping.
 
       testRole("articlemain", ROLE_DOCUMENT);
       testRole("articleform", ROLE_FORM);
 
@@ -119,16 +173,69 @@
      href="https://bugzilla.mozilla.org/show_bug.cgi?id=735645">
     Bug 735645
   </a>
   <p id="display"></p>
   <div id="content" style="display: none"></div>
   <pre id="test">
   </pre>
 
+  <span id="aria_alert" role="alert"/>
+  <span id="aria_alertdialog" role="alertdialog"/>
+  <span id="aria_application" role="application"/>
+  <span id="aria_article" role="article"/>
+  <span id="aria_button" role="button"/>
+  <span id="aria_checkbox" role="checkbox"/>
+  <span id="aria_columnheader" role="columnheader"/>
+  <span id="aria_combobox" role="combobox"/>
+  <span id="aria_dialog" role="dialog"/>
+  <span id="aria_directory" role="directory"/>
+  <span id="aria_document" role="document"/>
+  <span id="aria_form" role="form"/>
+  <span id="aria_grid" role="grid"/>
+  <span id="aria_gridcell" role="gridcell"/>
+  <span id="aria_group" role="group"/>
+  <span id="aria_heading" role="heading"/>
+  <span id="aria_img" role="img"/>
+  <span id="aria_link" role="link"/>
+  <span id="aria_list" role="list"/>
+  <span id="aria_listbox" role="listbox"/>
+  <span id="aria_listitem" role="listitem"/>
+  <span id="aria_log" role="log"/>
+  <span id="aria_marquee" role="marquee"/>
+  <span id="aria_math" role="math"/>
+  <span id="aria_menu" role="menu"/>
+  <span id="aria_menubar" role="menubar"/>
+  <span id="aria_menuitem" role="menuitem"/>
+  <span id="aria_menuitemcheckbox" role="menuitemcheckbox"/>
+  <span id="aria_menuitemradio" role="menuitemradio"/>
+  <span id="aria_note" role="note"/>
+  <span id="aria_presentation" role="presentation" tabindex="0"/>
+  <span id="aria_progressbar" role="progressbar"/>
+  <span id="aria_radio" role="radio"/>
+  <span id="aria_radiogroup" role="radiogroup"/>
+  <span id="aria_region" role="region"/>
+  <span id="aria_row" role="row"/>
+  <span id="aria_rowheader" role="rowheader"/>
+  <span id="aria_scrollbar" role="scrollbar"/>
+  <span id="aria_separator" role="separator"/>
+  <span id="aria_slider" role="slider"/>
+  <span id="aria_spinbutton" role="spinbutton"/>
+  <span id="aria_status" role="status"/>
+  <span id="aria_tab" role="tab"/>
+  <span id="aria_tablist" role="tablist"/>
+  <span id="aria_tabpanel" role="tabpanel"/>
+  <span id="aria_textbox" role="textbox"/>
+  <span id="aria_timer" role="timer"/>
+  <span id="aria_toolbar" role="toolbar"/>
+  <span id="aria_tooltip" role="tooltip"/>
+  <span id="aria_tree" role="tree"/>
+  <span id="aria_treegrid" role="treegrid"/>
+  <span id="aria_treeitem" role="treeitem"/>
+
   <article id="articlemain" role="main">a main area</article>
   <article id="articleform" role="form">a form area</article>
 
   <div id="testArticle" role="article" title="Test article">
     <p>This is a paragraph inside the article.</p>
   </div>
 
   <!-- "live" roles -->
--- a/accessible/tests/mochitest/table/test_layoutguess.html
+++ b/accessible/tests/mochitest/table/test_layoutguess.html
@@ -1,12 +1,12 @@
 <html>
 <!-- https://bugzilla.mozilla.org/show_bug.cgi?id=495388 -->
 <head>
-  <title>test nsHTMLTableAccessible::IsProbablyForLayout implementation</title>
+  <title>test HTMLTableAccessible::IsProbablyForLayout implementation</title>
   <link rel="stylesheet" type="text/css"
         href="chrome://mochikit/content/tests/SimpleTest/test.css" />
 
   <script type="application/javascript"
           src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
 
   <script type="application/javascript"
           src="../common.js"></script>
--- a/b2g/app/b2g.js
+++ b/b2g/app/b2g.js
@@ -482,8 +482,14 @@ pref("extensions.getAddons.cache.enabled
 // Context Menu
 pref("ui.click_hold_context_menus", true);
 pref("ui.click_hold_context_menus.delay", 1000);
 
 // Enable device storage
 pref("device.storage.enabled", true);
 
 pref("media.plugins.enabled", true);
+
+// Disable printing (particularly, window.print())
+pref("dom.disable_window_print", true);
+
+// Disable window.showModalDialog
+pref("dom.disable_window_showModalDialog", true);
--- a/b2g/chrome/content/shell.js
+++ b/b2g/chrome/content/shell.js
@@ -122,17 +122,17 @@ var shell = {
 
     addPermissions(domains.split(","));
 
     // Load webapi.js as a frame script
     let webapiUrl = 'chrome://browser/content/webapi.js';
     try {
       messageManager.loadFrameScript(webapiUrl, true);
     } catch (e) {
-      dump('Error loading ' + webapiUrl + ' as a frame script: ' + e + '\n');
+      dump('shell.js: Error loading ' + webapiUrl + ' as a frame script: ' + e + '\n');
     }
 
     CustomEventManager.init();
 
     WebappsHelper.init();
 
     let browser = this.contentBrowser;
     browser.homePage = homeURL;
@@ -336,26 +336,16 @@ nsBrowserAccess.prototype = {
     throw new Error('Not Implemented');
   },
 
   isTabContentWindow: function isTabContentWindow(contentWindow) {
     return contentWindow == window;
   }
 };
 
-// Pipe `console` log messages to the nsIConsoleService which writes them
-// to logcat.
-Services.obs.addObserver(function onConsoleAPILogEvent(subject, topic, data) {
-  let message = subject.wrappedJSObject;
-  let prefix = "Content JS " + message.level.toUpperCase() +
-               " at " + message.filename + ":" + message.lineNumber +
-               " in " + (message.functionName || "anonymous") + ": ";
-  Services.console.logStringMessage(prefix + Array.join(message.arguments, " "));
-}, "console-api-log-event", false);
-
 (function Repl() {
   if (!Services.prefs.getBoolPref('b2g.remote-js.enabled')) {
     return;
   }
   const prompt = 'JS> ';
   let output;
   let reader = {
     onInputStreamReady : function repl_readInput(input) {
--- a/b2g/components/B2GComponents.manifest
+++ b/b2g/components/B2GComponents.manifest
@@ -24,8 +24,13 @@ contract @mozilla.org/updates/update-pro
 component {397a7fdf-2254-47be-b74e-76625a1a66d5} MozKeyboard.js
 contract @mozilla.org/b2g-keyboard;1 {397a7fdf-2254-47be-b74e-76625a1a66d5}
 category JavaScript-navigator-property mozKeyboard @mozilla.org/b2g-keyboard;1
 
 # DirectoryProvider.js
 component {9181eb7c-6f87-11e1-90b1-4f59d80dd2e5} DirectoryProvider.js
 contract @mozilla.org/browser/directory-provider;1 {9181eb7c-6f87-11e1-90b1-4f59d80dd2e5}
 category xpcom-directory-providers browser-directory-provider @mozilla.org/browser/directory-provider;1
+
+# ProcessGlobal.js
+component {1a94c87a-5ece-4d11-91e1-d29c29f21b28} ProcessGlobal.js
+contract @mozilla.org/b2g-process-global;1 {1a94c87a-5ece-4d11-91e1-d29c29f21b28}
+category app-startup ProcessGlobal service,@mozilla.org/b2g-process-global;1
--- a/b2g/components/Makefile.in
+++ b/b2g/components/Makefile.in
@@ -12,21 +12,22 @@ include $(DEPTH)/config/autoconf.mk
 MODULE = B2GComponents
 XPIDL_MODULE = B2GComponents
 
 XPIDLSRCS = \
         b2g.idl \
         $(NULL)
 
 EXTRA_PP_COMPONENTS = \
+        AlertsService.js \
         B2GComponents.manifest \
         CameraContent.js \
-        AlertsService.js \
         ContentPermissionPrompt.js \
+        DirectoryProvider.js \
         MozKeyboard.js \
-        DirectoryProvider.js \
+        ProcessGlobal.js \
         $(NULL)
 
 ifdef MOZ_UPDATER
 EXTRA_PP_COMPONENTS += UpdatePrompt.js
 endif
 
 include $(topsrcdir)/config/rules.mk
new file mode 100644
--- /dev/null
+++ b/b2g/components/ProcessGlobal.js
@@ -0,0 +1,74 @@
+/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- /
+/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+'use strict';
+
+/**
+ * This code exists to be a "grab bag" of global code that needs to be
+ * loaded per B2G process, but doesn't need to directly interact with
+ * web content.
+ *
+ * (It's written as an XPCOM service because it needs to watch
+ * app-startup.)
+ */
+
+const Cc = Components.classes;
+const Ci = Components.interfaces;
+const Cu = Components.utils;
+const kWebApiShimFile = 'chrome://browser/content/webapi.js';
+
+Cu.import('resource://gre/modules/Services.jsm');
+Cu.import('resource://gre/modules/XPCOMUtils.jsm');
+
+function debug(msg) {
+  log(msg);
+}
+function log(msg) {
+  // This file implements console.log(), so use dump().
+  //dump('ProcessGlobal: ' + msg + '\n');
+}
+
+function ProcessGlobal() {}
+ProcessGlobal.prototype = {
+  classID: Components.ID('{1a94c87a-5ece-4d11-91e1-d29c29f21b28}'),
+  QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver,
+                                         Ci.nsISupportsWeakReference]),
+
+  observe: function pg_observe(subject, topic, data) {
+    switch (topic) {
+    case 'app-startup': {
+      Services.obs.addObserver(this, 'console-api-log-event', false);
+      Services.obs.addObserver(this, 'in-process-browser-frame-shown', false);
+      Services.obs.addObserver(this, 'remote-browser-frame-shown', false);
+      break;
+    }
+    case 'console-api-log-event': {
+      // Pipe `console` log messages to the nsIConsoleService which
+      // writes them to logcat on Gonk.
+      let message = subject.wrappedJSObject;
+      let prefix = ('Content JS ' + message.level.toUpperCase() +
+                    ' at ' + message.filename + ':' + message.lineNumber +
+                    ' in ' + (message.functionName || 'anonymous') + ': ');
+      Services.console.logStringMessage(prefix + Array.join(message.arguments,
+                                                            ' '));
+      break;
+    }
+    case 'remote-browser-frame-shown':
+    case 'in-process-browser-frame-shown': {
+      let frameLoader = subject.QueryInterface(Ci.nsIFrameLoader);
+      let mm = frameLoader.messageManager;
+      try {
+        mm.loadFrameScript(kWebApiShimFile, true);
+      } catch (e) {
+        log('Error loading ' + kWebApiShimFile + ' as frame script: ' + e + '\n');
+      }
+      break;
+    }
+    }
+  },
+};
+
+var NSGetFactory = XPCOMUtils.generateNSGetFactory([ProcessGlobal]);
--- a/b2g/installer/package-manifest.in
+++ b/b2g/installer/package-manifest.in
@@ -652,8 +652,9 @@ bin/components/@DLL_PREFIX@nkgnomevfs@DL
 @BINPATH@/components/marionettecomponent.js
 @BINPATH@/components/AlertsService.js
 @BINPATH@/components/ContentPermissionPrompt.js
 #ifdef MOZ_UPDATER
 @BINPATH@/components/UpdatePrompt.js
 #endif
 @BINPATH@/components/MozKeyboard.js
 @BINPATH@/components/DirectoryProvider.js
+@BINPATH@/components/ProcessGlobal.js
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -7162,35 +7162,19 @@ let gPrivateBrowsingUI = {
   },
 
   /**
    * These accessors are used to support per-window Private Browsing mode.
    * For now the getter returns nsIPrivateBrowsingService.privateBrowsingEnabled,
    * and the setter should only be used in tests.
    */
   get privateWindow() {
-    return window.QueryInterface(Ci.nsIInterfaceRequestor)
-                 .getInterface(Ci.nsIWebNavigation)
-                 .QueryInterface(Ci.nsIDocShellTreeItem)
-                 .treeOwner
-                 .QueryInterface(Ci.nsIInterfaceRequestor)
-                 .getInterface(Ci.nsIXULWindow)
-                 .docShell.QueryInterface(Ci.nsILoadContext)
-                 .usePrivateBrowsing;
-  },
-
-  set privateWindow(val) {
-    return window.QueryInterface(Ci.nsIInterfaceRequestor)
-                 .getInterface(Ci.nsIWebNavigation)
-                 .QueryInterface(Ci.nsIDocShellTreeItem)
-                 .treeOwner
-                 .QueryInterface(Ci.nsIInterfaceRequestor)
-                 .getInterface(Ci.nsIXULWindow)
-                 .docShell.QueryInterface(Ci.nsILoadContext)
-                 .usePrivateBrowsing = val;
+    return gBrowser.selectedTab.linkedBrowser
+                               .docShell.QueryInterface(Ci.nsILoadContext)
+                               .usePrivateBrowsing;
   }
 };
 
 
 /**
  * Switch to a tab that has a given URI, and focusses its browser window.
  * If a matching tab is in this window, it will be switched to. Otherwise, other
  * windows will be searched.
--- a/browser/base/content/pageinfo/pageInfo.css
+++ b/browser/base/content/pageinfo/pageInfo.css
@@ -14,12 +14,13 @@ richlistitem[feed] {
 richlistitem[feed]:not([selected="true"]) .feed-subscribe {
   display: none;
 }
 
 groupbox[closed="true"] > .groupbox-body { 
   visibility: collapse;
 }
 
+#thepreviewimage {
+  display: block;
 /* This following entry can be removed when Bug 522850 is fixed. */
-#thepreviewimage {
   min-width: 1px;
 }
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_lastpbcontextexited.js
+++ b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_lastpbcontextexited.js
@@ -14,15 +14,15 @@ function test() {
         is(aTopic, "last-pb-context-exited", "Correct topic should be dispatched");
         is(expected, true, "notification not expected yet");
         Services.obs.removeObserver(observer, "last-pb-context-exited", false);
         gPrefService.clearUserPref("browser.privatebrowsing.keep_current_session");
         finish();
       }
     };
     Services.obs.addObserver(observer, "last-pb-context-exited", false);
-    newWin.gPrivateBrowsingUI.privateWindow = true;
+    setPrivateWindow(newWin, true);
     expected = true;
     newWin.close(); // this will cause the docshells to leave PB mode
     newWin = null;
     SpecialPowers.forceGC();
   }, newWin);
 }
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_ui.js
+++ b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_ui.js
@@ -65,19 +65,19 @@ function test() {
       is(gPrivateBrowsingUI.privateWindow, false, "gPrivateBrowsingUI should expose the correct per-window private browsing status");
       // check to see if the Private Browsing mode was deactivated successfully
       is(observerData, "exit", "Private Browsing mode was deactivated using the gPrivateBrowsingUI object");
       is(pbMenuItem.getAttribute("label"), pbMenuItem.getAttribute("startlabel"), "The Private Browsing menu item should read \"Start Private Browsing\"");
 
       testNewWindow(function() {
         // These are tests for the privateWindow setter.  Note that the setter should
         // not be used anywhere else for now!
-        gPrivateBrowsingUI.privateWindow = true;
+        setPrivateWindow(window, true);
         is(gPrivateBrowsingUI.privateWindow, true, "gPrivateBrowsingUI should accept the correct per-window private browsing status");
-        gPrivateBrowsingUI.privateWindow = false;
+        setPrivateWindow(window, false);
         is(gPrivateBrowsingUI.privateWindow, false, "gPrivateBrowsingUI should accept the correct per-window private browsing status");
 
         // now, test using the <command> object
         let cmd = document.getElementById("Tools:PrivateBrowsing");
         isnot(cmd, null, "XUL command object for the private browsing service exists");
         var func = new Function("", cmd.getAttribute("oncommand"));
         func.call(cmd);
         // check to see if the Private Browsing mode was activated successfully
--- a/browser/components/privatebrowsing/test/browser/head.js
+++ b/browser/components/privatebrowsing/test/browser/head.js
@@ -18,8 +18,22 @@ registerCleanupFunction(function() {
  */
 function waitForClearHistory(aCallback) {
   Services.obs.addObserver(function observeCH(aSubject, aTopic, aData) {
     Services.obs.removeObserver(observeCH, PlacesUtils.TOPIC_EXPIRATION_FINISHED);
     aCallback();
   }, PlacesUtils.TOPIC_EXPIRATION_FINISHED, false);
   PlacesUtils.bhistory.removeAllPages();
 }
+
+/*
+ * Function created to replace the |privateWindow| setter
+ */
+function setPrivateWindow(aWindow, aEnable) {
+  return aWindow.QueryInterface(Ci.nsIInterfaceRequestor)
+                 .getInterface(Ci.nsIWebNavigation)
+                 .QueryInterface(Ci.nsIDocShellTreeItem)
+                 .treeOwner
+                 .QueryInterface(Ci.nsIInterfaceRequestor)
+                 .getInterface(Ci.nsIXULWindow)
+                 .docShell.QueryInterface(Ci.nsILoadContext)
+                 .usePrivateBrowsing = aEnable;
+} 
--- a/browser/installer/removed-files.in
+++ b/browser/installer/removed-files.in
@@ -869,16 +869,19 @@ xpicleanup@BIN_SUFFIX@
   chrome/localized.manifest
   chrome/nonlocalized.manifest
   chrome/pippki.jar
   chrome/toolkit.jar
   components/addonManager.js
   components/amContentHandler.js
   components/amWebInstallListener.js
   components/browser.xpt
+  components/BrowserElementParent.js
+  components/BrowserElementParent.manifest
+  components/BrowserElementPromptService.jsm
   components/components.manifest
   components/contentAreaDropListener.js
   components/contentSecurityPolicy.js
   components/crypto-SDR.js
   components/FeedConverter.js
   components/FeedProcessor.js
   components/FeedWriter.js
   components/fuelApplication.js
--- a/caps/idl/nsIScriptSecurityManager.idl
+++ b/caps/idl/nsIScriptSecurityManager.idl
@@ -4,17 +4,17 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsISupports.idl"
 #include "nsIPrincipal.idl"
 #include "nsIXPCSecurityManager.idl"
 interface nsIURI;
 interface nsIChannel;
 
-[scriptable, uuid(3708aa92-e2d9-4fd1-9e46-edfa3eb5ebf5)]
+[scriptable, uuid(cdb27711-492b-4973-938b-de81ac124658)]
 interface nsIScriptSecurityManager : nsIXPCSecurityManager
 {
     ///////////////// Security Checks //////////////////
     /**
      * Checks whether the running script is allowed to access aProperty.
      */
     [noscript] void checkPropertyAccess(in JSContextPtr aJSContext,
                                         in JSObjectPtr aJSObject,
@@ -255,37 +255,14 @@ interface nsIScriptSecurityManager : nsI
      * Same as getSubjectPrincipal(), only faster. cx must *never* be
      * passed null, and it must be the context on the top of the
      * context stack. Does *not* reference count the returned
      * principal.
      */
     [noscript,notxpcom] nsIPrincipal getCxSubjectPrincipal(in JSContextPtr cx);
     [noscript,notxpcom] nsIPrincipal getCxSubjectPrincipalAndFrame(in JSContextPtr cx,
                                                                    out JSStackFramePtr fp);
-
-    /**
-     * If no scripted code is running "above" (or called from) fp, then
-     * instead of looking at cx->globalObject, we will return |principal|.
-     * This function only affects |cx|. If someone pushes another context onto
-     * the context stack, then it supersedes this call.
-     * NOTE: If |fp| is non-null popContextPrincipal must be called before fp
-     * has finished executing.
-     *
-     * @param cx The context to clamp.
-     * @param fp The frame pointer to clamp at. May be 'null'.
-     * @param principal The principal to clamp to.
-     */
-    [noscript] void pushContextPrincipal(in JSContextPtr cx,
-                                         in JSStackFramePtr fp,
-                                         in nsIPrincipal principal);
-
-    /**
-     * Removes a clamp set by pushContextPrincipal from cx. This must be
-     * called in a stack-like fashion (e.g., given two contexts |a| and |b|,
-     * it is not legal to do: push(a) push(b) pop(a)).
-     */
-    [noscript] void popContextPrincipal(in JSContextPtr cx);
 };
 
 %{C++
 #define NS_SCRIPTSECURITYMANAGER_CONTRACTID "@mozilla.org/scriptsecuritymanager;1"
 #define NS_SCRIPTSECURITYMANAGER_CLASSNAME "scriptsecuritymanager"
 %}
--- a/caps/include/nsScriptSecurityManager.h
+++ b/caps/include/nsScriptSecurityManager.h
@@ -398,22 +398,21 @@ private:
     ObjectPrincipalFinder(JSObject *obj);
     
     // Decides, based on CSP, whether or not eval() and stuff can be executed.
     static JSBool
     ContentSecurityPolicyPermitsJSAction(JSContext *cx);
 
     // Returns null if a principal cannot be found; generally callers
     // should error out at that point.
-    static nsIPrincipal*
-    doGetObjectPrincipal(JSObject *obj
+    static nsIPrincipal* doGetObjectPrincipal(JSObject *obj);
 #ifdef DEBUG
-                         , bool aAllowShortCircuit = true
+    static nsIPrincipal*
+    old_doGetObjectPrincipal(JSObject *obj, bool aAllowShortCircuit = true);
 #endif
-                         );
 
     // Returns null if a principal cannot be found.  Note that rv can be NS_OK
     // when this happens -- this means that there was no JS running.
     nsIPrincipal*
     doGetSubjectPrincipal(nsresult* rv);
     
     nsresult
     CheckPropertyAccessImpl(PRUint32 aAction,
@@ -549,40 +548,28 @@ private:
     nsresult
     InitPrincipals(PRUint32 prefCount, const char** prefNames);
 
 #ifdef DEBUG_CAPS_HACKER
     void
     PrintPolicyDB();
 #endif
 
-    struct ContextPrincipal {
-        ContextPrincipal(ContextPrincipal *next, JSContext *cx,
-                         JSStackFrame *fp, nsIPrincipal *principal)
-            : mNext(next), mCx(cx), mFp(fp), mPrincipal(principal) {}
-
-        ContextPrincipal *mNext;
-        JSContext *mCx;
-        JSStackFrame *mFp;
-        nsCOMPtr<nsIPrincipal> mPrincipal;
-    };
-
     // JS strings we need to clean up on shutdown
     static jsid sEnabledID;
 
     inline void
     ScriptSecurityPrefChanged();
 
     nsObjectHashtable* mOriginToPolicyMap;
     DomainPolicy* mDefaultPolicy;
     nsObjectHashtable* mCapabilities;
 
     nsCOMPtr<nsIPrincipal> mSystemPrincipal;
     nsCOMPtr<nsIPrincipal> mSystemCertificate;
-    ContextPrincipal *mContextPrincipals;
     nsInterfaceHashtable<PrincipalKey, nsIPrincipal> mPrincipals;
     bool mPrefInitialized;
     bool mIsJavaScriptEnabled;
     bool mIsWritingPrefs;
     bool mPolicyPrefsChanged;
 
     static bool sStrictFileOriginPolicy;
 
--- a/caps/src/nsScriptSecurityManager.cpp
+++ b/caps/src/nsScriptSecurityManager.cpp
@@ -157,54 +157,16 @@ GetPrincipalDomainOrigin(nsIPrincipal* a
 }
 
 static nsIScriptContext *
 GetScriptContext(JSContext *cx)
 {
     return GetScriptContextFromJSContext(cx);
 }
 
-// Callbacks for the JS engine to use to push/pop context principals.
-static JSBool
-PushPrincipalCallback(JSContext *cx, JSPrincipals *principals)
-{
-    // We should already be in the compartment of the given principal.
-    MOZ_ASSERT(principals ==
-               JS_GetCompartmentPrincipals((js::GetContextCompartment(cx))));
-
-    // Get the security manager.
-    nsIScriptSecurityManager *ssm = XPCWrapper::GetSecurityManager();
-    if (!ssm) {
-        return true;
-    }
-
-    // Push the principal.
-    JSStackFrame *fp = NULL;
-    nsresult rv = ssm->PushContextPrincipal(cx, JS_FrameIterator(cx, &fp),
-                                            nsJSPrincipals::get(principals));
-    if (NS_FAILED(rv)) {
-        JS_ReportOutOfMemory(cx);
-        return false;
-    }
-
-    return true;
-}
-
-static JSBool
-PopPrincipalCallback(JSContext *cx)
-{
-    nsIScriptSecurityManager *ssm = XPCWrapper::GetSecurityManager();
-    if (ssm) {
-        ssm->PopContextPrincipal(cx);
-    }
-
-    return true;
-}
-
-
 inline void SetPendingException(JSContext *cx, const char *aMsg)
 {
     JSAutoRequest ar(cx);
     JS_ReportError(cx, "%s", aMsg);
 }
 
 inline void SetPendingException(JSContext *cx, const PRUnichar *aMsg)
 {
@@ -399,44 +361,16 @@ nsScriptSecurityManager::GetCxSubjectPri
     nsresult rv = NS_ERROR_FAILURE;
     nsIPrincipal *principal = GetPrincipalAndFrame(cx, fp, &rv);
     if (NS_FAILED(rv))
         return nsnull;
 
     return principal;
 }
 
-NS_IMETHODIMP
-nsScriptSecurityManager::PushContextPrincipal(JSContext *cx,
-                                              JSStackFrame *fp,
-                                              nsIPrincipal *principal)
-{
-    NS_ASSERTION(principal, "Must pass a non-null principal");
-
-    ContextPrincipal *cp = new ContextPrincipal(mContextPrincipals, cx, fp,
-                                                principal);
-    if (!cp)
-        return NS_ERROR_OUT_OF_MEMORY;
-
-    mContextPrincipals = cp;
-    return NS_OK;
-}
-
-NS_IMETHODIMP
-nsScriptSecurityManager::PopContextPrincipal(JSContext *cx)
-{
-    NS_ASSERTION(mContextPrincipals->mCx == cx, "Mismatched push/pop");
-
-    ContextPrincipal *next = mContextPrincipals->mNext;
-    delete mContextPrincipals;
-    mContextPrincipals = next;
-
-    return NS_OK;
-}
-
 ////////////////////
 // Policy Storage //
 ////////////////////
 
 // Table of security levels
 static bool
 DeleteCapability(nsHashKey *aKey, void *aData, void* closure)
 {
@@ -2283,62 +2217,29 @@ nsScriptSecurityManager::GetPrincipalAnd
 {
     NS_PRECONDITION(rv, "Null out param");
     //-- If there's no principal on the stack, look at the global object
     //   and return the innermost frame for annotations.
     *rv = NS_OK;
 
     if (cx)
     {
-        JSStackFrame *target = nsnull;
-        nsIPrincipal *targetPrincipal = nsnull;
-        for (ContextPrincipal *cp = mContextPrincipals; cp; cp = cp->mNext)
-        {
-            if (cp->mCx == cx)
-            {
-                target = cp->mFp;
-                targetPrincipal = cp->mPrincipal;
-                break;
-            }
-        }
-
         // Get principals from innermost JavaScript frame.
         JSStackFrame *fp = nsnull; // tell JS_FrameIterator to start at innermost
         for (fp = JS_FrameIterator(cx, &fp); fp; fp = JS_FrameIterator(cx, &fp))
         {
-            if (fp == target)
-                break;
             nsIPrincipal* result = GetFramePrincipal(cx, fp, rv);
             if (result)
             {
                 NS_ASSERTION(NS_SUCCEEDED(*rv), "Weird return");
                 *frameResult = fp;
                 return result;
             }
         }
 
-        // If targetPrincipal is non-null, then it means that someone wants to
-        // clamp the principals on this context to this principal. Note that
-        // fp might not equal target here (fp might be null) because someone
-        // could have set aside the frame chain in the meantime.
-        if (targetPrincipal)
-        {
-            if (fp && fp == target)
-            {
-                *frameResult = fp;
-            }
-            else
-            {
-                JSStackFrame *inner = nsnull;
-                *frameResult = JS_FrameIterator(cx, &inner);
-            }
-
-            return targetPrincipal;
-        }
-
         nsIScriptContextPrincipal* scp =
             GetScriptContextPrincipalFromJSContext(cx);
         if (scp)
         {
             nsIScriptObjectPrincipal* globalData = scp->GetObjectPrincipal();
             if (!globalData)
             {
                 *rv = NS_ERROR_FAILURE;
@@ -2359,47 +2260,67 @@ nsScriptSecurityManager::GetPrincipalAnd
 
     return nsnull;
 }
 
 nsIPrincipal*
 nsScriptSecurityManager::GetSubjectPrincipal(JSContext *cx,
                                              nsresult* rv)
 {
-    NS_PRECONDITION(rv, "Null out param");
-    JSStackFrame *fp;
-    return GetPrincipalAndFrame(cx, &fp, rv);
+    *rv = NS_OK;
+    JSCompartment *compartment = js::GetContextCompartment(cx);
+
+    // The context should always be in a compartment, either one it has entered
+    // or the one associated with its global.
+    MOZ_ASSERT(!!compartment);
+
+    JSPrincipals *principals = JS_GetCompartmentPrincipals(compartment);
+    return nsJSPrincipals::get(principals);
 }
 
 NS_IMETHODIMP
 nsScriptSecurityManager::GetObjectPrincipal(JSContext *aCx, JSObject *aObj,
                                             nsIPrincipal **result)
 {
     *result = doGetObjectPrincipal(aObj);
     if (!*result)
         return NS_ERROR_FAILURE;
     NS_ADDREF(*result);
     return NS_OK;
 }
 
 // static
 nsIPrincipal*
-nsScriptSecurityManager::doGetObjectPrincipal(JSObject *aObj
+nsScriptSecurityManager::doGetObjectPrincipal(JSObject *aObj)
+{
+    JSCompartment *compartment = js::GetObjectCompartment(aObj);
+    JSPrincipals *principals = JS_GetCompartmentPrincipals(compartment);
+    nsIPrincipal *principal = nsJSPrincipals::get(principals);
+
+    // We leave the old code in for a little while to make sure that pulling
+    // object principals directly off the compartment always gives an equivalent
+    // result (from a security perspective).
 #ifdef DEBUG
-                                              , bool aAllowShortCircuit
+    nsIPrincipal *old = old_doGetObjectPrincipal(aObj);
+    MOZ_ASSERT(NS_SUCCEEDED(CheckSameOriginPrincipal(principal, old)));
 #endif
-                                              )
+
+    return principal;
+}
+
+#ifdef DEBUG
+// static
+nsIPrincipal*
+nsScriptSecurityManager::old_doGetObjectPrincipal(JSObject *aObj,
+                                                  bool aAllowShortCircuit)
 {
     NS_ASSERTION(aObj, "Bad call to doGetObjectPrincipal()!");
     nsIPrincipal* result = nsnull;
 
-#ifdef DEBUG
     JSObject* origObj = aObj;
-#endif
-    
     js::Class *jsClass = js::GetObjectClass(aObj);
 
     // A common case seen in this code is that we enter this function
     // with aObj being a Function object, whose parent is a Call
     // object. Neither of those have object principals, so we can skip
     // those objects here before we enter the below loop. That way we
     // avoid wasting time checking properties of their classes etc in
     // the loop.
@@ -2423,48 +2344,41 @@ nsScriptSecurityManager::doGetObjectPrin
     }
 
     do {
         // Note: jsClass is set before this loop, and also at the
         // *end* of this loop.
         
         if (IS_WRAPPER_CLASS(jsClass)) {
             result = sXPConnect->GetPrincipal(aObj,
-#ifdef DEBUG
-                                              aAllowShortCircuit
-#else
-                                              true
-#endif
-                                              );
+                                              aAllowShortCircuit);
             if (result) {
                 break;
             }
         } else {
             nsISupports *priv;
             if (!(~jsClass->flags & (JSCLASS_HAS_PRIVATE |
                                      JSCLASS_PRIVATE_IS_NSISUPPORTS))) {
                 priv = (nsISupports *) js::GetObjectPrivate(aObj);
             } else if (IsDOMClass(jsClass) &&
                        DOMJSClass::FromJSClass(jsClass)->mDOMObjectIsISupports) {
                 priv = UnwrapDOMObject<nsISupports>(aObj);
             } else {
                 priv = nsnull;
             }
 
-#ifdef DEBUG
             if (aAllowShortCircuit) {
                 nsCOMPtr<nsIXPConnectWrappedNative> xpcWrapper =
                     do_QueryInterface(priv);
 
                 NS_ASSERTION(!xpcWrapper ||
                              !strcmp(jsClass->name, "XPCNativeWrapper"),
                              "Uh, an nsIXPConnectWrappedNative with the "
                              "wrong JSClass or getObjectOps hooks!");
             }
-#endif
 
             nsCOMPtr<nsIScriptObjectPrincipal> objPrin =
                 do_QueryInterface(priv);
 
             if (objPrin) {
                 result = objPrin->GetPrincipal();
 
                 if (result) {
@@ -2476,62 +2390,45 @@ nsScriptSecurityManager::doGetObjectPrin
         aObj = js::GetObjectParentMaybeScope(aObj);
 
         if (!aObj)
             break;
 
         jsClass = js::GetObjectClass(aObj);
     } while (1);
 
-#ifdef DEBUG
     if (aAllowShortCircuit) {
-        nsIPrincipal *principal = doGetObjectPrincipal(origObj, false);
+        nsIPrincipal *principal = old_doGetObjectPrincipal(origObj, false);
 
         // Because of inner window reuse, we can have objects with one principal
         // living in a scope with a different (but same-origin) principal. So
         // just check same-origin here.
         NS_ASSERTION(NS_SUCCEEDED(CheckSameOriginPrincipal(result, principal)),
                      "Principal mismatch.  Not good");
     }
-#endif
 
     return result;
 }
+#endif /* DEBUG */
 
 ///////////////// Capabilities API /////////////////////
 NS_IMETHODIMP
 nsScriptSecurityManager::IsCapabilityEnabled(const char *capability,
                                              bool *result)
 {
     nsresult rv;
     JSStackFrame *fp = nsnull;
     JSContext *cx = GetCurrentJSContext();
     fp = cx ? JS_FrameIterator(cx, &fp) : nsnull;
 
-    JSStackFrame *target = nsnull;
-    nsIPrincipal *targetPrincipal = nsnull;
-    for (ContextPrincipal *cp = mContextPrincipals; cp; cp = cp->mNext)
-    {
-        if (cp->mCx == cx)
-        {
-            target = cp->mFp;
-            targetPrincipal = cp->mPrincipal;
-            break;
-        }
-    }
-
     if (!fp)
     {
-        // No script code on stack. If we had a principal pushed for this
-        // context and fp is null, then we use that principal. Otherwise, we
-        // don't have enough information and have to allow execution.
-
-        *result = (targetPrincipal && !target)
-                  ? (targetPrincipal == mSystemPrincipal)
-                  : true;
+        // No script code on stack. We don't have enough information and have
+        // to allow execution.
+        *result = true;
 
         return NS_OK;
     }
 
     *result = false;
     nsIPrincipal* previousPrincipal = nsnull;
     do
     {
@@ -2565,17 +2462,17 @@ nsScriptSecurityManager::IsCapabilityEna
         if (NS_FAILED(rv)) return rv;
         if (*result)
             return NS_OK;
 
         // Capabilities do not extend to calls into C/C++ and then back into
         // the JS engine via JS_EvaluateScript or similar APIs.
         if (JS_IsGlobalFrame(cx, fp))
             break;
-    } while (fp != target && (fp = JS_FrameIterator(cx, &fp)) != nsnull);
+    } while ((fp = JS_FrameIterator(cx, &fp)) != nsnull);
 
     if (!previousPrincipal)
     {
         // No principals on the stack, all native code.  Allow
         // execution if the subject principal is the system principal.
 
         return SubjectPrincipalIsSystem(result);
     }
@@ -3049,17 +2946,16 @@ nsScriptSecurityManager::Observe(nsISupp
 
 /////////////////////////////////////////////
 // Constructor, Destructor, Initialization //
 /////////////////////////////////////////////
 nsScriptSecurityManager::nsScriptSecurityManager(void)
     : mOriginToPolicyMap(nsnull),
       mDefaultPolicy(nsnull),
       mCapabilities(nsnull),
-      mContextPrincipals(nsnull),
       mPrefInitialized(false),
       mIsJavaScriptEnabled(false),
       mIsWritingPrefs(false),
       mPolicyPrefsChanged(true)
 {
     MOZ_STATIC_ASSERT(sizeof(intptr_t) == sizeof(void*),
                       "intptr_t and void* have different lengths on this platform. "
                       "This may cause a security failure with the SecurityLevel union.");
@@ -3110,19 +3006,17 @@ nsresult nsScriptSecurityManager::Init()
 
     rv = runtimeService->GetRuntime(&sRuntime);
     NS_ENSURE_SUCCESS(rv, rv);
 
     static const JSSecurityCallbacks securityCallbacks = {
         CheckObjectAccess,
         nsJSPrincipals::Subsume,
         ObjectPrincipalFinder,
-        ContentSecurityPolicyPermitsJSAction,
-        PushPrincipalCallback,
-        PopPrincipalCallback
+        ContentSecurityPolicyPermitsJSAction
     };
 
     MOZ_ASSERT(!JS_GetSecurityCallbacks(sRuntime));
     JS_SetSecurityCallbacks(sRuntime, &securityCallbacks);
     JS_InitDestroyPrincipalsCallback(sRuntime, nsJSPrincipals::Destroy);
 
     JS_SetTrustedPrincipals(sRuntime, system);
 
@@ -3131,17 +3025,16 @@ nsresult nsScriptSecurityManager::Init()
 
 static nsScriptSecurityManager *gScriptSecMan = nsnull;
 
 jsid nsScriptSecurityManager::sEnabledID   = JSID_VOID;
 
 nsScriptSecurityManager::~nsScriptSecurityManager(void)
 {
     Preferences::RemoveObservers(this, kObservedPrefs);
-    NS_ASSERTION(!mContextPrincipals, "Leaking mContextPrincipals");
     delete mOriginToPolicyMap;
     if(mDefaultPolicy)
         mDefaultPolicy->Drop();
     delete mCapabilities;
     gScriptSecMan = nsnull;
 }
 
 void
--- a/content/base/public/nsContentUtils.h
+++ b/content/base/public/nsContentUtils.h
@@ -112,16 +112,17 @@ class nsIMIMEHeaderParam;
 class nsIObserver;
 class nsPresContext;
 class nsIChannel;
 class nsAutoScriptBlockerSuppressNodeRemoved;
 struct nsIntMargin;
 class nsPIDOMWindow;
 class nsIDocumentLoaderFactory;
 class nsIDOMHTMLInputElement;
+class nsTypedSelection;
 
 namespace mozilla {
 
 namespace layers {
   class LayerManager;
 } // namespace layers
 
 namespace dom {
@@ -2022,16 +2023,32 @@ public:
    * @param aPrefURL Preference name
    * @param aAllowed [out] outparam on whether or not window is allowed
    *                       to access pref
    *
    * @return NS_OK on successful preference lookup, error code otherwise
    */
   static nsresult IsOnPrefWhitelist(nsPIDOMWindow* aWindow,
                                     const char* aPrefURL, bool *aAllowed);
+
+  /**
+   * Takes a selection, and a text control element (<input> or <textarea>), and
+   * returns the offsets in the text content corresponding to the selection.
+   * The selection's anchor and focus must both be in the root node passed or a
+   * descendant.
+   *
+   * @param aSelection      Selection to check
+   * @param aRoot           Root <input> or <textarea> element
+   * @param aOutStartOffset Output start offset
+   * @param aOutEndOffset   Output end offset
+   */
+  static void GetSelectionInTextControl(nsTypedSelection* aSelection,
+                                        Element* aRoot,
+                                        PRInt32& aOutStartOffset,
+                                        PRInt32& aOutEndOffset);
   
 private:
   static bool InitializeEventTable();
 
   static nsresult EnsureStringBundle(PropertiesFile aFile);
 
   static bool CanCallerAccess(nsIPrincipal* aSubjectPrincipal,
                                 nsIPrincipal* aPrincipal);
--- a/content/base/public/nsIContentIterator.h
+++ b/content/base/public/nsIContentIterator.h
@@ -2,16 +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 __nsIContentIterator_h___
 #define __nsIContentIterator_h___
 
 #include "nsISupports.h"
+#include "nsCOMPtr.h"
 
 class nsINode;
 class nsIDOMRange;
 
 #define NS_ICONTENTITERATOR_IID \
 { 0x2550078e, 0xae87, 0x4914, \
  { 0xb3, 0x04, 0xe4, 0xd1, 0x46, 0x19, 0x3d, 0x5f } }
 
@@ -58,10 +59,13 @@ public:
 
   /** PositionAt will position the iterator to the supplied node
    */
   virtual nsresult PositionAt(nsINode* aCurNode) = 0;
 };
 
 NS_DEFINE_STATIC_IID_ACCESSOR(nsIContentIterator, NS_ICONTENTITERATOR_IID)
 
+already_AddRefed<nsIContentIterator> NS_NewContentIterator();
+already_AddRefed<nsIContentIterator> NS_NewPreContentIterator();
+already_AddRefed<nsIContentIterator> NS_NewContentSubtreeIterator();
+
 #endif // __nsIContentIterator_h___
-
--- a/content/base/public/nsIXMLHttpRequest.idl
+++ b/content/base/public/nsIXMLHttpRequest.idl
@@ -16,16 +16,37 @@ interface nsPIDOMWindow;
 interface nsIInputStream;
 interface nsIDOMBlob;
 
 %{C++
 // for jsval
 #include "jsapi.h"
 %}
 
+/**
+ * Parameters for instantiating an XMLHttpRequest. They are passed as an
+ * optional argument to the constructor:
+ *
+ *  new XMLHttpRequest({anon: true, system: true});
+ *
+ */
+dictionary XMLHttpRequestParameters
+{
+  /**
+   * If true, the request will be sent without cookie and authentication
+   * headers.
+   */
+  boolean mozAnon;
+
+  /**
+   * If true, the same origin policy will not be enforced on the request.
+   */
+  boolean mozSystem;
+};
+
 [scriptable, builtinclass, uuid(5e346bf8-7083-4ef8-b9b9-736a1b5aa7ab)]
 interface nsIXMLHttpRequestEventTarget : nsIDOMEventTarget {
   // event handler attributes
   attribute nsIDOMEventListener onabort;
   attribute nsIDOMEventListener onerror;
   attribute nsIDOMEventListener onload;
   attribute nsIDOMEventListener onloadstart;
   attribute nsIDOMEventListener onprogress;
@@ -74,17 +95,17 @@ interface nsIXMLHttpRequestUpload : nsIX
  *   The 'onload', 'onerror', and 'onreadystatechange' attributes moved to
  *   nsIJSXMLHttpRequest, but if you're coding in C++ you should avoid using
  *   those.
  *
  * Conclusion: Do not use event listeners on XMLHttpRequest from C++, unless
  * you're aware of all the security implications.  And then think twice about
  * it.
  */
-[scriptable, uuid(8681ffbc-4755-45de-9fc1-b63e6930e76a)]
+[scriptable, uuid(2ed23d20-9d6d-47fd-b60f-2416dbd57005)]
 interface nsIXMLHttpRequest : nsISupports
 {
   /**
    * The request uses a channel in order to perform the
    * request.  This attribute represents the channel used
    * for the request.  NULL if the channel has not yet been
    * created.
    *
@@ -346,16 +367,27 @@ interface nsIXMLHttpRequest : nsISupport
    * This attribute should not be used from native code!!
    *
    * After the initial response, all event listeners will be cleared.
    * // XXXbz what does that mean, exactly?   
    *
    * Call open() before setting an onreadystatechange listener.
    */
   attribute nsIDOMEventListener onreadystatechange;
+
+  /**
+   * If true, the request will be sent without cookie and authentication
+   * headers.
+   */
+  readonly attribute boolean mozAnon;
+
+  /**
+   * If true, the same origin policy will not be enforced on the request.
+   */
+  readonly attribute boolean mozSystem;
 };
 
 [scriptable, uuid(840d0d00-e83e-4a29-b3c7-67e96e90a499)]
 interface nsIXHRSendable : nsISupports {
   void getSendInfo(out nsIInputStream body,
                    out ACString contentType,
                    out ACString charset);
 };
--- a/content/base/src/nsContentIterator.cpp
+++ b/content/base/src/nsContentIterator.cpp
@@ -172,39 +172,29 @@ private:
 
 };
 
 
 /******************************************************
  * repository cruft
  ******************************************************/
 
-nsresult NS_NewContentIterator(nsIContentIterator** aInstancePtrResult)
+already_AddRefed<nsIContentIterator>
+NS_NewContentIterator()
 {
-  nsContentIterator * iter = new nsContentIterator(false);
-  if (!iter) {
-    return NS_ERROR_OUT_OF_MEMORY;
-  }
-
-  NS_ADDREF(*aInstancePtrResult = iter);
-
-  return NS_OK;
+  nsCOMPtr<nsIContentIterator> iter = new nsContentIterator(false);
+  return iter.forget();
 }
 
 
-nsresult NS_NewPreContentIterator(nsIContentIterator** aInstancePtrResult)
+already_AddRefed<nsIContentIterator>
+NS_NewPreContentIterator()
 {
-  nsContentIterator * iter = new nsContentIterator(true);
-  if (!iter) {
-    return NS_ERROR_OUT_OF_MEMORY;
-  }
-
-  NS_ADDREF(*aInstancePtrResult = iter);
-
-  return NS_OK;
+  nsCOMPtr<nsIContentIterator> iter = new nsContentIterator(true);
+  return iter.forget();
 }
 
 
 /******************************************************
  * XPCOM cruft
  ******************************************************/
  
 NS_IMPL_CYCLE_COLLECTING_ADDREF(nsContentIterator)
@@ -1179,35 +1169,28 @@ NS_INTERFACE_MAP_END_INHERITING(nsConten
 NS_IMPL_CYCLE_COLLECTION_CLASS(nsContentSubtreeIterator)
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(nsContentSubtreeIterator, nsContentIterator)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR_AMBIGUOUS(mRange, nsIDOMRange)
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(nsContentSubtreeIterator, nsContentIterator)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mRange)
 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 
-nsresult NS_NewContentSubtreeIterator(nsIContentIterator** aInstancePtrResult);
-
 
 
 
 /******************************************************
  * repository cruft
  ******************************************************/
 
-nsresult NS_NewContentSubtreeIterator(nsIContentIterator** aInstancePtrResult)
+already_AddRefed<nsIContentIterator>
+NS_NewContentSubtreeIterator()
 {
-  nsContentIterator * iter = new nsContentSubtreeIterator();
-  if (!iter) {
-    return NS_ERROR_OUT_OF_MEMORY;
-  }
-
-  NS_ADDREF(*aInstancePtrResult = iter);
-
-  return NS_OK;
+  nsCOMPtr<nsIContentIterator> iter = new nsContentSubtreeIterator();
+  return iter.forget();
 }
 
 
 
 /******************************************************
  * Init routines
  ******************************************************/
 
--- a/content/base/src/nsContentList.cpp
+++ b/content/base/src/nsContentList.cpp
@@ -24,18 +24,16 @@
 
 // Form related includes
 #include "nsIDOMHTMLFormElement.h"
 
 #include "pldhash.h"
 
 #ifdef DEBUG_CONTENT_LIST
 #include "nsIContentIterator.h"
-nsresult
-NS_NewPreContentIterator(nsIContentIterator** aInstancePtrResult);
 #define ASSERT_IN_SYNC AssertInSync()
 #else
 #define ASSERT_IN_SYNC PR_BEGIN_MACRO PR_END_MACRO
 #endif
 
 using namespace mozilla::dom;
 
 nsBaseContentList::~nsBaseContentList()
@@ -1011,17 +1009,17 @@ nsContentList::AssertInSync()
     root = static_cast<nsIDocument*>(mRootNode)->GetRootElement();
   }
   else {
     root = static_cast<nsIContent*>(mRootNode);
   }
 
   nsCOMPtr<nsIContentIterator> iter;
   if (mDeep) {
-    NS_NewPreContentIterator(getter_AddRefs(iter));
+    iter = NS_NewPreContentIterator();
     iter->Init(root);
     iter->First();
   }
 
   PRUint32 cnt = 0, index = 0;
   while (true) {
     if (cnt == mElements.Length() && mState == LIST_LAZY) {
       break;
--- a/content/base/src/nsContentUtils.cpp
+++ b/content/base/src/nsContentUtils.cpp
@@ -138,16 +138,17 @@ static NS_DEFINE_CID(kXTFServiceCID, NS_
 #include "nsTextEditorState.h"
 #include "nsIPluginHost.h"
 #include "nsICategoryManager.h"
 #include "nsIViewManager.h"
 #include "nsEventStateManager.h"
 #include "nsIDOMHTMLInputElement.h"
 #include "nsParserConstants.h"
 #include "nsIWebNavigation.h"
+#include "nsTypedSelection.h"
 
 #ifdef IBMBIDI
 #include "nsIBidiKeyboard.h"
 #endif
 #include "nsCycleCollectionParticipant.h"
 
 // for ReportToConsole
 #include "nsIStringBundle.h"
@@ -6858,8 +6859,62 @@ nsContentUtils::IsOnPrefWhitelist(nsPIDO
           break;
         }
       }
     }
   }
   *aAllowed = allowed;
   return NS_OK;
 }
+
+// static
+void
+nsContentUtils::GetSelectionInTextControl(nsTypedSelection* aSelection,
+                                          Element* aRoot,
+                                          PRInt32& aOutStartOffset,
+                                          PRInt32& aOutEndOffset)
+{
+  MOZ_ASSERT(aSelection && aRoot);
+
+  if (!aSelection->GetRangeCount()) {
+    // Nothing selected
+    aOutStartOffset = aOutEndOffset = 0;
+    return;
+  }
+
+  nsCOMPtr<nsINode> anchorNode = aSelection->GetAnchorNode();
+  PRInt32 anchorOffset = aSelection->GetAnchorOffset();
+  nsCOMPtr<nsINode> focusNode = aSelection->GetFocusNode();
+  PRInt32 focusOffset = aSelection->GetFocusOffset();
+
+  // We have at most two children, consisting of an optional text node followed
+  // by an optional <br>.
+  NS_ASSERTION(aRoot->GetChildCount() <= 2, "Unexpected children");
+  nsCOMPtr<nsIContent> firstChild = aRoot->GetFirstChild();
+#ifdef DEBUG
+  nsCOMPtr<nsIContent> lastChild = aRoot->GetLastChild();
+  NS_ASSERTION(anchorNode == aRoot || anchorNode == firstChild ||
+               anchorNode == lastChild, "Unexpected anchorNode");
+  NS_ASSERTION(focusNode == aRoot || focusNode == firstChild ||
+               focusNode == lastChild, "Unexpected focusNode");
+#endif
+  if (!firstChild || !firstChild->IsNodeOfType(nsINode::eTEXT)) {
+    // No text node, so everything is 0
+    anchorOffset = focusOffset = 0;
+  } else {
+    // First child is text.  If the anchor/focus is already in the text node,
+    // or the start of the root node, no change needed.  If it's in the root
+    // node but not the start, or in the trailing <br>, we need to set the
+    // offset to the end.
+    if ((anchorNode == aRoot && anchorOffset != 0) ||
+        (anchorNode != aRoot && anchorNode != firstChild)) {
+      anchorOffset = firstChild->Length();
+    }
+    if ((focusNode == aRoot && focusOffset != 0) ||
+        (focusNode != aRoot && focusNode != firstChild)) {
+      focusOffset = firstChild->Length();
+    }
+  }
+
+  // Make sure aOutStartOffset <= aOutEndOffset.
+  aOutStartOffset = NS_MIN(anchorOffset, focusOffset);
+  aOutEndOffset = NS_MAX(anchorOffset, focusOffset);
+}
--- a/content/base/src/nsGenericElement.cpp
+++ b/content/base/src/nsGenericElement.cpp
@@ -131,18 +131,16 @@ using namespace mozilla;
 using namespace mozilla::dom;
 
 NS_DEFINE_IID(kThisPtrOffsetsSID, NS_THISPTROFFSETS_SID);
 
 PRInt32 nsIContent::sTabFocusModel = eTabFocus_any;
 bool nsIContent::sTabFocusModelAppliesToXUL = false;
 PRUint32 nsMutationGuard::sMutationCount = 0;
 
-nsresult NS_NewContentIterator(nsIContentIterator** aInstancePtrResult);
-
 //----------------------------------------------------------------------
 
 nsINode::nsSlots::~nsSlots()
 {
   if (mChildNodes) {
     mChildNodes->DropReference();
     NS_RELEASE(mChildNodes);
   }
--- a/content/base/src/nsGkAtomList.h
+++ b/content/base/src/nsGkAtomList.h
@@ -1932,16 +1932,19 @@ GK_ATOM(Menu, "Menu")
 GK_ATOM(mouseWheel, "mouseWheel")  // For discrete wheel events (e.g. not OSX magic mouse)
 GK_ATOM(pixels,     "pixels")
 GK_ATOM(lines,      "lines")
 GK_ATOM(pages,      "pages")
 GK_ATOM(scrollbars, "scrollbars")
 GK_ATOM(other,      "other")
 
 #ifdef ACCESSIBILITY
+GK_ATOM(alert, "alert")
+GK_ATOM(alertdialog, "alertdialog")
+GK_ATOM(application, "application")
 GK_ATOM(anonid, "anonid")
 GK_ATOM(aria_activedescendant, "aria-activedescendant")
 GK_ATOM(aria_atomic, "aria-atomic")
 GK_ATOM(aria_autocomplete, "aria-autocomplete")
 GK_ATOM(aria_busy, "aria-busy")
 GK_ATOM(aria_checked, "aria-checked")
 GK_ATOM(aria_controls, "aria-controls")
 GK_ATOM(aria_describedby, "aria-describedby")
@@ -1969,53 +1972,69 @@ GK_ATOM(aria_required, "aria-required")
 GK_ATOM(aria_selected, "aria-selected")
 GK_ATOM(aria_setsize, "aria-setsize")
 GK_ATOM(aria_sort, "aria-sort")
 GK_ATOM(aria_valuenow, "aria-valuenow")
 GK_ATOM(aria_valuemin, "aria-valuemin")
 GK_ATOM(aria_valuemax, "aria-valuemax")
 GK_ATOM(aria_valuetext, "aria-valuetext")
 GK_ATOM(AreaFrame, "AreaFrame")
+GK_ATOM(auto_generated, "auto-generated")
 GK_ATOM(backgroundColor, "background-color")
 GK_ATOM(checkable, "checkable")
 GK_ATOM(choices, "choices")
+GK_ATOM(columnheader, "columnheader")
 GK_ATOM(containerAtomic, "container-atomic")
 GK_ATOM(containerBusy, "container-busy")
 GK_ATOM(containerLive, "container-live")
 GK_ATOM(containerLiveRole, "container-live-role")
 GK_ATOM(containerRelevant, "container-relevant")
 GK_ATOM(cycles, "cycles")
 GK_ATOM(datatable, "datatable")
+GK_ATOM(directory, "directory")
 GK_ATOM(droppable, "droppable")
 GK_ATOM(eventFromInput, "event-from-input")
+GK_ATOM(gridcell, "gridcell")
+GK_ATOM(heading, "heading")
 GK_ATOM(InlineBlockFrame, "InlineBlockFrame")
 GK_ATOM(inlinevalue, "inline")
 GK_ATOM(invalid, "invalid")
 GK_ATOM(item, "item")
 GK_ATOM(itemset, "itemset")
 GK_ATOM(lineNumber, "line-number")
 GK_ATOM(linkedPanel, "linkedpanel")
 GK_ATOM(live, "live")
 GK_ATOM(marginBottom, "margin-bottom")
 GK_ATOM(marginLeft, "margin-left")
 GK_ATOM(marginRight, "margin-right")
 GK_ATOM(marginTop, "margin-top")
+GK_ATOM(menuitemcheckbox, "menuitemcheckbox")
+GK_ATOM(menuitemradio, "menuitemradio")
 GK_ATOM(mixed, "mixed")
 GK_ATOM(multiline, "multiline")
 GK_ATOM(password, "password")
-GK_ATOM(posinset, "posinset") 
+GK_ATOM(posinset, "posinset")
+GK_ATOM(presentation, "presentation")
+GK_ATOM(progressbar, "progressbar")
+GK_ATOM(region, "region")
+GK_ATOM(rowheader, "rowheader")
 GK_ATOM(select1, "select1")
 GK_ATOM(setsize, "setsize")
+GK_ATOM(spinbutton, "spinbutton")
+GK_ATOM(status, "status")
 GK_ATOM(tableCellIndex, "table-cell-index")
+GK_ATOM(tablist, "tablist")
 GK_ATOM(textAlign, "text-align")
 GK_ATOM(textIndent, "text-indent")
 GK_ATOM(textLineThroughColor, "text-line-through-color")
 GK_ATOM(textLineThroughStyle, "text-line-through-style")
 GK_ATOM(textPosition, "text-position")
 GK_ATOM(textUnderlineColor, "text-underline-color")
 GK_ATOM(textUnderlineStyle, "text-underline-style")
+GK_ATOM(timer, "timer")
 GK_ATOM(toolbarname, "toolbarname")
 GK_ATOM(toolbarseparator, "toolbarseparator")
 GK_ATOM(toolbarspacer, "toolbarspacer")
 GK_ATOM(toolbarspring, "toolbarspring")
+GK_ATOM(treegrid, "treegrid")
 GK_ATOM(_undefined, "undefined")
 GK_ATOM(xmlroles, "xml-roles")
 #endif
--- a/content/base/src/nsRange.cpp
+++ b/content/base/src/nsRange.cpp
@@ -28,19 +28,16 @@
 #include "nsClientRect.h"
 #include "nsLayoutUtils.h"
 #include "nsTextFrame.h"
 #include "nsFontFaceList.h"
 #include "mozilla/Telemetry.h"
 
 using namespace mozilla;
 
-nsresult NS_NewContentIterator(nsIContentIterator** aInstancePtrResult);
-nsresult NS_NewContentSubtreeIterator(nsIContentIterator** aInstancePtrResult);
-
 /******************************************************
  * stack based utilty class for managing monitor
  ******************************************************/
 
 // NS_ERROR_DOM_NOT_OBJECT_ERR is not the correct one to throw, but spec doesn't say
 // what is
 #define VALIDATE_ACCESS(node_)                                                     \
   PR_BEGIN_MACRO                                                                   \
@@ -1165,18 +1162,17 @@ RangeSubtreeIterator::Init(nsIDOMRange *
 
     mEnd = nsnull;
   }
   else
   {
     // Now create a Content Subtree Iterator to be used
     // for the subtrees between the end points!
 
-    res = NS_NewContentSubtreeIterator(getter_AddRefs(mIter));
-    if (NS_FAILED(res)) return res;
+    mIter = NS_NewContentSubtreeIterator();
 
     res = mIter->Init(aRange);
     if (NS_FAILED(res)) return res;
 
     if (mIter->IsDone())
     {
       // The subtree iterator thinks there's nothing
       // to iterate over, so just free it up so we
@@ -2239,20 +2235,18 @@ nsRange::ToString(nsAString& aReturn)
       return NS_OK;
     }
   } 
   
   /* complex case: mStartParent != mEndParent, or mStartParent not a text node
      revisit - there are potential optimizations here and also tradeoffs.
   */
 
-  nsCOMPtr<nsIContentIterator> iter;
-  nsresult rv = NS_NewContentIterator(getter_AddRefs(iter));
-  NS_ENSURE_SUCCESS(rv, rv);
-  rv = iter->Init(this);
+  nsCOMPtr<nsIContentIterator> iter = NS_NewContentIterator();
+  nsresult rv = iter->Init(this);
   NS_ENSURE_SUCCESS(rv, rv);
   
   nsString tempString;
  
   // loop through the content iterator, which returns nodes in the range in 
   // close tag order, and grab the text from any text node
   while (!iter->IsDone())
   {
--- a/content/base/src/nsXMLHttpRequest.cpp
+++ b/content/base/src/nsXMLHttpRequest.cpp
@@ -71,16 +71,17 @@
 #include "nsStringBuffer.h"
 #include "nsDOMFile.h"
 #include "nsIFileChannel.h"
 #include "mozilla/Telemetry.h"
 #include "jsfriendapi.h"
 #include "sampler.h"
 #include "mozilla/dom/XMLHttpRequestBinding.h"
 #include "nsIDOMFormData.h"
+#include "DictionaryHelpers.h"
 
 #include "nsWrapperCacheInlines.h"
 #include "nsStreamListenerWrapper.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 #define LOAD_STR "load"
@@ -446,17 +447,19 @@ nsXMLHttpRequest::nsXMLHttpRequest()
     mProgressTimerIsActive(false), mProgressEventWasDelayed(false),
     mIsHtml(false),
     mWarnAboutMultipartHtml(false),
     mWarnAboutSyncHtml(false),
     mLoadLengthComputable(false), mLoadTotal(0),
     mFirstStartRequestSeen(false),
     mInLoadProgressEvent(false),
     mResultJSON(JSVAL_VOID),
-    mResultArrayBuffer(nsnull)
+    mResultArrayBuffer(nsnull),
+    mIsAnon(false),
+    mIsSystem(false)
 {
   nsLayoutStatics::AddRef();
 
   SetIsDOMBinding();
 #ifdef DEBUG
   StaticAssertions();
 #endif
 }
@@ -556,16 +559,51 @@ nsXMLHttpRequest::Initialize(nsISupports
   }
 
   // This XHR object is bound to a |window|,
   // so re-set principal and script context.
   nsCOMPtr<nsIScriptObjectPrincipal> scriptPrincipal = do_QueryInterface(aOwner);
   NS_ENSURE_STATE(scriptPrincipal);
 
   Construct(scriptPrincipal->GetPrincipal(), owner);
+  if (argc) {
+    nsresult rv = InitParameters(cx, argv);
+    NS_ENSURE_SUCCESS(rv, rv);
+  }
+  return NS_OK;
+}
+
+nsresult
+nsXMLHttpRequest::InitParameters(JSContext* aCx, const jsval* aParams)
+{
+  XMLHttpRequestParameters* params = new XMLHttpRequestParameters();
+  nsresult rv = params->Init(aCx, aParams);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  // Check for permissions.
+  nsCOMPtr<nsPIDOMWindow> window = do_QueryInterface(GetOwner());
+  NS_ENSURE_TRUE(window && window->GetDocShell(), NS_OK);
+
+  // Chrome is always allowed access, so do the permission check only
+  // for non-chrome pages.
+  if (!nsContentUtils::IsCallerChrome()) {
+    nsCOMPtr<nsIDocument> doc = do_QueryInterface(window->GetExtantDocument());
+    NS_ENSURE_TRUE(doc, NS_OK);
+
+    nsCOMPtr<nsIURI> uri;
+    doc->NodePrincipal()->GetURI(getter_AddRefs(uri));
+
+    if (!nsContentUtils::URIIsChromeOrInPref(uri, "dom.systemXHR.whitelist")) {
+      return NS_OK;
+    }
+  }
+
+  mIsAnon = params->mozAnon;
+  mIsSystem = params->mozSystem;
+
   return NS_OK;
 }
 
 void
 nsXMLHttpRequest::ResetResponse()
 {
   mResponseXML = nsnull;
   mResponseBody.Truncate();
@@ -1706,17 +1744,17 @@ nsXMLHttpRequest::GetCurrentHttpChannel(
   }
 
   return httpChannel;
 }
 
 bool
 nsXMLHttpRequest::IsSystemXHR()
 {
-  return !!nsContentUtils::IsSystemPrincipal(mPrincipal);
+  return mIsSystem || nsContentUtils::IsSystemPrincipal(mPrincipal);
 }
 
 nsresult
 nsXMLHttpRequest::CheckChannelForCrossSiteRequest(nsIChannel* aChannel)
 {
   // First check if cross-site requests are enabled...
   if (IsSystemXHR()) {
     return NS_OK;
@@ -2279,17 +2317,17 @@ nsXMLHttpRequest::OnStartRequest(nsIRequ
                                         baseURI, mPrincipal, global,
                                         mIsHtml ? DocumentFlavorHTML :
                                                   DocumentFlavorLegacyGuess,
                                         getter_AddRefs(responseDoc));
     NS_ENSURE_SUCCESS(rv, rv);
     mResponseXML = do_QueryInterface(responseDoc);
     mResponseXML->SetPrincipal(documentPrincipal);
 
-    if (IsSystemXHR()) {
+    if (nsContentUtils::IsSystemPrincipal(mPrincipal)) {
       mResponseXML->ForceEnableXULXBL();
     }
 
     if (mState & XML_HTTP_REQUEST_USE_XSITE_AC) {
       nsCOMPtr<nsIHTMLDocument> htmlDoc = do_QueryInterface(mResponseXML);
       if (htmlDoc) {
         htmlDoc->DisableCookieAccess();
       }
@@ -3044,16 +3082,20 @@ nsXMLHttpRequest::Send(JSContext *aCx, n
   else {
     // Because of bug 682305, we can't let listener be the XHR object itself
     // because JS wouldn't be able to use it. So if we haven't otherwise
     // created a listener around 'this', do so now.
 
     listener = new nsStreamListenerWrapper(listener);
   }
 
+  if (mIsAnon) {
+    AddLoadFlags(mChannel, nsIRequest::LOAD_ANONYMOUS);
+  }
+
   NS_ASSERTION(listener != this,
                "Using an object as a listener that can't be exposed to JS");
 
   // Bypass the network cache in cases where it makes no sense:
   // 1) Multipart responses are very large and would likely be doomed by the
   //    cache once they grow too large, so they are not worth caching.
   // 2) POST responses are always unique, and we provide no API that would
   //    allow our consumers to specify a "cache key" to access old POST
@@ -3886,16 +3928,42 @@ nsXMLHttpRequest::GetUpload()
 NS_IMETHODIMP
 nsXMLHttpRequest::GetUpload(nsIXMLHttpRequestUpload** aUpload)
 {
   nsRefPtr<nsXMLHttpRequestUpload> upload = GetUpload();
   upload.forget(aUpload);
   return NS_OK;
 }
 
+bool
+nsXMLHttpRequest::GetMozAnon()
+{
+  return mIsAnon;
+}
+
+NS_IMETHODIMP
+nsXMLHttpRequest::GetMozAnon(bool* aAnon)
+{
+  *aAnon = GetMozAnon();
+  return NS_OK;
+}
+
+bool
+nsXMLHttpRequest::GetMozSystem()
+{
+  return IsSystemXHR();
+}
+
+NS_IMETHODIMP
+nsXMLHttpRequest::GetMozSystem(bool* aSystem)
+{
+  *aSystem = GetMozSystem();
+  return NS_OK;
+}
+
 void
 nsXMLHttpRequest::HandleTimeoutCallback()
 {
   if (mState & XML_HTTP_REQUEST_DONE) {
     NS_NOTREACHED("nsXMLHttpRequest::HandleTimeoutCallback with completed request");
     // do nothing!
     return;
   }
--- a/content/base/src/nsXMLHttpRequest.h
+++ b/content/base/src/nsXMLHttpRequest.h
@@ -32,16 +32,17 @@
 #include "nsIPrivateDOMEvent.h"
 #include "nsDOMProgressEvent.h"
 #include "nsDOMEventTargetHelper.h"
 #include "nsContentUtils.h"
 #include "nsDOMFile.h"
 #include "nsDOMBlobBuilder.h"
 #include "nsIPrincipal.h"
 #include "nsIScriptObjectPrincipal.h"
+#include "mozilla/dom/BindingUtils.h"
 #include "mozilla/dom/XMLHttpRequestBinding.h"
 #include "mozilla/dom/XMLHttpRequestUploadBinding.h"
 
 #include "mozilla/Assertions.h"
 #include "mozilla/dom/TypedArray.h"
 
 class nsILoadGroup;
 class AsyncVerifyRedirectCallbackForwarder;
@@ -175,41 +176,54 @@ public:
   }
   nsISupports* GetParentObject()
   {
     return GetOwner();
   }
 
   // The WebIDL constructor.
   static already_AddRefed<nsXMLHttpRequest>
-  Constructor(nsISupports* aGlobal, ErrorResult& aRv)
+  Constructor(JSContext* aCx,
+              nsISupports* aGlobal,
+              const mozilla::dom::Optional<jsval>& aParams,
+              ErrorResult& aRv)
   {
     nsCOMPtr<nsPIDOMWindow> window = do_QueryInterface(aGlobal);
     nsCOMPtr<nsIScriptObjectPrincipal> principal = do_QueryInterface(aGlobal);
     if (!window || ! principal) {
       aRv.Throw(NS_ERROR_FAILURE);
       return NULL;
     }
 
     nsRefPtr<nsXMLHttpRequest> req = new nsXMLHttpRequest();
     req->Construct(principal->GetPrincipal(), window);
+    if (aParams.WasPassed()) {
+      nsresult rv = req->InitParameters(aCx, &aParams.Value());
+      if (NS_FAILED(rv)) {
+        aRv.Throw(rv);
+        return req.forget();
+      }
+    }
     return req.forget();
   }
 
   void Construct(nsIPrincipal* aPrincipal,
                  nsPIDOMWindow* aOwnerWindow,
                  nsIURI* aBaseURI = NULL)
   {
     MOZ_ASSERT(aPrincipal);
     MOZ_ASSERT_IF(aOwnerWindow, aOwnerWindow->IsInnerWindow());
     mPrincipal = aPrincipal;
     BindToOwner(aOwnerWindow);
     mBaseURI = aBaseURI;
   }
 
+  // Initialize XMLHttpRequestParameter object.
+  nsresult InitParameters(JSContext* aCx, const jsval* aParams);
+
   NS_DECL_ISUPPORTS_INHERITED
 
   // nsIXMLHttpRequest
   NS_DECL_NSIXMLHTTPREQUEST
 
   // nsIJSXMLHttpRequest
   NS_IMETHOD GetOnuploadprogress(nsIDOMEventListener** aOnuploadprogress);
   NS_IMETHOD SetOnuploadprogress(nsIDOMEventListener* aOnuploadprogress);
@@ -455,16 +469,19 @@ public:
   void GetResponseText(nsString& aResponseText, ErrorResult& aRv);
   nsIDocument* GetResponseXML(ErrorResult& aRv);
 
   bool GetMozBackgroundRequest();
   void SetMozBackgroundRequest(bool aMozBackgroundRequest, nsresult& aRv);
   bool GetMultipart();
   void SetMultipart(bool aMultipart, nsresult& aRv);
 
+  bool GetMozAnon();
+  bool GetMozSystem();
+
   nsIChannel* GetChannel()
   {
     return mChannel;
   }
 
   // We need a GetInterface callable from JS for chrome JS
   JS::Value GetInterface(JSContext* aCx, nsIJSIID* aIID, ErrorResult& aRv);
 
@@ -684,16 +701,19 @@ protected:
   bool mWarnAboutMultipartHtml;
   bool mWarnAboutSyncHtml;
   bool mLoadLengthComputable;
   PRUint64 mLoadTotal; // 0 if not known.
   PRUint64 mLoadTransferred;
   nsCOMPtr<nsITimer> mProgressNotifier;
   void HandleProgressTimerCallback();
 
+  bool mIsSystem;
+  bool mIsAnon;
+
   /**
    * Close the XMLHttpRequest's channels and dispatch appropriate progress
    * events.
    *
    * @param aType The progress event type.
    * @param aFlag A XML_HTTP_REQUEST_* state flag defined in
    *              nsXMLHttpRequest.cpp.
    */
--- a/content/base/test/Makefile.in
+++ b/content/base/test/Makefile.in
@@ -546,16 +546,20 @@ include $(topsrcdir)/config/rules.mk
 		file_bug650386_report.sjs \
 		test_bug719533.html \
 		test_bug737087.html \
 		test_bug433662.html \
 		test_bug749367.html \
 		test_bug753278.html \
 		test_bug761120.html \
 		test_XHR_onuploadprogress.html \
+		test_XHR_anon.html \
+		file_XHR_anon.sjs \
+		test_XHR_system.html \
+		test_XHR_parameters.html \
 		$(NULL)
 
 _CHROME_FILES =	\
 		test_bug357450.js \
 		$(NULL)
 
 # This test fails on the Mac for some reason
 ifneq (,$(filter gtk2 windows,$(MOZ_WIDGET_TOOLKIT)))
new file mode 100644
--- /dev/null
+++ b/content/base/test/file_XHR_anon.sjs
@@ -0,0 +1,23 @@
+function handleRequest(request, response) {
+  let invalidHeaders = ["Cookie"];
+  let headers = {};
+
+  if (request.queryString == "expectAuth=true") {
+    if (request.hasHeader("Authorization")) {
+      headers["authorization"] = request.getHeader("Authorization");
+    } else {
+      response.setStatusLine(null, 500, "Server Error");
+    }
+  } else {
+    invalidHeaders.push("Authorization");
+  }
+
+  for each (let header in invalidHeaders) {
+    if (request.hasHeader(header)) {
+      response.setStatusLine(null, 500, "Server Error");
+      headers[header.toLowerCase()] = request.getHeader(header);
+    }
+  }
+
+  response.write(JSON.stringify(headers));
+}
new file mode 100644
--- /dev/null
+++ b/content/base/test/test_XHR_anon.html
@@ -0,0 +1,88 @@
+<!DOCTYPE html>
+<html>
+<head>
+  <meta charset="utf-8">
+  <title>Test for XMLHttpRequest with system privileges</title>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>        
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body onload="runTests();">
+<p id="display">
+<iframe id="loader"></iframe>
+</p>
+<div id="content" style="display: none">
+  
+</div>
+<pre id="test">
+<script class="testbody" type="application/javascript;version=1.8">
+
+
+function runTests() {
+  let tearDown = (function setUp() {
+    SimpleTest.waitForExplicitFinish();
+
+    const {classes: Cc, interfaces: Ci} = SpecialPowers.wrap(Components);
+
+    let authMgr = Cc["@mozilla.org/network/http-auth-manager;1"]
+                    .getService(Components.interfaces.nsIHttpAuthManager)
+    authMgr.setAuthIdentity("http", "example.com", 80, "basic", "testrealm",
+                            "", "example.com", "user1", "password1");
+
+    SpecialPowers.setCharPref("dom.systemXHR.whitelist",
+                              "http://mochi.test:8888");
+
+    return function tearDown() {
+      authMgr.clearAll();
+      SpecialPowers.clearUserPref("dom.systemXHR.whitelist");
+      SimpleTest.finish();
+    }
+  }());
+
+  // An XHR with the anon flag set will not send cookie and auth information.
+
+  const TEST_URL = "http://example.com/tests/content/base/test/file_XHR_anon.sjs";
+
+  document.cookie = "foo=bar";
+
+
+  function withoutCredentials() {
+    let xhr = new XMLHttpRequest({mozAnon: true, mozSystem: true});
+    is(xhr.mozAnon, true, "withoutCredentials: .mozAnon == true");
+    xhr.open("GET", TEST_URL);
+    xhr.onload = function onload() {
+      is(xhr.status, 200, "withoutCredentials: " + xhr.responseText);
+      withCredentials();
+    };
+    xhr.onerror = function onerror() {
+      ok(false, "Got an error event!");
+      tearDown();
+    }
+    xhr.send();
+  }
+
+  function withCredentials() {
+    // TODO: this currently does not work as expected, see bug 761479
+    let xhr = new XMLHttpRequest({mozAnon: true, mozSystem: true});
+    is(xhr.mozAnon, true, "withCredentials: .mozAnon == true");
+    xhr.open("GET", TEST_URL + "?expectAuth=true", true,
+             "user2name", "pass2word");
+    xhr.onload = function onload() {
+      todo_is(xhr.status, 200, "withCredentials: " + xhr.responseText);
+      let response = JSON.parse(xhr.responseText);
+      todo_is(response.authorization, "Basic dXNlcjJuYW1lOnBhc3Myd29yZA==");
+      tearDown();
+    };
+    xhr.onerror = function onerror() {
+      ok(false, "Got an error event!");
+      tearDown();
+    }
+    xhr.send();
+  }
+
+  withoutCredentials();
+}
+
+</script>
+</pre>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/content/base/test/test_XHR_parameters.html
@@ -0,0 +1,93 @@
+
+
+<!DOCTYPE html>
+<html>
+<head>
+  <meta charset="utf-8">
+  <title>Test for XMLHttpRequest with system privileges</title>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>        
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body onload="runTests();">
+<p id="display">
+</p>
+<div id="content" style="display: none">
+  
+</div>
+<pre id="test">
+<script class="testbody" type="application/javascript;version=1.8">
+
+function runTests() {
+  SimpleTest.waitForExplicitFinish();
+
+  let validParameters = [
+    {},
+    {mozSystem: ""},
+    {mozSystem: 0},
+    {mozAnon: 1},
+    {mozAnon: []},
+    {get mozAnon() { return true; }},
+  ];
+
+  let invalidParameters = [
+    undefined,
+    null,
+    {get mozSystem() { throw "Bla"; } },
+  ];
+
+  let havePrivileges = false;
+
+  function testValidParameter(value) {
+    let xhr;
+    try {
+      xhr = new XMLHttpRequest(value);
+    } catch (ex) {
+      ok(false, "Got unexpected exception: " + ex);
+      return;
+    }
+    ok(xhr instanceof XMLHttpRequest, "passed " + JSON.stringify(value));
+
+    // If the page doesnt have privileges to create a system or anon XHR,
+    // these flags will always be false no matter what is passed.
+    let expectedAnon = false;
+    let expectedSystem = false;
+    if (havePrivileges) {
+      expectedAnon = Boolean(value && value.mozAnon);
+      expectedSystem = Boolean(value && value.mozSystem);
+    }
+    is(xhr.mozAnon, expectedAnon, "testing mozAnon");
+    is(xhr.mozSystem, expectedSystem, "testing mozSystem");
+  }
+
+  function testInvalidParameter(value) {
+    let expectedError;
+    try {
+      new XMLHttpRequest(value);
+      ok(false, "invalid parameter did not cause exception: " +
+         JSON.stringify(value));
+    } catch (ex) {
+      expectedError = ex;
+    }
+    ok(expectedError, "invalid parameter raised exception as expected: " +
+       JSON.stringify(expectedError))
+  }
+
+  // Run the tests once without API privileges...
+  validParameters.forEach(testValidParameter);
+  invalidParameters.forEach(testInvalidParameter);
+
+  // ...and once with privileges.
+  havePrivileges = true;
+  SpecialPowers.setCharPref("dom.systemXHR.whitelist",
+                            "http://mochi.test:8888");
+  validParameters.forEach(testValidParameter);
+  invalidParameters.forEach(testInvalidParameter);
+  SpecialPowers.clearUserPref("dom.systemXHR.whitelist");
+
+  SimpleTest.finish();
+}
+
+</script>
+</pre>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/content/base/test/test_XHR_system.html
@@ -0,0 +1,52 @@
+<!DOCTYPE html>
+<html>
+<head>
+  <meta charset="utf-8">
+  <title>Test for XMLHttpRequest with system privileges</title>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>        
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body onload="runTests();">
+<p id="display">
+</p>
+<div id="content" style="display: none">
+  
+</div>
+<pre id="test">
+<script class="testbody" type="application/javascript;version=1.8">
+
+function runTests() {
+  SimpleTest.waitForExplicitFinish();
+  SpecialPowers.setCharPref("dom.systemXHR.whitelist",
+                            "http://mochi.test:8888");
+
+  function tearDown() {
+    SpecialPowers.clearUserPref("dom.systemXHR.whitelist");
+    SimpleTest.finish();
+  }
+
+  // An XHR with system privileges will be able to do cross-site calls.
+
+  const TEST_URL = "http://example.com/tests/content/base/test/test_XHR_system.html";
+  is(window.location.hostname, "mochi.test");
+
+  let xhr = new XMLHttpRequest({mozSystem: true});
+  is(xhr.mozSystem, true, ".mozSystem == true");
+  xhr.open("GET", TEST_URL);
+  xhr.onload = function onload() {
+    is(xhr.status, 200);
+    ok(xhr.responseText != null);
+    ok(xhr.responseText.length);
+    tearDown();
+  };
+  xhr.onerror = function onerror() {
+    ok(false, "Got an error event!");
+    tearDown();
+  }
+  xhr.send();
+}
+
+</script>
+</pre>
+</body>
+</html>
--- a/content/base/test/test_bug518104.html
+++ b/content/base/test/test_bug518104.html
@@ -7,31 +7,31 @@ https://bugzilla.mozilla.org/show_bug.cg
   <title>Test for Bug 518104</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>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=518104">Mozilla Bug 518104</a>
 <p id="display"></p>
-<div id="content" style="display: none">
-  <iframe id='iframe' src="data:text/html,
-    <div></div><div></div>
-    <script defer src='data:application/javascript,document.write(%2522<p></p>%2522);parent.done();document.close();'></script>">
-  </iframe>
-</div>
-<pre id="test">
 <script class="testbody" type="text/javascript">
 
 /** Test for Bug 518104 **/
 SimpleTest.waitForExplicitFinish();
 
 function done() {
   var iframe = document.getElementById("iframe");
   var divs = iframe.contentWindow.document.getElementsByTagName("p").length;
   is(divs, 0, "<p> got written.")
   SimpleTest.finish();
 }
 
 </script>
+<div id="content" style="display: none">
+  <iframe id='iframe' src="data:text/html,
+    <div></div><div></div>
+    <script defer src='data:application/javascript,document.write(%2522<p></p>%2522);parent.done();document.close();'></script>">
+  </iframe>
+</div>
+<pre id="test">
 </pre>
 </body>
 </html>
--- a/content/events/src/nsContentEventHandler.cpp
+++ b/content/events/src/nsContentEventHandler.cpp
@@ -22,18 +22,16 @@
 #include "nsTextFrame.h"
 #include "nsISelectionController.h"
 #include "nsISelectionPrivate.h"
 #include "nsContentUtils.h"
 #include "nsLayoutUtils.h"
 #include "nsIMEStateManager.h"
 #include "nsIObjectFrame.h"
 
-nsresult NS_NewContentIterator(nsIContentIterator** aInstancePtrResult);
-
 /******************************************************************/
 /* nsContentEventHandler                                          */
 /******************************************************************/
 
 nsContentEventHandler::nsContentEventHandler(
                               nsPresContext* aPresContext) :
   mPresContext(aPresContext),
   mPresShell(aPresContext->GetPresShell()), mSelection(nsnull),
@@ -273,20 +271,17 @@ static PRUint32 ConvertToXPOffset(nsICon
   // On other platforms, the native and XP newlines are the same.
   return aNativeOffset;
 #endif
 }
 
 static nsresult GenerateFlatTextContent(nsRange* aRange,
                                         nsAFlatString& aString)
 {
-  nsCOMPtr<nsIContentIterator> iter;
-  nsresult rv = NS_NewContentIterator(getter_AddRefs(iter));
-  NS_ENSURE_SUCCESS(rv, rv);
-  NS_ASSERTION(iter, "NS_NewContentIterator succeeded, but the result is null");
+  nsCOMPtr<nsIContentIterator> iter = NS_NewContentIterator();
   iter->Init(aRange);
 
   NS_ASSERTION(aString.IsEmpty(), "aString must be empty string");
 
   nsINode* startNode = aRange->GetStartParent();
   NS_ENSURE_TRUE(startNode, NS_ERROR_FAILURE);
   nsINode* endNode = aRange->GetEndParent();
   NS_ENSURE_TRUE(endNode, NS_ERROR_FAILURE);
@@ -369,21 +364,18 @@ nsContentEventHandler::ExpandToClusterBo
 
 nsresult
 nsContentEventHandler::SetRangeFromFlatTextOffset(
                               nsRange* aRange,
                               PRUint32 aNativeOffset,
                               PRUint32 aNativeLength,
                               bool aExpandToClusterBoundaries)
 {
-  nsCOMPtr<nsIContentIterator> iter;
-  nsresult rv = NS_NewContentIterator(getter_AddRefs(iter));
-  NS_ENSURE_SUCCESS(rv, rv);
-  NS_ASSERTION(iter, "NS_NewContentIterator succeeded, but the result is null");
-  rv = iter->Init(mRootContent);
+  nsCOMPtr<nsIContentIterator> iter = NS_NewContentIterator();
+  nsresult rv = iter->Init(mRootContent);
   NS_ENSURE_SUCCESS(rv, rv);
 
   PRUint32 nativeOffset = 0;
   PRUint32 nativeEndOffset = aNativeOffset + aNativeLength;
   nsCOMPtr<nsIContent> content;
   for (; !iter->IsDone(); iter->Next()) {
     nsINode* node = iter->GetCurrentNode();
     if (!node)
@@ -574,21 +566,18 @@ nsContentEventHandler::OnQueryTextRect(n
     return rv;
 
   nsRefPtr<nsRange> range = new nsRange();
   rv = SetRangeFromFlatTextOffset(range, aEvent->mInput.mOffset,
                                   aEvent->mInput.mLength, true);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // used to iterate over all contents and their frames
-  nsCOMPtr<nsIContentIterator> iter;
-  rv = NS_NewContentIterator(getter_AddRefs(iter));
-  NS_ENSURE_SUCCESS(rv, rv);
+  nsCOMPtr<nsIContentIterator> iter = NS_NewContentIterator();
   iter->Init(range);
-  NS_ENSURE_SUCCESS(rv, rv);
 
   // get the starting frame
   PRInt32 offset = range->StartOffset();
   nsINode* node = iter->GetCurrentNode();
   if (!node) {
     node = AdjustTextRectNode(range->GetStartParent(), offset);
   }
   nsIFrame* firstFrame = nsnull;
@@ -910,20 +899,17 @@ nsContentEventHandler::GetFlatTextOffset
   nsRefPtr<nsRange> prev = new nsRange();
   nsCOMPtr<nsIDOMNode> rootDOMNode(do_QueryInterface(aRootContent));
   prev->SetStart(rootDOMNode, 0);
 
   nsCOMPtr<nsIDOMNode> startDOMNode(do_QueryInterface(aNode));
   NS_ASSERTION(startDOMNode, "startNode doesn't have nsIDOMNode");
   prev->SetEnd(startDOMNode, aNodeOffset);
 
-  nsCOMPtr<nsIContentIterator> iter;
-  nsresult rv = NS_NewContentIterator(getter_AddRefs(iter));
-  NS_ENSURE_SUCCESS(rv, rv);
-  NS_ASSERTION(iter, "NS_NewContentIterator succeeded, but the result is null");
+  nsCOMPtr<nsIContentIterator> iter = NS_NewContentIterator();
   iter->Init(prev);
 
   nsCOMPtr<nsINode> startNode = do_QueryInterface(startDOMNode);
   nsINode* endNode = aNode;
 
   *aNativeOffset = 0;
   for (; !iter->IsDone(); iter->Next()) {
     nsINode* node = iter->GetCurrentNode();
--- a/content/events/src/nsEventStateManager.cpp
+++ b/content/events/src/nsEventStateManager.cpp
@@ -3170,20 +3170,20 @@ nsEventStateManager::PostHandleEvent(nsP
     break;
   case NS_MOUSE_BUTTON_UP:
     {
       ClearGlobalActiveContent(this);
       if (IsMouseEventReal(aEvent)) {
         if (!mCurrentTarget) {
           GetEventTarget();
         }
-        if (mCurrentTarget) {
-          ret = CheckForAndDispatchClick(presContext, (nsMouseEvent*)aEvent,
-                                         aStatus);
-        }
+        // Make sure to dispatch the click even if there is no frame for
+        // the current target element. This is required for Web compatibility.
+        ret = CheckForAndDispatchClick(presContext, (nsMouseEvent*)aEvent,
+                                       aStatus);
       }
 
       nsIPresShell *shell = presContext->GetPresShell();
       if (shell) {
         nsRefPtr<nsFrameSelection> frameSelection = shell->FrameSelection();
         frameSelection->SetMouseDownState(false);
       }
     }
--- a/content/events/src/nsEventStateManager.h
+++ b/content/events/src/nsEventStateManager.h
@@ -590,11 +590,15 @@ protected:
   bool mResetFMMouseDownState;
 
 private:
   // Hide so that this class can only be stack-allocated
   static void* operator new(size_t /*size*/) CPP_THROW_NEW { return nsnull; }
   static void operator delete(void* /*memory*/) {}
 };
 
-#define NS_EVENT_NEEDS_FRAME(event) (!NS_IS_ACTIVATION_EVENT(event))
+// Click and double-click events need to be handled even for content that
+// has no frame. This is required for Web compatibility.
+#define NS_EVENT_NEEDS_FRAME(event) \
+    (!NS_IS_ACTIVATION_EVENT(event) && (event)->message != NS_MOUSE_CLICK && \
+     (event)->message != NS_MOUSE_DOUBLECLICK)
 
 #endif // nsEventStateManager_h__
--- a/content/events/test/Makefile.in
+++ b/content/events/test/Makefile.in
@@ -80,16 +80,17 @@ include $(topsrcdir)/config/rules.mk
 		empty.js \
 		test_bug689564.html \
 		test_bug698929.html \
 		test_eventctors.html \
 		test_bug635465.html \
 		test_bug741666.html \
 		test_dom_keyboard_event.html \
 		test_dom_mouse_event.html \
+		test_bug742376.html \
 		$(NULL)
 
 #bug 585630
 ifneq (mobile,$(MOZ_BUILD_APP))
 _TEST_FILES += \
 		test_dragstart.html \
 		$(NULL)
 endif
new file mode 100644
--- /dev/null
+++ b/content/events/test/test_bug742376.html
@@ -0,0 +1,55 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=402089
+-->
+<head>
+  <title>Test for Bug 742376</title>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+
+<body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=742376">Mozilla Bug 742376</a>
+<script class="testbody" type="text/javascript">
+
+/** Test for Bug 742376 **/
+
+function getListenerCount() {
+
+  var Cc = SpecialPowers.wrap(Components).classes;
+  var Ci = SpecialPowers.wrap(Components).interfaces;
+  var dss = Cc["@mozilla.org/devicesensors;1"].getService(Ci.nsIDeviceSensors);
+
+  return dss.listenerCount(Ci.nsIDeviceSensorData.TYPE_ORIENTATION);
+}
+
+var startListenerCount = getListenerCount();
+
+function dumbListener(event) {}
+function dumbListener2(event) {}
+
+window.addEventListener("deviceorientation", dumbListener, false);
+window.addEventListener("deviceorientation", dumbListener2, false);
+
+window.setTimeout(function() {
+
+  window.removeEventListener("deviceorientation", dumbListener, false);
+  window.setTimeout(function() {
+
+    window.removeEventListener("deviceorientation", dumbListener2, false);
+    window.setTimeout(function() {
+      is (getListenerCount(), startListenerCount, "Must have the same listeners at this point");
+      SimpleTest.finish();
+    }, 0);
+  }, 0);
+}, 0);
+
+SimpleTest.waitForExplicitFinish();
+
+</script>
+</pre>
+</body>
+</html>
+
--- a/content/svg/content/src/nsSVGSVGElement.cpp
+++ b/content/svg/content/src/nsSVGSVGElement.cpp
@@ -31,18 +31,16 @@
 #include "nsStyleUtil.h"
 
 #include "nsEventDispatcher.h"
 #include "nsSMILTimeContainer.h"
 #include "nsSMILAnimationController.h"
 #include "nsSMILTypes.h"
 #include "nsIContentIterator.h"
 
-nsresult NS_NewContentIterator(nsIContentIterator** aInstancePtrResult);
-
 using namespace mozilla;
 using namespace mozilla::dom;
 
 NS_SVG_VAL_IMPL_CYCLE_COLLECTION(nsSVGTranslatePoint::DOMVal, mElement)
 
 NS_IMPL_CYCLE_COLLECTING_ADDREF(nsSVGTranslatePoint::DOMVal)
 NS_IMPL_CYCLE_COLLECTING_RELEASE(nsSVGTranslatePoint::DOMVal)
 
--- a/dom/Makefile.in
+++ b/dom/Makefile.in
@@ -43,16 +43,17 @@ DIRS += \
   interfaces/apps \
   $(NULL)
 
 DIRS += \
   apps \
   base \
   bindings \
   battery \
+  browser-element \
   contacts \
   devicestorage \
   file \
   media \
   power \
   settings \
   sms \
   mms \
--- a/dom/apps/src/Webapps.js
+++ b/dom/apps/src/Webapps.js
@@ -158,17 +158,16 @@ WebappsRegistry.prototype = {
   },
 
   // nsIDOMGlobalPropertyInitializer implementation
   init: function(aWindow) {
     this.initHelper(aWindow, ["Webapps:Install:Return:OK", "Webapps:Install:Return:KO",
                               "Webapps:GetInstalled:Return:OK", "Webapps:GetInstalled:Return:KO",
                               "Webapps:GetSelf:Return:OK", "Webapps:GetSelf:Return:KO"]);
 
-    Services.obs.addObserver(this, "inner-window-destroyed", false);
     let util = this._window.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils);
     this._id = util.outerWindowID;
   },
   
   classID: Components.ID("{fff440b3-fae2-45c1-bf03-3b5a2e432270}"),
 
   QueryInterface: XPCOMUtils.generateQI([Ci.mozIDOMApplicationRegistry, Ci.nsIDOMGlobalPropertyInitializer]),
   
--- a/dom/base/Makefile.in
+++ b/dom/base/Makefile.in
@@ -17,18 +17,16 @@ FORCE_STATIC_LIB = 1
 
 DIRS = \
   test \
   $(NULL)
 
 EXTRA_PP_COMPONENTS = \
   ConsoleAPI.js \
   ConsoleAPI.manifest \
-  BrowserElementParent.js \
-  BrowserElementParent.manifest \
   $(NULL)
 
 EXTRA_JS_MODULES = ConsoleAPIStorage.jsm \
   $(NULL)
 
 EXTRA_JS_MODULES += \
   DOMRequestHelper.jsm \
   IndexedDBHelper.jsm \
--- a/dom/base/nsDOMWindowUtils.cpp
+++ b/dom/base/nsDOMWindowUtils.cpp
@@ -1788,17 +1788,16 @@ nsDOMWindowUtils::EnterModalStateWithWin
 }
 
 NS_IMETHODIMP
 nsDOMWindowUtils::LeaveModalStateWithWindow(nsIDOMWindow *aWindow)
 {
   nsCOMPtr<nsPIDOMWindow> window = do_QueryReferent(mWindow);
   NS_ENSURE_STATE(window);
 
-  NS_ENSURE_ARG_POINTER(aWindow);
   window->LeaveModalState(aWindow);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsDOMWindowUtils::IsInModalState(bool *retval)
 {
   nsCOMPtr<nsPIDOMWindow> window = do_QueryReferent(mWindow);
--- a/dom/base/nsGlobalWindow.cpp
+++ b/dom/base/nsGlobalWindow.cpp
@@ -2468,17 +2468,17 @@ nsGlobalWindow::PreHandleEvent(nsEventCh
 
   aVisitor.mParentTarget = GetParentTarget();
   return NS_OK;
 }
 
 bool
 nsGlobalWindow::DialogOpenAttempted()
 {
-  nsGlobalWindow *topWindow = GetTop();
+  nsGlobalWindow *topWindow = GetScriptableTop();
   if (!topWindow) {
     NS_ERROR("DialogOpenAttempted() called without a top window?");
 
     return false;
   }
 
   topWindow = topWindow->GetCurrentInnerWindowInternal();
   if (!topWindow ||
@@ -2502,17 +2502,17 @@ nsGlobalWindow::DialogOpenAttempted()
   topWindow->mDialogAbuseCount = 0;
 
   return false;
 }
 
 bool
 nsGlobalWindow::AreDialogsBlocked()
 {
-  nsGlobalWindow *topWindow = GetTop();
+  nsGlobalWindow *topWindow = GetScriptableTop();
   if (!topWindow) {
     NS_ASSERTION(!mDocShell, "AreDialogsBlocked() called without a top window?");
 
     return true;
   }
 
   topWindow = topWindow->GetCurrentInnerWindowInternal();
 
@@ -2553,17 +2553,17 @@ nsGlobalWindow::ConfirmDialogAllowed()
   }
 
   return true;
 }
 
 void
 nsGlobalWindow::PreventFurtherDialogs()
 {
-  nsGlobalWindow *topWindow = GetTop();
+  nsGlobalWindow *topWindow = GetScriptableTop();
   if (!topWindow) {
     NS_ERROR("PreventFurtherDialogs() called without a top window?");
 
     return;
   }
 
   topWindow = topWindow->GetCurrentInnerWindowInternal();
 
@@ -6356,17 +6356,22 @@ nsGlobalWindow::CanClose()
   return true;
 }
 
 NS_IMETHODIMP
 nsGlobalWindow::Close()
 {
   FORWARD_TO_OUTER(Close, (), NS_ERROR_NOT_INITIALIZED);
 
-  if (IsFrame() || !mDocShell || IsInModalState()) {
+  bool isMozBrowser = false;
+  if (mDocShell) {
+    mDocShell->GetIsBrowserFrame(&isMozBrowser);
+  }
+
+  if ((!isMozBrowser && IsFrame()) || !mDocShell || IsInModalState()) {
     // window.close() is called on a frame in a frameset, on a window
     // that's already closed, or on a window for which there's
     // currently a modal dialog open. Ignore such calls.
 
     return NS_OK;
   }
 
   if (mHavePendingClose) {
@@ -6538,17 +6543,19 @@ nsGlobalWindow::ReallyCloseWindow()
 
     CleanUp(false);
   }
 }
 
 nsIDOMWindow *
 nsGlobalWindow::EnterModalState()
 {
-  nsGlobalWindow* topWin = GetTop();
+  // GetScriptableTop, not GetTop, so that EnterModalState works properly with
+  // <iframe mozbrowser>.
+  nsGlobalWindow* topWin = GetScriptableTop();
 
   if (!topWin) {
     NS_ERROR("Uh, EnterModalState() called w/o a reachable top window?");
 
     return nsnull;
   }
 
   // If there is an active ESM in this window, clear it. Otherwise, this can
@@ -6667,17 +6674,17 @@ public:
 
 private:
   nsRefPtr<nsGlobalWindow> mWindow;
 };
 
 void
 nsGlobalWindow::LeaveModalState(nsIDOMWindow *aCallerWin)
 {
-  nsGlobalWindow *topWin = GetTop();
+  nsGlobalWindow* topWin = GetScriptableTop();
 
   if (!topWin) {
     NS_ERROR("Uh, LeaveModalState() called w/o a reachable top window?");
     return;
   }
 
   topWin->mModalStateDepth--;
 
@@ -6709,17 +6716,17 @@ nsGlobalWindow::LeaveModalState(nsIDOMWi
   nsGlobalWindow *inner = topWin->GetCurrentInnerWindowInternal();
   if (inner)
     inner->mLastDialogQuitTime = TimeStamp::Now();
 }
 
 bool
 nsGlobalWindow::IsInModalState()
 {
-  nsGlobalWindow *topWin = GetTop();
+  nsGlobalWindow *topWin = GetScriptableTop();
 
   if (!topWin) {
     NS_ERROR("Uh, IsInModalState() called w/o a reachable top window?");
 
     return false;
   }
 
   return topWin->mModalStateDepth != 0;
@@ -10064,45 +10071,54 @@ nsGlobalWindow::EnableDeviceSensor(PRUin
   bool alreadyEnabled = false;
   for (PRUint32 i = 0; i < mEnabledSensors.Length(); i++) {
     if (mEnabledSensors[i] == aType) {
       alreadyEnabled = true;
       break;
     }
   }
 
-  if (alreadyEnabled)
+  mEnabledSensors.AppendElement(aType);
+
+  if (alreadyEnabled) {
     return;
-
-  mEnabledSensors.AppendElement(aType);
+  }
 
   nsCOMPtr<nsIDeviceSensors> ac = do_GetService(NS_DEVICE_SENSORS_CONTRACTID);
-  if (ac)
+  if (ac) {
     ac->AddWindowListener(aType, this);
+  }
 }
 
 void
 nsGlobalWindow::DisableDeviceSensor(PRUint32 aType)
 {
   PRInt32 doomedElement = -1;
+  PRInt32 listenerCount = 0;
   for (PRUint32 i = 0; i < mEnabledSensors.Length(); i++) {
     if (mEnabledSensors[i] == aType) {
       doomedElement = i;
-      break;
-    }
-  }
-
-  if (doomedElement == -1)
+      listenerCount++;
+    }
+  }
+
+  if (doomedElement == -1) {
     return;
+  }
 
   mEnabledSensors.RemoveElementAt(doomedElement);
 
+  if (listenerCount > 1) {
+    return;
+  }
+
   nsCOMPtr<nsIDeviceSensors> ac = do_GetService(NS_DEVICE_SENSORS_CONTRACTID);
-  if (ac)
+  if (ac) {
     ac->RemoveWindowListener(aType, this);
+  }
 }
 
 NS_IMETHODIMP
 nsGlobalWindow::GetURL(nsIDOMMozURLProperty** aURL)
 {
   FORWARD_TO_INNER(GetURL, (aURL), NS_ERROR_UNEXPECTED);
 
   if (!mURLProperty) {
--- a/dom/base/nsGlobalWindow.h
+++ b/dom/base/nsGlobalWindow.h
@@ -374,17 +374,27 @@ public:
     return nsIDOMWindow::GetTop(aWindow);
   }
 
   inline nsGlobalWindow *GetTop()
   {
     nsCOMPtr<nsIDOMWindow> top;
     GetTop(getter_AddRefs(top));
     if (top)
-      return static_cast<nsGlobalWindow *>(static_cast<nsIDOMWindow *>(top.get()));
+      return static_cast<nsGlobalWindow *>(top.get());
+    return nsnull;
+  }
+
+  inline nsGlobalWindow* GetScriptableTop()
+  {
+    nsCOMPtr<nsIDOMWindow> top;
+    GetScriptableTop(getter_AddRefs(top));
+    if (top) {
+      return static_cast<nsGlobalWindow *>(top.get());
+    }
     return nsnull;
   }
 
   // Call this when a modal dialog is about to be opened.  Returns
   // true if we've reached the state in this top level window where we
   // ask the user if further dialogs should be blocked.
   bool DialogOpenAttempted();
 
--- a/dom/base/nsJSEnvironment.cpp
+++ b/dom/base/nsJSEnvironment.cpp
@@ -1193,56 +1193,55 @@ nsJSContext::EvaluateStringWithValue(con
     }
 
     return NS_OK;
   }
 
   xpc_UnmarkGrayObject(aScopeObject);
   nsAutoMicroTask mt;
 
-  // Safety first: get an object representing the script's principals, i.e.,
-  // the entities who signed this script, or the fully-qualified-domain-name
-  // or "codebase" from which it was loaded.
-  nsCOMPtr<nsIPrincipal> principal = aPrincipal;
-  nsresult rv;
-  if (!aPrincipal) {
-    nsIScriptGlobalObject *global = GetGlobalObject();
-    if (!global)
-      return NS_ERROR_FAILURE;
-    nsCOMPtr<nsIScriptObjectPrincipal> objPrincipal =
-      do_QueryInterface(global, &rv);
-    if (NS_FAILED(rv))
-      return NS_ERROR_FAILURE;
-    principal = objPrincipal->GetPrincipal();
-    if (!principal)
-      return NS_ERROR_FAILURE;
-  }
+  // Ignore the principal that was passed in, and just assert that it matches
+  // the one we pull off the global.
+  nsCOMPtr<nsIPrincipal> principal;
+  nsCOMPtr<nsIScriptObjectPrincipal> objPrincipal = do_QueryInterface(GetGlobalObject());
+  if (!objPrincipal)
+    return NS_ERROR_FAILURE;
+  principal = objPrincipal->GetPrincipal();
+  if (!principal)
+    return NS_ERROR_FAILURE;
+#ifdef DEBUG
+  bool equal = false;
+  principal->Equals(aPrincipal, &equal);
+  MOZ_ASSERT(equal);
+  nsIPrincipal *scopeObjectPrincipal =
+    nsJSPrincipals::get(JS_GetCompartmentPrincipals(js::GetObjectCompartment(aScopeObject)));
+  equal = false;
+  principal->Equals(scopeObjectPrincipal, &equal);
+  MOZ_ASSERT(equal);
+#endif
 
   bool ok = false;
 
-  rv = sSecurityManager->CanExecuteScripts(mContext, principal, &ok);
+  nsresult rv = sSecurityManager->CanExecuteScripts(mContext, principal, &ok);
   if (NS_FAILED(rv)) {
     return NS_ERROR_FAILURE;
   }
 
   // Push our JSContext on the current thread's context stack so JS called
   // from native code via XPConnect uses the right context.  Do this whether
   // or not the SecurityManager said "ok", in order to simplify control flow
   // below where we pop before returning.
   nsCOMPtr<nsIJSContextStack> stack =
            do_GetService("@mozilla.org/js/xpc/ContextStack;1", &rv);
   if (NS_FAILED(rv) || NS_FAILED(stack->Push(mContext))) {
     return NS_ERROR_FAILURE;
   }
 
   jsval val;
 
-  rv = sSecurityManager->PushContextPrincipal(mContext, nsnull, principal);
-  NS_ENSURE_SUCCESS(rv, rv);
-
   nsJSContext::TerminationFuncHolder holder(this);
 
   // SecurityManager said "ok", but don't compile if aVersion is unknown.
   // Since the caller is responsible for parsing the version strings, we just
   // check it isn't JSVERSION_UNKNOWN.
   if (ok && ((JSVersion)aVersion) != JSVERSION_UNKNOWN) {
 
     XPCAutoRequest ar(mContext);
@@ -1288,18 +1287,16 @@ nsJSContext::EvaluateStringWithValue(con
     // tricky...
   }
   else {
     if (aIsUndefined) {
       *aIsUndefined = true;
     }
   }
 
-  sSecurityManager->PopContextPrincipal(mContext);
-
   // Pop here, after JS_ValueToString and any other possible evaluation.
   if (NS_FAILED(stack->Pop(nsnull)))
     rv = NS_ERROR_FAILURE;
 
   // ScriptEvaluated needs to come after we pop the stack
   ScriptEvaluated(true);
 
   return rv;
@@ -1395,29 +1392,35 @@ nsJSContext::EvaluateString(const nsAStr
   nsAutoMicroTask mt;
 
   if (!aScopeObject) {
     aScopeObject = JS_GetGlobalObject(mContext);
   }
 
   xpc_UnmarkGrayObject(aScopeObject);
 
-  // Safety first: get an object representing the script's principals, i.e.,
-  // the entities who signed this script, or the fully-qualified-domain-name
-  // or "codebase" from which it was loaded.
-  nsCOMPtr<nsIPrincipal> principal = aPrincipal;
-  if (!aPrincipal) {
-    nsCOMPtr<nsIScriptObjectPrincipal> objPrincipal =
-      do_QueryInterface(GetGlobalObject());
-    if (!objPrincipal)
-      return NS_ERROR_FAILURE;
-    principal = objPrincipal->GetPrincipal();
-    if (!principal)
-      return NS_ERROR_FAILURE;
-  }
+  // Ignore the principal that was passed in, and just assert that it matches
+  // the one we pull off the global.
+  nsCOMPtr<nsIPrincipal> principal;
+  nsCOMPtr<nsIScriptObjectPrincipal> objPrincipal = do_QueryInterface(GetGlobalObject());
+  if (!objPrincipal)
+    return NS_ERROR_FAILURE;
+  principal = objPrincipal->GetPrincipal();
+  if (!principal)
+    return NS_ERROR_FAILURE;
+#ifdef DEBUG
+  bool equal = false;
+  principal->Equals(aPrincipal, &equal);
+  MOZ_ASSERT(equal);
+  nsIPrincipal *scopeObjectPrincipal =
+    nsJSPrincipals::get(JS_GetCompartmentPrincipals(js::GetObjectCompartment(aScopeObject)));
+  equal = false;
+  principal->Equals(scopeObjectPrincipal, &equal);
+  MOZ_ASSERT(equal);
+#endif
 
   bool ok = false;
 
   nsresult rv = sSecurityManager->CanExecuteScripts(mContext, principal, &ok);
   if (NS_FAILED(rv)) {
     return NS_ERROR_FAILURE;
   }
 
@@ -1432,19 +1435,16 @@ nsJSContext::EvaluateString(const nsAStr
   }
 
   // The result of evaluation, used only if there were no errors.  This need
   // not be a GC root currently, provided we run the GC only from the
   // operation callback or from ScriptEvaluated.
   jsval val = JSVAL_VOID;
   jsval* vp = aRetValue ? &val : NULL;
 
-  rv = sSecurityManager->PushContextPrincipal(mContext, nsnull, principal);
-  NS_ENSURE_SUCCESS(rv, rv);
-
   nsJSContext::TerminationFuncHolder holder(this);
 
   ++mExecuteDepth;
 
   // SecurityManager said "ok", but don't compile if aVersion is unknown.
   // Since the caller is responsible for parsing the version strings, we just
   // check it isn't JSVERSION_UNKNOWN.
   if (ok && JSVersion(aVersion) != JSVERSION_UNKNOWN) {
@@ -1486,18 +1486,16 @@ nsJSContext::EvaluateString(const nsAStr
 
     if (aRetValue) {
       aRetValue->Truncate();
     }
   }
 
   --mExecuteDepth;
 
-  sSecurityManager->PopContextPrincipal(mContext);
-
   // Pop here, after JS_ValueToString and any other possible evaluation.
   if (NS_FAILED(stack->Pop(nsnull)))
     rv = NS_ERROR_FAILURE;
 
   // ScriptEvaluated needs to come after we pop the stack
   ScriptEvaluated(true);
 
   return rv;
@@ -1585,25 +1583,16 @@ nsJSContext::ExecuteScript(JSScript* aSc
   // called from JS calls back into JS via XPConnect.
   nsresult rv;
   nsCOMPtr<nsIJSContextStack> stack =
            do_GetService("@mozilla.org/js/xpc/ContextStack;1", &rv);
   if (NS_FAILED(rv) || NS_FAILED(stack->Push(mContext))) {
     return NS_ERROR_FAILURE;
   }
 
-  nsCOMPtr<nsIPrincipal> principal;
-  rv = sSecurityManager->GetObjectPrincipal(mContext,
-                                            JS_GetGlobalFromScript(aScriptObject),
-                                            getter_AddRefs(principal));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  rv = sSecurityManager->PushContextPrincipal(mContext, nsnull, principal);
-  NS_ENSURE_SUCCESS(rv, rv);
-
   nsJSContext::TerminationFuncHolder holder(this);
   XPCAutoRequest ar(mContext);
   ++mExecuteDepth;
 
   // The result of evaluation, used only if there were no errors. This need
   // not be a GC root currently, provided we run the GC only from the
   // operation callback or from ScriptEvaluated.
   jsval val;
@@ -1620,18 +1609,16 @@ nsJSContext::ExecuteScript(JSScript* aSc
 
     if (aRetValue) {
       aRetValue->Truncate();
     }
   }
 
   --mExecuteDepth;
 
-  sSecurityManager->PopContextPrincipal(mContext);
-
   // Pop here, after JS_ValueToString and any other possible evaluation.
   if (NS_FAILED(stack->Pop(nsnull)))
     rv = NS_ERROR_FAILURE;
 
   // ScriptEvaluated needs to come after we pop the stack
   ScriptEvaluated(true);
 
   return rv;
@@ -1862,34 +1849,22 @@ nsJSContext::CallEventHandler(nsISupport
   nsJSContext::TerminationFuncHolder holder(this);
 
   if (NS_SUCCEEDED(rv)) {
     // Convert args to jsvals.
     PRUint32 argc = 0;
     jsval *argv = nsnull;
 
     JSObject *funobj = aHandler;
-    nsCOMPtr<nsIPrincipal> principal;
-    rv = sSecurityManager->GetObjectPrincipal(mContext, funobj,
-                                              getter_AddRefs(principal));
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    JSStackFrame *currentfp = nsnull;
-    rv = sSecurityManager->PushContextPrincipal(mContext,
-                                                JS_FrameIterator(mContext, &currentfp),
-                                                principal);
-    NS_ENSURE_SUCCESS(rv, rv);
-
     jsval funval = OBJECT_TO_JSVAL(funobj);
     JSAutoEnterCompartment ac;
     js::ForceFrame ff(mContext, funobj);
     if (!ac.enter(mContext, funobj) || !ff.enter() ||
         !JS_WrapObject(mContext, &target)) {
       ReportPendingException();
-      sSecurityManager->PopContextPrincipal(mContext);
       return NS_ERROR_FAILURE;
     }
 
     Maybe<nsRootedJSValueArray> tempStorage;
 
     // Use |target| as the scope for wrapping the arguments, since aScope is
     // the safe scope in many cases, which isn't very useful.  Wrapping aTarget
     // was OK because those typically have PreCreate methods that give them the
@@ -1922,18 +1897,16 @@ nsJSContext::CallEventHandler(nsISupport
       rv = nsContentUtils::XPConnect()->JSToVariant(mContext, rval, arv);
     }
 
     // Tell XPConnect about any pending exceptions. This is needed
     // to avoid dropping JS exceptions in case we got here through
     // nested calls through XPConnect.
     if (NS_FAILED(rv))
       ReportPendingException();
-
-    sSecurityManager->PopContextPrincipal(mContext);
   }
 
   pusher.Pop();
 
   // ScriptEvaluated needs to come after we pop the stack
   ScriptEvaluated(true);
 
   return rv;
--- a/dom/bindings/Bindings.conf
+++ b/dom/bindings/Bindings.conf
@@ -224,34 +224,35 @@ DOMInterfaces = {
 'XMLHttpRequest': [
 {
     'nativeType': 'nsXMLHttpRequest',
     'prefable': True,
     'infallible': {
         'all': [
             'readyState', 'withCredentials', 'abort', 'statusText',
             'getAllResponseHeaders', 'overrideMimeType', 'mozBackgroundRequest',
-            'multipart', 'channel', 'upload', 'status'
+            'multipart', 'channel', 'upload', 'status', 'mozAnon', 'mozSystem'
         ],
         'getterOnly': [
             'responseType', 'timeout', 'onreadystatechange', 'onuploadprogress'
         ]
     },
     # XXXbz need a JSContext for send() and sendAsBinary because of
     # the old nsIVariant-based signatures which actually use it for
-    # typed arrays.  Once those go away, we can nuke this line.
-    'implicitJSContext': [ 'send', 'sendAsBinary' ],
+    # typed arrays.  Once those go away, we can nuke them from this
+    # list.
+    'implicitJSContext': [ 'constructor', 'send', 'sendAsBinary' ],
     'resultNotAddRefed': [ 'upload', 'responseXML' ]
 },
 {
     'workers': True,
     'nativeType': 'mozilla::dom::workers::XMLHttpRequest',
     'headerFile': 'mozilla/dom/workers/bindings/XMLHttpRequest.h',
     'infallible': {
-        'all': ['readyState', 'statusText' ],
+        'all': ['readyState', 'statusText', 'mozAnon', 'mozSystem' ],
         'getterOnly': [ 'timeout', 'withCredentials', 'mozBackgroundRequest',
                         'responseType', 'responseXML', 'channel', 'multipart' ]
     }
 
 }],
 
 'XMLHttpRequestEventTarget': [
 {
rename from dom/base/BrowserElementChild.js
rename to dom/browser-element/BrowserElementChild.js
--- a/dom/base/BrowserElementChild.js
+++ b/dom/browser-element/BrowserElementChild.js
@@ -2,17 +2,21 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 "use strict";
 
 let Cu = Components.utils;
 let Ci = Components.interfaces;
 let Cc = Components.classes;
+let Cr = Components.results;
+
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+Cu.import("resource://gre/modules/Services.jsm");
+Cu.import("resource://gre/modules/BrowserElementPromptService.jsm");
 
 // Event whitelisted for bubbling.
 let whitelistedEvents = [
   Ci.nsIDOMKeyEvent.DOM_VK_ESCAPE,   // Back button.
   Ci.nsIDOMKeyEvent.DOM_VK_CONTEXT_MENU,
   Ci.nsIDOMKeyEvent.DOM_VK_F5,       // Search button.
   Ci.nsIDOMKeyEvent.DOM_VK_PAGE_UP,  // Volume up.
   Ci.nsIDOMKeyEvent.DOM_VK_PAGE_DOWN // Volume down.
@@ -39,24 +43,29 @@ function sendSyncMsg(msg, data) {
  *
  * Our job here is to listen for events within this frame and bubble them up to
  * the parent process.
  */
 
 var global = this;
 
 function BrowserElementChild() {
+  // Maps outer window id --> weak ref to window.  Used by modal dialog code.
+  this._windowIDDict = {};
+
   this._init();
 };
 
 BrowserElementChild.prototype = {
   _init: function() {
     debug("Starting up.");
     sendAsyncMsg("hello");
 
+    BrowserElementPromptService.mapWindowToBrowserElementChild(content, this);
+
     docShell.QueryInterface(Ci.nsIWebProgress)
             .addProgressListener(this._progressListener,
                                  Ci.nsIWebProgress.NOTIFY_LOCATION |
                                  Ci.nsIWebProgress.NOTIFY_STATE_WINDOW);
 
     // A mozbrowser iframe contained inside a mozapp iframe should return false
     // for nsWindowUtils::IsPartOfApp (unless the mozbrowser iframe is itself
     // also mozapp).  That is, mozapp is transitive down to its children, but
@@ -82,36 +91,172 @@ BrowserElementChild.prototype = {
                      /* useCapture = */ true,
                      /* wantsUntrusted = */ false);
 
     addEventListener('DOMLinkAdded',
                      this._iconChangedHandler.bind(this),
                      /* useCapture = */ true,
                      /* wantsUntrusted = */ false);
 
-    addMessageListener("browser-element-api:get-screenshot",
-                       this._recvGetScreenshot.bind(this));
+    var self = this;
+    function addMsgListener(msg, handler) {
+      addMessageListener('browser-element-api:' + msg, handler.bind(self));
+    }
 
-    addMessageListener("browser-element-api:set-visible",
-                        this._recvSetVisible.bind(this));
+    addMsgListener("get-screenshot", this._recvGetScreenshot);
+    addMsgListener("set-visible", this._recvSetVisible);
+    addMsgListener("unblock-modal-prompt", this._recvStopWaiting);
 
     let els = Cc["@mozilla.org/eventlistenerservice;1"]
                 .getService(Ci.nsIEventListenerService);
 
     // We are using the system group for those events so if something in the
     // content called .stopPropagation() this will still be called.
     els.addSystemEventListener(global, 'keydown',
                                this._keyEventHandler.bind(this),
                                /* useCapture = */ true);
     els.addSystemEventListener(global, 'keypress',
                                this._keyEventHandler.bind(this),
                                /* useCapture = */ true);
     els.addSystemEventListener(global, 'keyup',
                                this._keyEventHandler.bind(this),
                                /* useCapture = */ true);
+    els.addSystemEventListener(global, 'DOMWindowClose',
+                               this._closeHandler.bind(this),
+                               /* useCapture = */ false);
+  },
+
+  _tryGetInnerWindowID: function(win) {
+    let utils = win.QueryInterface(Ci.nsIInterfaceRequestor)
+                   .getInterface(Ci.nsIDOMWindowUtils);
+    try {
+      return utils.currentInnerWindowID;
+    }
+    catch(e) {
+      return null;
+    }
+  },
+
+  /**
+   * Show a modal prompt.  Called by BrowserElementPromptService.
+   */
+  showModalPrompt: function(win, args) {
+    let utils = win.QueryInterface(Ci.nsIInterfaceRequestor)
+                   .getInterface(Ci.nsIDOMWindowUtils);
+
+    args.windowID = { outer: utils.outerWindowID,
+                      inner: this._tryGetInnerWindowID(win) };
+    sendAsyncMsg('showmodalprompt', args);
+
+    let returnValue = this._waitForResult(win);
+
+    if (args.promptType == 'prompt' ||
+        args.promptType == 'confirm') {
+      return returnValue;
+    }
+  },
+
+  /**
+   * Spin in a nested event loop until we receive a unblock-modal-prompt message for
+   * this window.
+   */
+  _waitForResult: function(win) {
+    debug("_waitForResult(" + win + ")");
+    let utils = win.QueryInterface(Ci.nsIInterfaceRequestor)
+                   .getInterface(Ci.nsIDOMWindowUtils);
+
+    let outerWindowID = utils.outerWindowID;
+    let innerWindowID = this._tryGetInnerWindowID(win);
+    if (innerWindowID === null) {
+      // I have no idea what waiting for a result means when there's no inner
+      // window, so let's just bail.
+      debug("_waitForResult: No inner window. Bailing.");
+      return;
+    }
+
+    this._windowIDDict[outerWindowID] = Cu.getWeakReference(win);
+
+    debug("Entering modal state (outerWindowID=" + outerWindowID + ", " +
+                                "innerWindowID=" + innerWindowID + ")");
+
+    // In theory, we're supposed to pass |modalStateWin| back to
+    // leaveModalStateWithWindow.  But in practice, the window is always null,
+    // because it's the window associated with this script context, which
+    // doesn't have a window.  But we'll play along anyway in case this
+    // changes.
+    var modalStateWin = utils.enterModalStateWithWindow();
+
+    // We'll decrement win.modalDepth when we receive a unblock-modal-prompt message
+    // for the window.
+    if (!win.modalDepth) {
+      win.modalDepth = 0;
+    }
+    win.modalDepth++;
+    let origModalDepth = win.modalDepth;
+
+    let thread = Services.tm.currentThread;
+    debug("Nested event loop - begin");
+    while (win.modalDepth == origModalDepth) {
+      // Bail out of the loop if the inner window changed; that means the
+      // window navigated.
+      if (this._tryGetInnerWindowID(win) !== innerWindowID) {
+        debug("_waitForResult: Inner window ID changed " +
+              "while in nested event loop.");
+        break;
+      }
+
+      thread.processNextEvent(/* mayWait = */ true);
+    }
+    debug("Nested event loop - finish");
+
+    // If we exited the loop because the inner window changed, then bail on the
+    // modal prompt.
+    if (innerWindowID !== this._tryGetInnerWindowID(win)) {
+      throw Components.Exception("Modal state aborted by navigation",
+                                 Cr.NS_ERROR_NOT_AVAILABLE);
+    }
+
+    let returnValue = win.modalReturnValue;
+    delete win.modalReturnValue;
+
+    utils.leaveModalStateWithWindow(modalStateWin);
+
+    debug("Leaving modal state (outerID=" + outerWindowID + ", " +
+                               "innerID=" + innerWindowID + ")");
+    return returnValue;
+  },
+
+  _recvStopWaiting: function(msg) {
+    let outerID = msg.json.windowID.outer;
+    let innerID = msg.json.windowID.inner;
+    let returnValue = msg.json.returnValue;
+    debug("recvStopWaiting(outer=" + outerID + ", inner=" + innerID +
+          ", returnValue=" + returnValue + ")");
+
+    if (!this._windowIDDict[outerID]) {
+      debug("recvStopWaiting: No record of outer window ID " + outerID);
+      return;
+    }
+
+    let win = this._windowIDDict[outerID].get();
+    delete this._windowIDDict[outerID];
+
+    if (!win) {
+      debug("recvStopWaiting, but window is gone\n");
+      return;
+    }
+
+    if (innerID !== this._tryGetInnerWindowID(win)) {
+      debug("recvStopWaiting, but inner ID has changed\n");
+      return;
+    }
+
+    debug("recvStopWaiting " + win);
+    win.modalReturnValue = returnValue;
+    win.modalDepth--;
   },
 
   _titleChangedHandler: function(e) {
     debug("Got titlechanged: (" + e.target.title + ")");
     var win = e.target.defaultView;
 
     // Ignore titlechanges which don't come from the top-level
     // <iframe mozbrowser> window.
@@ -137,16 +282,29 @@ BrowserElementChild.prototype = {
         sendAsyncMsg('iconchange', e.target.href);
       }
       else {
         debug("Not top level!");
       }
     }
   },
 
+  _closeHandler: function(e) {
+    let win = e.target;
+    if (win != content || e.defaultPrevented) {
+      return;
+    }
+
+    debug("Closing window " + win);
+    sendAsyncMsg('close');
+
+    // Inform the window implementation that we handled this close ourselves.
+    e.preventDefault();
+  },
+
   _recvGetScreenshot: function(data) {
     debug("Received getScreenshot message: (" + data.json.id + ")");
     var canvas = content.document
       .createElementNS("http://www.w3.org/1999/xhtml", "canvas");
     var ctx = canvas.getContext("2d");
     canvas.mozOpaque = true;
     canvas.height = content.innerHeight;
     canvas.width = content.innerWidth;
@@ -174,18 +332,17 @@ BrowserElementChild.prototype = {
       });
     }
   },
 
   // The docShell keeps a weak reference to the progress listener, so we need
   // to keep a strong ref to it ourselves.
   _progressListener: {
     QueryInterface: XPCOMUtils.generateQI([Ci.nsIWebProgressListener,
-                                           Ci.nsISupportsWeakReference,
-                                           Ci.nsISupports]),
+                                           Ci.nsISupportsWeakReference]),
     _seenLoadStart: false,
 
     onLocationChange: function(webProgress, request, location, flags) {
       // We get progress events from subshells here, which is kind of weird.
       if (webProgress != docShell) {
         return;
       }
 
rename from dom/base/BrowserElementParent.js
rename to dom/browser-element/BrowserElementParent.js
--- a/dom/base/BrowserElementParent.js
+++ b/dom/browser-element/BrowserElementParent.js
@@ -13,16 +13,24 @@ Cu.import("resource://gre/modules/XPCOMU
 
 const NS_PREFBRANCH_PREFCHANGE_TOPIC_ID = "nsPref:changed";
 const BROWSER_FRAMES_ENABLED_PREF = "dom.mozBrowserFramesEnabled";
 
 function debug(msg) {
   //dump("BrowserElementParent - " + msg + "\n");
 }
 
+function sendAsyncMsg(frameElement, msg, data) {
+  let mm = frameElement.QueryInterface(Ci.nsIFrameLoaderOwner)
+                       .frameLoader
+                       .messageManager;
+
+  mm.sendAsyncMessage('browser-element-api:' + msg, data);
+}
+
 /**
  * The BrowserElementParent implements one half of <iframe mozbrowser>.
  * (The other half is, unsurprisingly, BrowserElementChild.)
  *
  * We detect windows and docshells contained inside <iframe mozbrowser>s and
  * inject script to listen for certain events in the child.  We then listen to
  * messages from the child script and take appropriate action here.
  */
@@ -33,30 +41,29 @@ BrowserElementParent.prototype = {
   QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver,
                                          Ci.nsISupportsWeakReference]),
 
   /**
    * Called on app startup, and also when the browser frames enabled pref is
    * changed.
    */
   _init: function() {
-    debug("_init");
-
     if (this._initialized) {
       return;
     }
 
     // If the pref is disabled, do nothing except wait for the pref to change.
     // (This is important for tests, if nothing else.)
     if (!this._browserFramesPrefEnabled()) {
       var prefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch);
       prefs.addObserver(BROWSER_FRAMES_ENABLED_PREF, this, /* ownsWeak = */ true);
       return;
     }
 
+    debug("_init");
     this._initialized = true;
 
     this._screenshotListeners = {};
     this._screenshotReqCounter = 0;
 
     var os = Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);
     os.addObserver(this, 'remote-browser-frame-shown', /* ownsWeak = */ true);
     os.addObserver(this, 'in-process-browser-frame-shown', /* ownsWeak = */ true);
@@ -100,18 +107,20 @@ BrowserElementParent.prototype = {
     }
 
     addMessageListener("hello", this._recvHello);
     addMessageListener("locationchange", this._fireEventFromMsg);
     addMessageListener("loadstart", this._fireEventFromMsg);
     addMessageListener("loadend", this._fireEventFromMsg);
     addMessageListener("titlechange", this._fireEventFromMsg);
     addMessageListener("iconchange", this._fireEventFromMsg);
+    addMessageListener("close", this._fireEventFromMsg);
     addMessageListener("get-mozapp-manifest-url", this._sendMozAppManifestURL);
     addMessageListener("keyevent", this._fireKeyEvent);
+    addMessageListener("showmodalprompt", this._handleShowModalPrompt);
     mm.addMessageListener('browser-element-api:got-screenshot',
                           this._recvGotScreenshot.bind(this));
 
     XPCNativeWrapper.unwrap(frameElement).getScreenshot =
       this._getScreenshot.bind(this, mm, frameElement);
 
     XPCNativeWrapper.unwrap(frameElement).setVisible =
       this._setVisible.bind(this, mm, frameElement);
@@ -124,34 +133,93 @@ BrowserElementParent.prototype = {
     debug("recvHello " + frameElement);
   },
 
   /**
    * Fire either a vanilla or a custom event, depending on the contents of
    * |data|.
    */
   _fireEventFromMsg: function(frameElement, data) {
-    let name = data.name;
+    let name = data.name.substring('browser-element-api:'.length);
     let detail = data.json;
 
-    debug('fireEventFromMsg: ' + name + ' ' + detail);
-    let evtName = name.substring('browser-element-api:'.length);
+    debug('fireEventFromMsg: ' + name + ', ' + detail);
+    let evt = this._createEvent(frameElement, name, detail,
+                                /* cancelable = */ false);
+    frameElement.dispatchEvent(evt);
+  },
+
+  _handleShowModalPrompt: function(frameElement, data) {
+    // Fire a showmodalprmopt event on the iframe.  When this method is called,
+    // the child is spinning in a nested event loop waiting for an
+    // unblock-modal-prompt message.
+    //
+    // If the embedder calls preventDefault() on the showmodalprompt event,
+    // we'll block the child until event.detail.unblock() is called.
+    //
+    // Otherwise, if preventDefault() is not called, we'll send the
+    // unblock-modal-prompt message to the child as soon as the event is done
+    // dispatching.
+
+    let detail = data.json;
+    debug('handleShowPrompt ' + JSON.stringify(detail));
+
+    // Strip off the windowID property from the object we send along in the
+    // event.
+    let windowID = detail.windowID;
+    delete detail.windowID;
+    debug("Event will have detail: " + JSON.stringify(detail));
+    let evt = this._createEvent(frameElement, 'showmodalprompt', detail,
+                                /* cancelable = */ true);
+
+    let unblockMsgSent = false;
+    function sendUnblockMsg() {
+      if (unblockMsgSent) {
+        return;
+      }
+      unblockMsgSent = true;
+
+      // We don't need to sanitize evt.detail.returnValue (e.g. converting the
+      // return value of confirm() to a boolean); Gecko does that for us.
+
+      let data = { windowID: windowID,
+                   returnValue: evt.detail.returnValue };
+      sendAsyncMsg(frameElement, 'unblock-modal-prompt', data);
+    }
+
+    XPCNativeWrapper.unwrap(evt.detail).unblock = function() {
+      sendUnblockMsg();
+    };
+
+    frameElement.dispatchEvent(evt);
+
+    if (!evt.defaultPrevented) {
+      // Unblock the inner frame immediately.  Otherwise we'll unblock upon
+      // evt.detail.unblock().
+      sendUnblockMsg();
+    }
+  },
+
+  _createEvent: function(frameElement, evtName, detail, cancelable) {
     let win = frameElement.ownerDocument.defaultView;
     let evt;
 
     // This will have to change if we ever want to send a CustomEvent with null
     // detail.  For now, it's OK.
     if (detail !== undefined && detail !== null) {
-      evt = new win.CustomEvent('mozbrowser' + evtName, {detail: detail});
+      evt = new win.CustomEvent('mozbrowser' + evtName,
+                                {bubbles: true, cancelable: cancelable,
+                                 detail: detail});
     }
     else {
-      evt = new win.Event('mozbrowser' + evtName);
+      evt = new win.Event('mozbrowser' + evtName,
+                          {bubbles: true, cancelable: cancelable});
     }
 
-    frameElement.dispatchEvent(evt);
+    return evt;
   },
 
   _sendMozAppManifestURL: function(frameElement, data) {
     return frameElement.getAttribute('mozapp');
   },
 
   _recvGotScreenshot: function(data) {
     var req = this._screenshotListeners[data.json.id];
rename from dom/base/BrowserElementParent.manifest
rename to dom/browser-element/BrowserElementParent.manifest
new file mode 100644
--- /dev/null
+++ b/dom/browser-element/BrowserElementPromptService.jsm
@@ -0,0 +1,189 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+/* vim: set ft=javascript : */
+
+"use strict";
+
+let Cu = Components.utils;
+let Ci = Components.interfaces;
+let Cc = Components.classes;
+let Cr = Components.results;
+let Cm = Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
+
+let EXPORTED_SYMBOLS = ["BrowserElementPromptService"];
+
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+
+function debug(msg) {
+  //dump("BrowserElementPromptService - " + msg + "\n");
+}
+
+function BrowserElementPrompt(win, browserElementChild) {
+  this._win = win;
+  this._browserElementChild = browserElementChild;
+}
+
+BrowserElementPrompt.prototype = {
+  QueryInterface: XPCOMUtils.generateQI([Ci.nsIPrompt]),
+
+  alert: function(title, text) {
+    this._browserElementChild.showModalPrompt(
+      this._win, {promptType: "alert", title: title, message: text});
+  },
+
+  alertCheck: function(title, text, checkMsg, checkState) {
+    // Treat this like a normal alert() call, ignoring the checkState.  The
+    // front-end can do its own suppression of the alert() if it wants.
+    this.alert(title, text);
+  },
+
+  confirm: function(title, text) {
+    return this._browserElementChild.showModalPrompt(
+      this._win, {promptType: "confirm", title: title, message: text});
+  },
+
+  confirmCheck: function(title, text, checkMsg, checkState) {
+    return this.confirm(title, text);
+  },
+
+  confirmEx: function(title, text, buttonFlags, button0Title, button1Title, button2Title, checkMsg, checkState) {
+    throw Cr.NS_ERROR_NOT_IMPLEMENTED;
+  },
+
+  prompt: function(title, text, value, checkMsg, checkState) {
+    let rv = this._browserElementChild.showModalPrompt(
+      this._win,
+      { promptType: "prompt",
+        title: title,
+        message: text,
+        initialValue: value.value,
+        returnValue: null });
+
+    value.value = rv;
+
+    // nsIPrompt::Prompt returns true if the user pressed "OK" at the prompt,
+    // and false if the user pressed "Cancel".
+    //
+    // BrowserElementChild returns null for "Cancel" and returns the string the
+    // user entered otherwise.
+    return rv !== null;
+  },
+
+  promptUsernameAndPassword: function(title, text, username, password, checkMsg, checkState) {
+    throw Cr.NS_ERROR_NOT_IMPLEMENTED;
+  },
+
+  promptPassword: function(title, text, password, checkMsg, checkState) {
+    throw Cr.NS_ERROR_NOT_IMPLEMENTED;
+  },
+
+  select: function(title, text, aCount, aSelectList, aOutSelection) {
+    throw Cr.NS_ERROR_NOT_IMPLEMENTED;
+  },
+};
+
+function BrowserElementPromptFactory(toWrap) {
+  this._wrapped = toWrap;
+}
+
+BrowserElementPromptFactory.prototype = {
+  classID: Components.ID("{24f3d0cf-e417-4b85-9017-c9ecf8bb1299}"),
+  QueryInterface: XPCOMUtils.generateQI([Ci.nsIPromptFactory]),
+
+  getPrompt: function(win, iid) {
+    // Try to find a browserelementchild for the window.
+    if (iid.number != Ci.nsIPrompt.number) {
+      debug("Falling back to wrapped prompt service because " +
+            "we don't recognize the requested IID (" + iid + ", " +
+            "nsIPrompt=" + Ci.nsIPrompt);
+      return this._wrapped.getPrompt(win, iid);
+    }
+
+    let browserElementChild =
+      BrowserElementPromptService.getBrowserElementChildForWindow(win);
+    if (!browserElementChild) {
+      debug("Falling back to wrapped prompt service because " +
+            "we can't find a browserElementChild for " +
+            win + ", " + win.location);
+      return this._wrapped.getPrompt(win, iid);
+    }
+
+    debug("Returning wrapped getPrompt for " + win);
+    return new BrowserElementPrompt(win, browserElementChild)
+                                   .QueryInterface(iid);
+  }
+};
+
+let BrowserElementPromptService = {
+  QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver,
+                                         Ci.nsISupportsWeakReference]),
+
+  _init: function() {
+    var os = Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);
+    os.addObserver(this, "outer-window-destroyed", /* ownsWeak = */ true);
+
+    // Wrap the existing @mozilla.org/prompter;1 implementation.
+    var contractID = "@mozilla.org/prompter;1";
+    var oldCID = Cm.contractIDToCID(contractID);
+    var newCID = BrowserElementPromptFactory.prototype.classID;
+    var oldFactory = Cm.getClassObject(Cc[contractID], Ci.nsIFactory);
+
+    if (oldCID == newCID) {
+      debug("WARNING: Wrapped prompt factory is already installed!");
+      return;
+    }
+
+    Cm.unregisterFactory(oldCID, oldFactory);
+
+    var oldInstance = oldFactory.createInstance(null, Ci.nsIPromptFactory);
+    var newInstance = new BrowserElementPromptFactory(oldInstance);
+
+    var newFactory = {
+      createInstance: function(outer, iid) {
+        if (outer != null) {
+          throw Cr.NS_ERROR_NO_AGGREGATION;
+        }
+        return newInstance.QueryInterface(iid);
+      }
+    };
+    Cm.registerFactory(newCID,
+                       "BrowserElementPromptService's prompter;1 wrapper",
+                       contractID, newFactory);
+
+    debug("Done installing new prompt factory.");
+  },
+
+  _getOuterWindowID: function(win) {
+    return win.QueryInterface(Ci.nsIInterfaceRequestor)
+              .getInterface(Ci.nsIDOMWindowUtils)
+              .outerWindowID;
+  },
+
+  _browserElementChildMap: {},
+  mapWindowToBrowserElementChild: function(win, browserElementChild) {
+    this._browserElementChildMap[this._getOuterWindowID(win)] = browserElementChild;
+  },
+
+  getBrowserElementChildForWindow: function(win) {
+    return this._browserElementChildMap[this._getOuterWindowID(win)];
+  },
+
+  _observeOuterWindowDestroyed: function(outerWindowID) {
+    let id = outerWindowID.QueryInterface(Ci.nsISupportsPRUint64).data;
+    debug("observeOuterWindowDestroyed " + id);
+    delete this._browserElementChildMap[outerWindowID.data];
+  },
+
+  observe: function(subject, topic, data) {
+    switch(topic) {
+    case "outer-window-destroyed":
+      this._observeOuterWindowDestroyed(subject);
+      break;
+    default:
+      debug("Observed unexpected topic " + topic);
+    }
+  },
+};
+
+BrowserElementPromptService._init();
new file mode 100644
--- /dev/null
+++ b/dom/browser-element/Makefile.in
@@ -0,0 +1,25 @@
+# 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/.
+
+DEPTH            = ../..
+topsrcdir        = @top_srcdir@
+srcdir           = @srcdir@
+VPATH            = @srcdir@
+
+relativesrcdir   = dom/browser-element
+
+include $(DEPTH)/config/autoconf.mk
+
+TEST_DIRS += mochitest
+
+EXTRA_COMPONENTS = \
+  BrowserElementParent.js \
+  BrowserElementParent.manifest \
+  $(NULL)
+
+EXTRA_JS_MODULES = \
+  BrowserElementPromptService.jsm \
+  $(NULL)
+
+include $(topsrcdir)/config/rules.mk
rename from dom/tests/mochitest/browser-frame/Makefile.in
rename to dom/browser-element/mochitest/Makefile.in
--- a/dom/tests/mochitest/browser-frame/Makefile.in
+++ b/dom/browser-element/mochitest/Makefile.in
@@ -1,18 +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/.
 
-DEPTH		= ../../../..
+DEPTH		= ../../..
 topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
-relativesrcdir  = dom/tests/mochitest/browser-frame
+relativesrcdir  = dom/browser-element/mochitest
 
 include $(DEPTH)/config/autoconf.mk
 include $(topsrcdir)/config/rules.mk
 
 _TEST_FILES = \
 		file_empty.html \
 		file_focus.html \
 		browserFrameHelpers.js \
@@ -22,12 +22,16 @@ include $(topsrcdir)/config/rules.mk
 		test_browserFrame4.html \
 		test_browserFrame5.html \
 		test_browserFrame6.html \
 		test_browserFrame7.html \
 		test_browserFrame8.html \
 		test_browserFrame9.html \
 		test_browserFrame10.html \
 		test_browserFrame_keyEvents.html \
+		test_browserFrameAlert.html \
+		test_browserFramePromptCheck.html \
+		test_browserFramePromptConfirm.html \
+		test_browserFrameClose.html \
 		$(NULL)
 
 libs:: $(_TEST_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/tests/$(relativesrcdir)
rename from dom/tests/mochitest/browser-frame/browserFrameHelpers.js
rename to dom/browser-element/mochitest/browserFrameHelpers.js
--- a/dom/tests/mochitest/browser-frame/browserFrameHelpers.js
+++ b/dom/browser-element/mochitest/browserFrameHelpers.js
@@ -120,12 +120,15 @@ browserFrameHelpers.origPageThumbsEnable
 // Disable tab view; it seriously messes us up.
 browserFrameHelpers.setPageThumbsEnabledPref(false);
 
 // OOP by default, except on Windows, where OOP doesn't work.
 browserFrameHelpers.setOOPByDefaultPref(true);
 if (navigator.platform.indexOf('Win') != -1) {
   browserFrameHelpers.setOOPDisabledPref(true);
 }
+else {
+  browserFrameHelpers.setOOPDisabledPref(false);
+}
 
 addEventListener('unload', function() {
   browserFrameHelpers.restoreOriginalPrefs();
 });
rename from dom/tests/mochitest/browser-frame/file_empty.html
rename to dom/browser-element/mochitest/file_empty.html
rename from dom/tests/mochitest/browser-frame/file_focus.html
rename to dom/browser-element/mochitest/file_focus.html
--- a/dom/tests/mochitest/browser-frame/file_focus.html
+++ b/dom/browser-element/mochitest/file_focus.html
@@ -17,9 +17,8 @@ document.getElementById('url').innerHTML
         alreadyBlocked == false) {
       alreadyBlocked = true;
       e.preventDefault();
     }
   });
 </script>
 </body>
 </html>
-
rename from dom/tests/mochitest/browser-frame/test_browserFrame1.html
rename to dom/browser-element/mochitest/test_browserFrame1.html
rename from dom/tests/mochitest/browser-frame/test_browserFrame10.html
rename to dom/browser-element/mochitest/test_browserFrame10.html
rename from dom/tests/mochitest/browser-frame/test_browserFrame2.html
rename to dom/browser-element/mochitest/test_browserFrame2.html
rename from dom/tests/mochitest/browser-frame/test_browserFrame3.html
rename to dom/browser-element/mochitest/test_browserFrame3.html
rename from dom/tests/mochitest/browser-frame/test_browserFrame4.html
rename to dom/browser-element/mochitest/test_browserFrame4.html
--- a/dom/tests/mochitest/browser-frame/test_browserFrame4.html
+++ b/dom/browser-element/mochitest/test_browserFrame4.html
@@ -85,25 +85,26 @@ function runTest() {
   waitForAllCallbacks();
 }
 
 function runTest2() {
   var seenLoadStart = false;
   var seenLoadEnd = false;
   var seenLocationChange = false;
 
-  var iframe = document.getElementById('iframe');
-  iframe.addEventListener('mozbrowserloadstart', function(e) {
+  // Add this event listener to the document; the events should bubble.
+  document.addEventListener('mozbrowserloadstart', function(e) {
     ok(e.isTrusted, 'Event should be trusted.');
     ok(!seenLoadStart, 'Just one loadstart event.');
     seenLoadStart = true;
     ok(!seenLoadEnd, 'Got mozbrowserloadstart before loadend.');
     ok(!seenLocationChange, 'Got mozbrowserloadstart before locationchange.');
   });
 
+  var iframe = document.getElementById('iframe');
   iframe.addEventListener('mozbrowserlocationchange', function(e) {
     ok(e.isTrusted, 'Event should be trusted.');
     ok(!seenLocationChange, 'Just one locationchange event.');
     seenLocationChange = true;
     ok(seenLoadStart, 'Location change after load start.');
     ok(!seenLoadEnd, 'Location change before load end.');
     ok(e.detail, browserFrameHelpers.emptyPage2, "event's reported location");
   });
rename from dom/tests/mochitest/browser-frame/test_browserFrame5.html
rename to dom/browser-element/mochitest/test_browserFrame5.html
rename from dom/tests/mochitest/browser-frame/test_browserFrame6.html
rename to dom/browser-element/mochitest/test_browserFrame6.html
rename from dom/tests/mochitest/browser-frame/test_browserFrame7.html
rename to dom/browser-element/mochitest/test_browserFrame7.html
--- a/dom/tests/mochitest/browser-frame/test_browserFrame7.html
+++ b/dom/browser-element/mochitest/test_browserFrame7.html
@@ -39,17 +39,17 @@ function runTest() {
   iframe.style.display = 'none';
   document.body.appendChild(iframe);
 
   SimpleTest.waitForExplicitFinish();
 }
 
 var numMsgReceived = 0;
 function outerIframeLoaded() {
-  var injectedScript = 
+  var injectedScript =
     "data:,function is(a, b, desc) {                                     \
       if (a == b) {                                                      \
         sendAsyncMessage('test:test-pass', desc);                        \
       } else {                                                           \
         sendAsyncMessage('test:test-fail', desc + ' ' + a + ' != ' + b); \
       }                                                                  \
     }                                                                    \
     is(content.window.top, content.window, 'top');                       \
@@ -62,17 +62,17 @@ function outerIframeLoaded() {
     is(innerWindow.frameElement, innerIframe, 'inner frameElement');"
 
   var mm = SpecialPowers.getBrowserFrameMessageManager(iframe);
 
   function onRecvTestPass(msg) {
     numMsgReceived++;
     ok(true, msg.json);
   }
-  mm.addMessageListener('test:test-pass', onRecvTestPass); 
+  mm.addMessageListener('test:test-pass', onRecvTestPass);
 
   function onRecvTestFail(msg) {
     numMsgReceived++;
     ok(false, msg.json);
   }
   mm.addMessageListener('test:test-fail', onRecvTestFail);
 
   mm.loadFrameScript(injectedScript, /* allowDelayedLoad = */ false);
@@ -80,17 +80,17 @@ function outerIframeLoaded() {
   waitForMessages(6);
 }
 
 function waitForMessages(num) {
   if (numMsgReceived < num) {
     SimpleTest.executeSoon(function() { waitForMessages(num); });
     return;
   }
-  
+
   SimpleTest.finish();
 }
 
 runTest();
 
 </script>
 </body>
 </html>
rename from dom/tests/mochitest/browser-frame/test_browserFrame8.html
rename to dom/browser-element/mochitest/test_browserFrame8.html
rename from dom/tests/mochitest/browser-frame/test_browserFrame9.html
rename to dom/browser-element/mochitest/test_browserFrame9.html
new file mode 100644
--- /dev/null
+++ b/dom/browser-element/mochitest/test_browserFrameAlert.html
@@ -0,0 +1,180 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=741587
+-->
+<head>
+  <title>Test for Bug 741587</title>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="application/javascript" src="browserFrameHelpers.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=741587">Mozilla Bug 741587</a>
+
+<!--
+  Test that alert works.
+-->
+
+<script type="application/javascript;version=1.7">
+"use strict";
+
+SimpleTest.waitForExplicitFinish();
+
+var numPendingChildTests = 0;
+var iframe;
+var mm;
+
+function runTest() {
+  browserFrameHelpers.setEnabledPref(true);
+  browserFrameHelpers.addToWhitelist();
+
+  iframe = document.createElement('iframe');
+  iframe.mozbrowser = true;
+  document.body.appendChild(iframe);
+
+  mm = SpecialPowers.getBrowserFrameMessageManager(iframe);
+  mm.addMessageListener('test-success', function(msg) {
+    numPendingChildTests--;
+    ok(true, msg.json);
+  });
+  mm.addMessageListener('test-fail', function(msg) {
+    numPendingChildTests--;
+    ok(false, msg.json);
+  });
+
+  // Wait for the initial load to finish, then navigate the page, then wait
+  // for that load to finish, then start test1.
+  iframe.addEventListener('mozbrowserloadend', function loadend() {
+    iframe.removeEventListener('mozbrowserloadend', loadend);
+    iframe.src = browserFrameHelpers.emptyPage1;
+
+    iframe.addEventListener('mozbrowserloadend', function loadend2() {
+      iframe.removeEventListener('mozbrowserloadend', loadend2);
+      SimpleTest.executeSoon(test1);
+    });
+  });
+
+}
+
+function test1() {
+  iframe.addEventListener('mozbrowsershowmodalprompt', test2);
+
+  // Do window.alert within the iframe, then modify the global |testState|
+  // after the alert.
+  var script = 'data:,\
+    testState = 0; \
+    content.alert("Hello, world!"); \
+    testState = 1; \
+  ';
+
+  mm.loadFrameScript(script, /* allowDelayedLoad = */ false);
+
+  // Triggers a mozbrowsershowmodalprompt event, which sends us down to test2.
+}
+
+// test2 is a mozbrowsershowmodalprompt listener.
+function test2(e) {
+  iframe.removeEventListener("mozbrowsershowmodalprompt", test2);
+
+  is(e.detail.message, 'Hello, world!');
+  e.preventDefault(); // cause the alert to block.
+
+  SimpleTest.executeSoon(function() { test2a(e); });
+}
+
+function test2a(e) {
+  // The iframe should be blocked on the alert call at the moment, so testState
+  // should still be 0.
+  var script = 'data:,\
+    if (testState === 0) { \
+      sendAsyncMessage("test-success", "1: Correct testState"); \
+    } \
+    else { \
+      sendAsyncMessage("test-fail", "1: Wrong testState: " + testState); \
+    }';
+
+  mm.loadFrameScript(script, /* allowDelayedLoad = */ false);
+  numPendingChildTests++;
+
+  waitForPendingTests(function() { test3(e); });
+}
+
+function test3(e) {
+  // Now unblock the iframe and check that the script completed.
+  e.detail.unblock();
+
+  var script2 = 'data:,\
+    if (testState === 1) { \
+      sendAsyncMessage("test-success", "2: Correct testState"); \
+    } \
+    else { \
+      sendAsyncMessage("test-try-again", "2: Wrong testState (for now): " + testState); \
+    }';
+
+  // Urgh.  e.unblock() didn't necessarily unblock us immediately, so we have
+  // to spin and wait.
+  function onTryAgain() {
+    SimpleTest.executeSoon(function() {
+      //dump('onTryAgain\n');
+      mm.loadFrameScript(script2, /* allowDelayedLoad = */ false);
+    });
+  }
+
+  mm.addMessageListener('test-try-again', onTryAgain);
+  numPendingChildTests++;
+
+  onTryAgain();
+  waitForPendingTests(function() { test4(); });
+}
+
+function test4() {
+  // Navigate the iframe while an alert is pending.  This shouldn't screw
+  // things up.
+
+  iframe.addEventListener("mozbrowsershowmodalprompt", test5);
+
+  var script = 'data:,content.alert("test4");';
+  mm.loadFrameScript(script, /* allowDelayedLoad = */ false);
+}
+
+// test4 is a mozbrowsershowmodalprompt listener.
+function test5(e) {
+  iframe.removeEventListener('mozbrowsershowmodalprompt', test4);
+
+  is(e.detail.message, 'test4');
+  e.preventDefault(); // cause the page to block.
+
+  SimpleTest.executeSoon(test5a);
+}
+
+function test5a() {
+  iframe.addEventListener('mozbrowserloadend', test5b);
+  iframe.src = browserFrameHelpers.emptyPage2;
+}
+
+function test5b() {
+  iframe.removeEventListener('mozbrowserloadend', test5b);
+  SimpleTest.finish();
+}
+
+var prevNumPendingTests = null;
+function waitForPendingTests(next) {
+  if (numPendingChildTests !== prevNumPendingTests) {
+    dump("Waiting for end; " + numPendingChildTests + " pending tests\n");
+    prevNumPendingTests = numPendingChildTests;
+  }
+
+  if (numPendingChildTests > 0) {
+    SimpleTest.executeSoon(function() { waitForPendingTests(next); });
+    return;
+  }
+
+  prevNumPendingTests = null;
+  next();
+}
+
+runTest();
+</script>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/dom/browser-element/mochitest/test_browserFrameClose.html
@@ -0,0 +1,43 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=757182
+-->
+<head>
+  <title>Test for Bug 757182</title>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="application/javascript" src="browserFrameHelpers.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=757182">Mozilla Bug 757182</a>
+
+<!--
+  Test that window.close() works.
+-->
+
+<script type="application/javascript;version=1.7">
+"use strict";
+
+SimpleTest.waitForExplicitFinish();
+
+function runTest() {
+  browserFrameHelpers.setEnabledPref(true);
+  browserFrameHelpers.addToWhitelist();
+
+  var iframe = document.createElement('iframe');
+  iframe.mozbrowser = true;
+  document.body.appendChild(iframe);
+
+  iframe.addEventListener("mozbrowserclose", function(e) {
+    ok(true, "got mozbrowserclose event.");
+    SimpleTest.finish();
+  });
+
+  iframe.src = "data:text/html,<html><body><script>window.close()</scr"+"ipt></body></html>";
+}
+
+runTest();
+</script>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/dom/browser-element/mochitest/test_browserFramePromptCheck.html
@@ -0,0 +1,83 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=741587
+-->
+<head>
+  <title>Test for Bug 741587</title>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="application/javascript" src="browserFrameHelpers.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=741587">Mozilla Bug 741587</a>
+
+<!--
+  Test that alertCheck (i.e., alert with the opportunity to opt out of future
+  alerts), promptCheck, and confirmCheck work.  We do this by spamming
+  alerts/prompts/confirms from inside an <iframe mozbrowser>.
+
+  At the moment, we treat alertCheck/promptCheck/confirmCheck just like a
+  normal alert.  But it's different to nsIPrompt!
+-->
+
+<script type="application/javascript;version=1.7">
+"use strict";
+
+SimpleTest.waitForExplicitFinish();
+
+browserFrameHelpers.setEnabledPref(true);
+browserFrameHelpers.addToWhitelist();
+
+// Test harness sets dom.successive_dialog_time_limit to 0 for some bizarre
+// reason.  That's not normal usage, and it keeps us from testing alertCheck!
+const dialogTimeLimitPrefName = 'dom.successive_dialog_time_limit';
+var oldDialogTimeLimitPref;
+try {
+  oldDialogTimeLimitPref = SpecialPowers.getIntPref(dialogTimeLimitPrefName);
+}
+catch(e) {}
+
+SpecialPowers.setIntPref(dialogTimeLimitPrefName, 10);
+
+var iframe = document.createElement('iframe');
+iframe.mozbrowser = true;
+document.body.appendChild(iframe);
+
+var numPrompts = 0;
+iframe.addEventListener('mozbrowsershowmodalprompt', function(e) {
+  is(e.detail.message, numPrompts, "prompt message");
+  if (numPrompts / 10 < 1) {
+    is(e.detail.promptType, 'alert');
+  }
+  else if (numPrompts / 10 < 2) {
+    is(e.detail.promptType, 'confirm');
+  }
+  else {
+    is(e.detail.promptType, 'prompt');
+  }
+
+  numPrompts++;
+  if (numPrompts == 30) {
+    if (oldDialogTimeLimitPref !== undefined) {
+      SpecialPowers.setIntPref(dialogTimeLimitPrefName, oldDialogTimeLimitPref);
+    }
+    else {
+      SpecialPowers.clearUserPref(dialogTimeLimitPrefName);
+    }
+
+    SimpleTest.finish();
+  }
+});
+
+iframe.src =
+  'data:text/html,<html><body><script>\
+    var i = 0; \
+    for (; i < 10; i++) { alert(i); } \
+    for (; i < 20; i++) { confirm(i); } \
+    for (; i < 30; i++) { prompt(i); } \
+   </scr' + 'ipt></body></html>';
+
+</script>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/dom/browser-element/mochitest/test_browserFramePromptConfirm.html
@@ -0,0 +1,106 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=741587
+-->
+<head>
+  <title>Test for Bug 741587</title>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="application/javascript" src="browserFrameHelpers.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=741587">Mozilla Bug 741587</a>
+
+<!--
+  Test that prompt and confirm work.  In particular, we're concerned that we
+  get correct return values out of them.
+
+  We use alert() to communicate the return values of prompt/confirm back to
+  ourselves.
+-->
+
+<script type="application/javascript;version=1.7">
+"use strict";
+
+SimpleTest.waitForExplicitFinish();
+
+function runTest() {
+  browserFrameHelpers.setEnabledPref(true);
+  browserFrameHelpers.addToWhitelist();
+
+  var iframe = document.createElement('iframe');
+  iframe.mozbrowser = true;
+  document.body.appendChild(iframe);
+
+  var prompts = [
+    {msg: 1, type: 'alert', rv: 42, expected: 'undefined'},
+    {msg: 2, type: 'confirm', rv: true, expected: 'true'},
+    {msg: 3, type: 'confirm', rv: false, expected: 'false'},
+
+    // rv == 42 should be coerced to 'true' for confirm.
+    {msg: 4, type: 'confirm', rv: 42, expected: 'true'},
+    {msg: 5, type: 'prompt', rv: 'worked', expected: 'worked'},
+    {msg: 6, type: 'prompt', rv: null, expected: 'null'},
+    {msg: 7, type: 'prompt', rv: '', expected: ''}
+  ];
+
+  iframe.addEventListener("mozbrowsershowmodalprompt", function(e) {
+    var curPrompt = prompts[0];
+    if (!curPrompt.waitingForResponse) {
+      curPrompt.waitingForResponse = true;
+
+      is(e.detail.message, curPrompt.msg, "prompt message");
+      is(e.detail.promptType, curPrompt.type, "prompt type");
+
+      if (e.detail.promptType == 'prompt') {
+        ok(e.detail.returnValue === null, "prompt's returnValue should be null");
+        is(e.detail.initialValue, "initial", "prompt's initial value.");
+      }
+      else {
+        ok(e.detail.returnValue === undefined,
+           "Other than for prompt, shouldn't have initial value.");
+      }
+
+      // Block the child until we call e.detail.unblock().
+      e.preventDefault();
+
+      SimpleTest.executeSoon(function() {
+        e.detail.returnValue = curPrompt.rv;
+        e.detail.unblock();
+      });
+    }
+    else {
+      prompts.shift();
+
+      // |e| now corresponds to an alert() containing the return value we just
+      // sent for this prompt.
+
+      is(e.detail.message, 'RESULT:' + curPrompt.expected,
+         "expected rv for msg " + curPrompt.msg);
+
+      if (prompts.length == 0) {
+        SimpleTest.finish();
+      }
+    }
+  });
+
+  iframe.src =
+    'data:text/html,<html><body><script>\
+      function sendVal(val) { \
+        alert("RESULT:" + val); \
+      } \
+      sendVal(alert("1")); \
+      sendVal(confirm("2")); \
+      sendVal(confirm("3")); \
+      sendVal(confirm("4")); \
+      sendVal(prompt("5", "initial")); \
+      sendVal(prompt("6", "initial")); \
+      sendVal(prompt("7", "initial")); \
+    </scr' + 'ipt></body></html>';
+}
+
+runTest();
+</script>
+</body>
+</html>
rename from dom/tests/mochitest/browser-frame/test_browserFrame_keyEvents.html
rename to dom/browser-element/mochitest/test_browserFrame_keyEvents.html
--- a/dom/imptests/failures/html/tests/submission/Opera/microdata/test_001.html.json
+++ b/dom/imptests/failures/html/tests/submission/Opera/microdata/test_001.html.json
@@ -1,8 +1,7 @@
 {
   "document.getItems must return a NodeList": true,
   "itemValue must reflect the src attribute on track elements": true,
   "itemValue must reflect the textContent of time elements with no datetime attribute": true,
-  "itemValue must reflect the datetime attribute of time elements with a datetime attribute": true,
-  "the namedItem property must be read/write": true
+  "itemValue must reflect the datetime attribute of time elements with a datetime attribute": true
 }
 
--- a/dom/interfaces/settings/nsIDOMSettingsManager.idl
+++ b/dom/interfaces/settings/nsIDOMSettingsManager.idl
@@ -16,21 +16,24 @@ interface nsIDOMSettingsLock : nsISuppor
   nsIDOMDOMRequest set(in nsIVariant settings);
 
   // result contains the value of the setting.
   nsIDOMDOMRequest get(in jsval name);
 
   nsIDOMDOMRequest clear();
 };
 
-[scriptable, uuid(5609d0a0-52a9-11e1-b86c-0800200c9a66)]
+[scriptable, uuid(dd9f5380-a454-11e1-b3dd-0800200c9a66)]
 interface nsIDOMSettingsManager : nsISupports
 {
   nsIDOMSettingsLock getLock();
 
+  void addObserver(in DOMString name, in jsval callback);
+  void removeObserver(in DOMString name, in jsval callback);
+
   attribute nsIDOMEventListener onsettingchange;
 };
 
 [scriptable, uuid(5ce02690-52a9-11e1-b86c-0800200c9a66)]
 interface nsIDOMMozSettingsEvent : nsIDOMEvent
 {
   readonly attribute DOMString  settingName;
   readonly attribute nsIVariant settingValue;
--- a/dom/ipc/jar.mn
+++ b/dom/ipc/jar.mn
@@ -1,8 +1,8 @@
 # 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/.
 
 toolkit.jar:
         content/global/test-ipc.xul (test.xul)
         content/global/remote-test-ipc.js (remote-test.js)
-        content/global/BrowserElementChild.js (../base/BrowserElementChild.js)
+        content/global/BrowserElementChild.js (../browser-element/BrowserElementChild.js)
--- a/dom/settings/SettingsManager.js
+++ b/dom/settings/SettingsManager.js
@@ -38,17 +38,17 @@ SettingsLock.prototype = {
 
   process: function process() {
     let lock = this;
     lock._open = false;
     let store = lock._transaction.objectStore(SETTINGSSTORE_NAME);
 
     while (!lock._requests.isEmpty()) {
       let info = lock._requests.dequeue();
-      debug("info:" + info.intent);
+      debug("info: " + info.intent);
       let request = info.request;
       switch (info.intent) {
         case "clear":
           let req = store.clear();
           req.onsuccess = function() { this._open = true;
                                        Services.DOMRequest.fireSuccess(request, 0);
                                        this._open = false; }.bind(lock);
           req.onerror = function() { Services.DOMRequest.fireError(request, 0) };
@@ -183,32 +183,33 @@ SettingsLock.prototype = {
   classInfo : XPCOMUtils.generateCI({classID: SETTINGSLOCK_CID,
                                      contractID: SETTINGSLOCK_CONTRACTID,
                                      classDescription: "SettingsLock",
                                      interfaces: [nsIDOMSettingsLock],
                                      flags: nsIClassInfo.DOM_OBJECT})
 };
 
 const SETTINGSMANAGER_CONTRACTID = "@mozilla.org/settingsManager;1";
-const SETTINGSMANAGER_CID        = Components.ID("{5609d0a0-52a9-11e1-b86c-0800200c9a66}");
+const SETTINGSMANAGER_CID        = Components.ID("{dd9f5380-a454-11e1-b3dd-0800200c9a66}");
 const nsIDOMSettingsManager      = Ci.nsIDOMSettingsManager;
 
 let myGlobal = this;
 
 function SettingsManager()
 {
   this._locks = new Queue();
   var idbManager = Components.classes["@mozilla.org/dom/indexeddb/manager;1"].getService(Ci.nsIIndexedDatabaseManager);
   idbManager.initWindowless(myGlobal);
   this._settingsDB = new SettingsDB();
   this._settingsDB.init(myGlobal);
 }
 
 SettingsManager.prototype = {
   _onsettingchange: null,
+  _callbacks: null,
 
   nextTick: function nextTick(aCallback, thisObj) {
     if (thisObj)
       aCallback = aCallback.bind(thisObj);
 
     Services.tm.currentThread.dispatch(aCallback, Ci.nsIThread.DISPATCH_NORMAL);
   },
 
@@ -237,32 +238,68 @@ SettingsManager.prototype = {
 
   receiveMessage: function(aMessage) {
     debug("Settings::receiveMessage: " + aMessage.name);
     let msg = aMessage.json;
 
     switch (aMessage.name) {
       case "Settings:Change:Return:OK":
         debug("Settings:Change:Return:OK");
-        if (!this._onsettingchange)
-          return;
+        if (this._onsettingchange || this._callbacks) {
+          debug('data:' + msg.key + ':' + msg.value + '\n');
 
-        debug('key:' + msg.key + ', value:' + msg.value + '\n');
-        let event = new this._window.MozSettingsEvent("settingchanged", {
-          settingName: msg.key,
-          settingValue: msg.value
-        });
-
-        this._onsettingchange.handleEvent(event);
+          if (this._onsettingchange) {
+            let event = new this._window.MozSettingsEvent("settingchanged", {
+              settingName: msg.key,
+              settingValue: msg.value
+            });
+            this._onsettingchange.handleEvent(event);
+          }
+          if (this._callbacks && this._callbacks[msg.key]) {
+            debug("observe callback called! " + msg.key + " " + this._callbacks[msg.key].length);
+            for (let cb in this._callbacks[msg.key]) {
+              this._callbacks[msg.key].forEach(function(cb) {
+                cb({settingName: msg.key, settingValue: msg.value});
+              });
+            }
+          }
+        } else {
+          debug("no observers stored!");
+        }
         break;
       default: 
         debug("Wrong message: " + aMessage.name);
     }
   },
 
+  addObserver: function addObserver(aName, aCallback) {
+    debug("addObserver " + aName);
+    if (!this._callbacks)
+      this._callbacks = {};
+    if (!this._callbacks[aName]) {
+      this._callbacks[aName] = [aCallback];
+    } else {
+      this._callbacks[aName].push(aCallback);
+    }
+  },
+
+  removeObserver: function removeObserver(aName, aCallback) {
+    debug("deleteObserver " + aName);
+    if (this._callbacks && this._callbacks[aName]) {
+      let index = this._callbacks[aName].indexOf(aCallback)
+      if (index != -1) {
+        this._callbacks[aName].splice(index, 1)
+      } else {
+        debug("Callback not found for: " + aName);
+      }
+    } else {
+      debug("No observers stored for " + aName);
+    }
+  },
+
   init: function(aWindow) {
     // Set navigator.mozSettings to null.
     if (!Services.prefs.getBoolPref("dom.mozSettings.enabled"))
       return null;
 
     cpmm.addMessageListener("Settings:Change:Return:OK", this);
     this._window = aWindow;
     Services.obs.addObserver(this, "inner-window-destroyed", false);
@@ -285,17 +322,16 @@ SettingsManager.prototype = {
       if (wId == this.innerWindowID) {
         Services.obs.removeObserver(this, "inner-window-destroyed");
         cpmm.removeMessageListener("Settings:Change:Return:OK", this);
         this._requests = null;
         this._window = null;
         this._innerWindowID = null;
         this._onsettingchange = null;
         this._settingsDB.close();
-        cpmm = null;
       }
     }
   },
 
   classID : SETTINGSMANAGER_CID,
   QueryInterface : XPCOMUtils.generateQI([nsIDOMSettingsManager, Ci.nsIDOMGlobalPropertyInitializer]),
 
   classInfo : XPCOMUtils.generateCI({classID: SETTINGSMANAGER_CID,
--- a/dom/settings/SettingsManager.manifest
+++ b/dom/settings/SettingsManager.manifest
@@ -1,6 +1,6 @@
-component {5609d0a0-52a9-11e1-b86c-0800200c9a66} SettingsManager.js
-contract @mozilla.org/settingsManager;1 {5609d0a0-52a9-11e1-b86c-0800200c9a66}
+component {dd9f5380-a454-11e1-b3dd-0800200c9a66} SettingsManager.js
+contract @mozilla.org/settingsManager;1 {dd9f5380-a454-11e1-b3dd-0800200c9a66}
 category JavaScript-navigator-property mozSettings @mozilla.org/settingsManager;1
 
 component {ef95ddd0-6308-11e1-b86c-0800200c9a66} SettingsManager.js
 contract @mozilla.org/settingsLock;1 {ef95ddd0-6308-11e1-b86c-0800200c9a66}
--- a/dom/settings/tests/test_settings_basics.html
+++ b/dom/settings/tests/test_settings_basics.html
@@ -57,16 +57,38 @@ function equals(o1, o2) {
     if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
       return equals(o1[keyPair[0]], o2[keyPair[1]])
     } else {
       return o1[keyPair[0]] == o2[keyPair[1]];
     }
   }).all();
 };
 
+function observer1(setting) {
+  is(setting.settingName, "screen.brightness", "Same settingName");
+  is(setting.settingValue, "0.7", "Same settingvalue");
+};
+
+function observer2(setting) {
+  is(setting.settingName, "screen.brightness", "Same settingName");
+  is(setting.settingValue, "0.7", "Same settingvalue");
+};
+
+function observerWithNext(setting) {
+  is(setting.settingName, "screen.brightness", "Same settingName");
+  is(setting.settingValue, "0.7", "Same settingvalue");
+  next();
+};
+
+function onsettingschangeWithNext(event) {
+  is(event.settingName, "screen.brightness", "Same settingName");
+  is(event.settingValue, "0.7", "Same settingvalue");
+  next();
+};
+
 function check(o1, o2) {
   is(JSON.stringify(o1), JSON.stringify(o2), "same");
 }
 
 var req, req2, req3, req4, req5, req6;
 var index = 0;
 
 var mozSettings = window.navigator.mozSettings;
@@ -83,35 +105,118 @@ var steps = [
     req2 = lock.set(screenBright);
     req2.onsuccess = function () {
       ok(true, "set done");
       next();
     }
     req2.onerror = onFailure;
   },
   function() {
-    ok(true, "adding Event Listener2");
-    navigator.mozSettings.onsettingchange = function(event) {
-      is(event.settingName, "screen.brightness", "Same settingName");
-      is(event.settingValue, "0.7", "Same settingvalue");
-    }
+    ok(true, "adding onsettingchange");
+    navigator.mozSettings.onsettingchange = onsettingschangeWithNext;
     var lock = mozSettings.getLock();
     req2 = lock.get("screen.brightness");
     req2.onsuccess = function() {
+      ok(true, "end adding onsettingchange");
       next();
     };
     req2.onerror = onFailure;
   },
   function() {
-    ok(true, "adding Event Listener");
+    ok(true, "Test onsettingchange");
+    var lock = mozSettings.getLock();
+    req = lock.set(screenBright);
+    req.onsuccess = function () {
+      ok(true, "set done, observer has to call next");
+    }
+    req.onerror = onFailure;
+  },
+  function() {
+    ok(true, "delete onsettingschange");
+    var lock = mozSettings.getLock();
+    navigator.mozSettings.onsettingchange = null;
+    req = lock.set(screenBright);
+    req.onsuccess = function () {
+      ok(true, "set done");
+      next();
+    }
+    req.onerror = onFailure;
+  },
+  function () {
+    ok(true, "Waiting for all set callbacks");
+    var lock = mozSettings.getLock();
+    req = lock.get("screen.brightness");
+    req.onsuccess = function() {
+      ok(true, "Done");
+      next();
+    }
+    req.onerror = onFailure;
+  },
+  function() {
+    ok(true, "adding Observers 1");
+    navigator.mozSettings.addObserver("screen.brightness", observer1);
+    navigator.mozSettings.addObserver("screen.brightness", observer1);
+    navigator.mozSettings.addObserver("screen.brightness", observer2);
+    navigator.mozSettings.addObserver("screen.brightness", observerWithNext);
+    var lock = mozSettings.getLock();
+    req2 = lock.get("screen.brightness");
+    req2.onsuccess = function() {
+      ok(true, "set observeSetting done!");
+      next();
+    };
+    req2.onerror = onFailure;
+  },
+  function() {
+    ok(true, "test observers");
     var lock = mozSettings.getLock();
     req = lock.set(screenBright);
     req.onsuccess = function () {
       ok(true, "set done");
-      navigator.mozSettings.onsettingchange = null;
+    }
+    req.onerror = onFailure;
+  },
+  function() {
+    ok(true, "removing Event Listener");
+    var lock = mozSettings.getLock();
+    req = lock.set(screenBright);
+    req.onsuccess = function () {
+      ok(true, "set done");
+      navigator.mozSettings.removeObserver("screen.brightness", observer2);
+      navigator.mozSettings.removeObserver("screen.brightness", observer1);
+    }
+    req.onerror = onFailure;
+  },
+  function() {
+    ok(true, "test Event Listener");
+    var lock = mozSettings.getLock();
+    req = lock.set(screenBright);
+    req.onsuccess = function () {
+      ok(true, "set done");
+    }
+    req.onerror = onFailure;
+  },
+  function() {
+    ok(true, "removing Event Listener");
+    var lock = mozSettings.getLock();
+    navigator.mozSettings.removeObserver("screen.brightness", observerWithNext);
+    req = lock.set(screenBright);
+    req.onsuccess = function () {
+      ok(true, "set done");
+      navigator.mozSettings.removeObserver("screen.brightness", observer2);
+      navigator.mozSettings.removeObserver("screen.brightness", observer1);
+      next();
+    }
+    req.onerror = onFailure;
+  },
+  function() {
+    ok(true, "removing Event Listener");
+    var lock = mozSettings.getLock();
+    req = lock.get("screen.brightness");
+    req.onsuccess = function () {
+      ok(true, "get done");
       next();
     }
     req.onerror = onFailure;
   },
   function () {
     ok(true, "Nested test");
     var lock = mozSettings.getLock();
     req = lock.get("screen.brightness");
--- a/dom/src/json/nsJSON.cpp
+++ b/dom/src/json/nsJSON.cpp
@@ -172,42 +172,25 @@ NS_IMETHODIMP
 nsJSON::EncodeFromJSVal(JS::Value *value, JSContext *cx, nsAString &result)
 {
   result.Truncate();
 
   // Begin a new request
   JSAutoRequest ar(cx);
 
   JSAutoEnterCompartment ac;
-  nsIScriptSecurityManager *ssm = nsnull;
   if (value->isObject()) {
     JSObject *obj = &value->toObject();
     if (!ac.enter(cx, obj)) {
       return NS_ERROR_FAILURE;
     }
-
-    nsCOMPtr<nsIPrincipal> principal;
-    ssm = nsContentUtils::GetSecurityManager();
-    nsresult rv = ssm->GetObjectPrincipal(cx, obj, getter_AddRefs(principal));
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    JSStackFrame *fp = nsnull;
-    rv = ssm->PushContextPrincipal(cx, JS_FrameIterator(cx, &fp), principal);
-    NS_ENSURE_SUCCESS(rv, rv);
   }
 
   nsJSONWriter writer;
-  JSBool ok = JS_Stringify(cx, value, NULL, JSVAL_NULL,
-                           WriteCallback, &writer);
-
-  if (ssm) {
-    ssm->PopContextPrincipal(cx);
-  }
-
-  if (!ok) {
+  if (!JS_Stringify(cx, value, NULL, JSVAL_NULL, WriteCallback, &writer)) {
     return NS_ERROR_XPC_BAD_CONVERT_JS;
   }
 
   NS_ENSURE_TRUE(writer.DidWrite(), NS_ERROR_UNEXPECTED);
   writer.FlushBuffer();
   result.Assign(writer.mOutputString);
   return NS_OK;
 }
--- a/dom/system/nsDeviceSensors.cpp
+++ b/dom/system/nsDeviceSensors.cpp
@@ -113,16 +113,27 @@ nsDeviceSensors::~nsDeviceSensors()
       UnregisterSensorObserver((SensorType)i, this);
   }
 
   for (int i = 0; i < NUM_SENSOR_TYPE; i++) {
     delete mWindowListeners[i];
   }
 }
 
+NS_IMETHODIMP nsDeviceSensors::ListenerCount(PRUint32 aType, PRInt32 *aRetVal)
+{
+  if (!mEnabled) {
+    *aRetVal = 0;
+    return NS_OK;
+  }
+
+  *aRetVal = mWindowListeners[aType]->Length();
+  return NS_OK;
+}
+
 NS_IMETHODIMP nsDeviceSensors::AddWindowListener(PRUint32 aType, nsIDOMWindow *aWindow)
 {
   if (!mEnabled)
     return NS_OK;
 
   if (mWindowListeners[aType]->IndexOf(aWindow) != NoIndex)
     return NS_OK;
 
--- a/dom/tests/mochitest/Makefile.in
+++ b/dom/tests/mochitest/Makefile.in
@@ -22,17 +22,16 @@ DIRS	+= \
 	general \
 	whatwg \
 	geolocation \
 	localstorage \
 	orientation \
 	sessionstorage \
 	storageevent \
 	pointerlock \
-	browser-frame \
 	webapps \
 	$(NULL)
 
 #needs IPC support, also tests do not run successfully in Firefox for now
 #ifneq (mobile,$(MOZ_BUILD_APP))
 #DIRS	+= notification
 #endif
 
--- a/dom/tests/mochitest/whatwg/postMessage_chrome_helper.html
+++ b/dom/tests/mochitest/whatwg/postMessage_chrome_helper.html
@@ -32,19 +32,17 @@
           msg += " wrong-message(" + evt.data + ")";
 
         respond(msg);
       }
     }
     
     function respond(msg)
     {
-      // ...so get privileges and test that this works with privileges
-      netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-      window.parent.postMessage(msg, "*");
+      SpecialPowers.wrap(window).parent.postMessage(msg, "*");
     }
     
     window.addEventListener("message", receiveMessage, false);
   </script>
 </head>
 <body>
 <h1 id="domain">example.org</h1>
 </body>
--- a/dom/tests/mochitest/whatwg/test_postMessage_chrome.html
+++ b/dom/tests/mochitest/whatwg/test_postMessage_chrome.html
@@ -88,20 +88,16 @@ function chromePathIsSet(evt)
 
 /*************
  * RECEIVERS *
  *************/
 
 function receiveContent(evt)
 {
   is(evt.isTrusted, true, "should have sent a trusted event");
-  is(evt.origin, "http://example.org", "content response event has wrong URI");
-  is(evt.source, window.frames.contentDomain,
-     "wrong source for same-domain message!");
-
   finish();
 }
 
 
 /**************
  * TEST SETUP *
  **************/
 
--- a/dom/webidl/XMLHttpRequest.webidl
+++ b/dom/webidl/XMLHttpRequest.webidl
@@ -26,17 +26,17 @@ enum XMLHttpRequestResponseType {
   "text",
 
   // Mozilla-specific stuff
   "moz-chunked-text",
   "moz-chunked-arraybuffer",
   "moz-blob"
 };
 
-[Constructor]
+[Constructor(optional any params)]
 interface XMLHttpRequest : XMLHttpRequestEventTarget {
   // event handler
   [TreatNonCallableAsNull] attribute Function? onreadystatechange;
 
   // states
   const unsigned short UNSENT = 0;
   const unsigned short OPENED = 1;
   const unsigned short HEADERS_RECEIVED = 2;
@@ -75,9 +75,11 @@ interface XMLHttpRequest : XMLHttpReques
 
   // Mozilla-specific stuff
   attribute boolean multipart;
   attribute boolean mozBackgroundRequest;
   [ChromeOnly] readonly attribute MozChannel channel;
   void sendAsBinary(DOMString body);
   any getInterface(IID iid);
   [TreatNonCallableAsNull] attribute Function? onuploadprogress;
+  readonly attribute boolean mozAnon;
+  readonly attribute boolean mozSystem;
 };
--- a/dom/workers/XMLHttpRequest.cpp
+++ b/dom/workers/XMLHttpRequest.cpp
@@ -1458,28 +1458,33 @@ void
 XMLHttpRequest::_finalize(JSFreeOp* aFop)
 {
   ReleaseProxy(XHRIsGoingAway);
   XMLHttpRequestEventTarget::_finalize(aFop);
 }
 
 // static
 XMLHttpRequest*
-XMLHttpRequest::Constructor(JSContext* aCx, JSObject* aGlobal, ErrorResult& aRv)
+XMLHttpRequest::Constructor(JSContext* aCx,
+                            JSObject* aGlobal,
+                            const Optional<jsval>& aParams,
+                            ErrorResult& aRv)
 {
   WorkerPrivate* workerPrivate = GetWorkerPrivateFromContext(aCx);
   MOZ_ASSERT(workerPrivate);
 
   nsRefPtr<XMLHttpRequest> xhr = new XMLHttpRequest(aCx, workerPrivate);
 
   if (!Wrap(aCx, aGlobal, xhr)) {
     aRv.Throw(NS_ERROR_FAILURE);
     return NULL;
   }
 
+  // TODO: process aParams. See bug 761227
+
   xhr->mJSObject = xhr->GetJSObject();
   return xhr;
 }
 
 void
 XMLHttpRequest::ReleaseProxy(ReleaseType aType)
 {
   // Can't assert that we're on the worker thread here because mWorkerPrivate
--- a/dom/workers/XMLHttpRequest.h
+++ b/dom/workers/XMLHttpRequest.h
@@ -7,16 +7,17 @@
 #define mozilla_dom_workers_xmlhttprequest_h__
 
 #include "mozilla/dom/workers/bindings/XMLHttpRequestEventTarget.h"
 #include "mozilla/dom/workers/bindings/WorkerFeature.h"
 
 // Need this for XMLHttpRequestResponseType.
 #include "mozilla/dom/XMLHttpRequestBinding.h"
 
+#include "mozilla/dom/BindingUtils.h"
 #include "mozilla/dom/TypedArray.h"
 
 BEGIN_WORKERS_NAMESPACE
 
 class Proxy;
 class XMLHttpRequestUpload;
 class WorkerPrivate;
 
@@ -65,18 +66,18 @@ protected:
 public:
   virtual void
   _trace(JSTracer* aTrc) MOZ_OVERRIDE;
 
   virtual void
   _finalize(JSFreeOp* aFop) MOZ_OVERRIDE;
 
   static XMLHttpRequest*
-  Constructor(JSContext* aCx, JSObject* aGlobal, ErrorResult& aRv);
-
+  Constructor(JSContext* aCx, JSObject* aGlobal,
+              const Optional<jsval>& aParams, ErrorResult& aRv);
   void
   Unpin();
 
   bool
   Notify(JSContext* aCx, Status aStatus) MOZ_OVERRIDE;
 
 #define IMPL_GETTER_AND_SETTER(_type)                                          \
   JSObject*                                                                    \
@@ -252,16 +253,26 @@ public:
 
   void
   NullResponseText()
   {
     mStateData.mResponseText.SetIsVoid(true);
     mStateData.mResponse = JSVAL_NULL;
   }
 
+  bool GetMozAnon() {
+    // TODO: bug 761227
+    return false;
+  }
+
+  bool GetMozSystem() {
+    // TODO: bug 761227
+    return false;
+  }
+
 private:
   enum ReleaseType { Default, XHRIsGoingAway, WorkerIsGoingAway };
 
   void
   ReleaseProxy(ReleaseType aType = Default);
 
   void
   MaybePin(ErrorResult& aRv);
--- a/editor/libeditor/base/nsEditor.h
+++ b/editor/libeditor/base/nsEditor.h
@@ -12,17 +12,16 @@
 #include "nsIEditor.h"
 #include "nsIPlaintextEditor.h"
 #include "nsIEditorIMESupport.h"
 #include "nsIPhonetic.h"
 
 #include "nsIAtom.h"
 #include "nsIDOMDocument.h"
 #include "nsISelection.h"
-#include "nsRange.h"
 #include "nsTypedSelection.h"
 #include "nsIDOMCharacterData.h"
 #include "nsIPrivateTextRange.h"
 #include "nsITransactionManager.h"
 #include "nsIComponentManager.h"
 #include "nsCOMArray.h"
 #include "nsIEditActionListener.h"
 #include "nsIEditorObserver.h"
--- a/editor/libeditor/html/nsHTMLAbsPosition.cpp
+++ b/editor/libeditor/html/nsHTMLAbsPosition.cpp
@@ -484,17 +484,16 @@ nsHTMLEditor::AbsolutelyPositionElement(
                                      positionStr);
   bool isPositioned = (positionStr.EqualsLiteral("absolute"));
 
   // nothing to do if the element is already in the state we want
   if (isPositioned == aEnabled)
     return NS_OK;
 
   nsAutoEditBatch batchIt(this);
-  nsresult res;
 
   if (aEnabled) {
     PRInt32 x, y;
     GetElementOrigin(aElement, x, y);
 
     mHTMLCSSUtils->SetCSSProperty(aElement,
                                   nsEditProperty::cssPosition,
                                   NS_LITERAL_STRING("absolute"),
@@ -507,21 +506,21 @@ nsHTMLEditor::AbsolutelyPositionElement(
     // we may need to create a br if the positioned element is alone in its
     // container
     nsCOMPtr<nsINode> element = do_QueryInterface(aElement);
     NS_ENSURE_STATE(element);
 
     nsINode* parentNode = element->GetNodeParent();
     if (parentNode->GetChildCount() == 1) {
       nsCOMPtr<nsIDOMNode> brNode;
-      res = CreateBR(parentNode->AsDOMNode(), 0, address_of(brNode));
+      nsresult res = CreateBR(parentNode->AsDOMNode(), 0, address_of(brNode));
+      NS_ENSURE_SUCCESS(res, res);
     }
   }
   else {
-    res = NS_OK;
     mHTMLCSSUtils->RemoveCSSProperty(aElement,
                                      nsEditProperty::cssPosition,
                                      EmptyString(), false);
     mHTMLCSSUtils->RemoveCSSProperty(aElement,
                                      nsEditProperty::cssTop,
                                      EmptyString(), false);
     mHTMLCSSUtils->RemoveCSSProperty(aElement,
                                      nsEditProperty::cssLeft,
@@ -538,22 +537,23 @@ nsHTMLEditor::AbsolutelyPositionElement(
                                        nsEditProperty::cssHeight,
                                        EmptyString(), false);
     }
 
     nsCOMPtr<dom::Element> element = do_QueryInterface(aElement);
     if (element && element->IsHTML(nsGkAtoms::div) && !HasStyleOrIdOrClass(element)) {
       nsHTMLEditRules* htmlRules = static_cast<nsHTMLEditRules*>(mRules.get());
       NS_ENSURE_TRUE(htmlRules, NS_ERROR_FAILURE);
-      res = htmlRules->MakeSureElemStartsOrEndsOnCR(aElement);
+      nsresult res = htmlRules->MakeSureElemStartsOrEndsOnCR(aElement);
       NS_ENSURE_SUCCESS(res, res);
       res = RemoveContainer(aElement);
+      NS_ENSURE_SUCCESS(res, res);
     }
   }
-  return res;
+  return NS_OK;
 }
 
 NS_IMETHODIMP
 nsHTMLEditor::SetSnapToGridEnabled(bool aEnabled)
 {
   mSnapToGridEnabled = aEnabled;
   return NS_OK;
 }
--- a/editor/libeditor/html/nsHTMLDataTransfer.cpp
+++ b/editor/libeditor/html/nsHTMLDataTransfer.cpp
@@ -997,28 +997,31 @@ NS_IMETHODIMP nsHTMLEditor::PrepareHTMLT
       }
       (*aTransferable)->AddDataFlavor(kHTMLMime);
       (*aTransferable)->AddDataFlavor(kFileMime);
 
       switch (Preferences::GetInt("clipboard.paste_image_type", 1))
       {
         case 0:  // prefer JPEG over PNG over GIF encoding
           (*aTransferable)->AddDataFlavor(kJPEGImageMime);
+          (*aTransferable)->AddDataFlavor(kJPGImageMime);
           (*aTransferable)->AddDataFlavor(kPNGImageMime);
           (*aTransferable)->AddDataFlavor(kGIFImageMime);
           break;
         case 1:  // prefer PNG over JPEG over GIF encoding (default)
         default:
           (*aTransferable)->AddDataFlavor(kPNGImageMime);
           (*aTransferable)->AddDataFlavor(kJPEGImageMime);
+          (*aTransferable)->AddDataFlavor(kJPGImageMime);
           (*aTransferable)->AddDataFlavor(kGIFImageMime);
           break;
         case 2:  // prefer GIF over JPEG over PNG encoding
           (*aTransferable)->AddDataFlavor(kGIFImageMime);
           (*aTransferable)->AddDataFlavor(kJPEGImageMime);
+          (*aTransferable)->AddDataFlavor(kJPGImageMime);
           (*aTransferable)->AddDataFlavor(kPNGImageMime);
           break;
       }
     }
     (*aTransferable)->AddDataFlavor(kUnicodeMime);
     (*aTransferable)->AddDataFlavor(kMozTextInternal);
   }
   
@@ -1230,16 +1233,17 @@ nsresult nsHTMLEditor::InsertObject(cons
       if (StringBeginsWith(contentType, NS_LITERAL_CSTRING("image/"))) {
         insertAsImage = true;
         type = contentType.get();
       }
     }
   }
 
   if (0 == nsCRT::strcmp(type, kJPEGImageMime) ||
+      0 == nsCRT::strcmp(type, kJPGImageMime) ||
       0 == nsCRT::strcmp(type, kPNGImageMime) ||
       0 == nsCRT::strcmp(type, kGIFImageMime) ||
       insertAsImage)
   {
     nsCOMPtr<nsIInputStream> imageStream;
     if (insertAsImage) {
       NS_ASSERTION(fileURI, "The file URI should be retrieved earlier");
       rv = NS_OpenURI(getter_AddRefs(imageStream), fileURI);
@@ -1299,16 +1303,17 @@ NS_IMETHODIMP nsHTMLEditor::InsertFromTr
 #ifdef DEBUG_clipboard
     printf("Got flavor [%s]\n", bestFlavor.get());
 #endif
 
     bool isSafe = IsSafeToInsertData(aSourceDoc);
 
     if (0 == nsCRT::strcmp(bestFlavor, kFileMime) ||
         0 == nsCRT::strcmp(bestFlavor, kJPEGImageMime) ||
+        0 == nsCRT::strcmp(bestFlavor, kJPGImageMime) ||
         0 == nsCRT::strcmp(bestFlavor, kPNGImageMime) ||
         0 == nsCRT::strcmp(bestFlavor, kGIFImageMime)) {
       rv = InsertObject(bestFlavor, genericDataObj, isSafe,
                         aSourceDoc, aDestinationNode, aDestOffset, aDoDeleteSelection);
     }
     else if (0 == nsCRT::strcmp(bestFlavor, kNativeHTMLMime))
     {
       // note cf_html uses utf8, hence use length = len, not len/2 as in flavors below
@@ -1398,16 +1403,17 @@ nsresult nsHTMLEditor::InsertFromDataTra
   types->GetLength(&length);
   for (PRUint32 t = 0; t < length; t++) {
     nsAutoString type;
     types->Item(t, type);
 
     if (!isText) {
       if (type.EqualsLiteral(kFileMime) ||
           type.EqualsLiteral(kJPEGImageMime) ||
+          type.EqualsLiteral(kJPGImageMime) ||
           type.EqualsLiteral(kPNGImageMime) ||
           type.EqualsLiteral(kGIFImageMime)) {
         nsCOMPtr<nsIVariant> variant;
         aDataTransfer->MozGetDataAt(type, aIndex, getter_AddRefs(variant));
         if (variant) {
           nsCOMPtr<nsISupports> object;
           variant->GetAsISupports(getter_AddRefs(object));
           rv = InsertObject(NS_ConvertUTF16toUTF8(type).get(), object, isSafe,
@@ -1619,18 +1625,18 @@ NS_IMETHODIMP nsHTMLEditor::PasteNoForma
 }
 
 
 // The following arrays contain the MIME types that we can paste. The arrays
 // are used by CanPaste() and CanPasteTransferable() below.
 
 static const char* textEditorFlavors[] = { kUnicodeMime };
 static const char* textHtmlEditorFlavors[] = { kUnicodeMime, kHTMLMime,
-                                               kJPEGImageMime, kPNGImageMime,
-                                               kGIFImageMime };
+                                               kJPEGImageMime, kJPGImageMime,
+                                               kPNGImageMime, kGIFImageMime };
 
 NS_IMETHODIMP nsHTMLEditor::CanPaste(PRInt32 aSelectionType, bool *aCanPaste)
 {
   NS_ENSURE_ARG_POINTER(aCanPaste);
   *aCanPaste = false;
 
   // can't paste if readonly
   if (!IsModifiable()) {
--- a/editor/libeditor/html/nsHTMLEditRules.cpp
+++ b/editor/libeditor/html/nsHTMLEditRules.cpp
@@ -1232,17 +1232,17 @@ nsHTMLEditRules::WillInsert(nsISelection
     NS_ENSURE_SUCCESS(res, res);
   }
 
   return NS_OK;
 }    
 
 nsresult
 nsHTMLEditRules::WillInsertText(nsEditor::OperationID aAction,
-                                nsISelection *aSelection, 
+                                nsTypedSelection* aSelection,
                                 bool            *aCancel,
                                 bool            *aHandled,
                                 const nsAString *inString,
                                 nsAString       *outString,
                                 PRInt32          aMaxLength)
 {  
   if (!aSelection || !aCancel || !aHandled) { return NS_ERROR_NULL_POINTER; }
 
@@ -1458,17 +1458,17 @@ nsHTMLEditRules::WillLoadHTML(nsISelecti
     mEditor->DeleteNode(mBogusNode);
     mBogusNode = nsnull;
   }
 
   return NS_OK;
 }
 
 nsresult
-nsHTMLEditRules::WillInsertBreak(nsISelection* aSelection,
+nsHTMLEditRules::WillInsertBreak(nsTypedSelection* aSelection,
                                  bool* aCancel, bool* aHandled)
 {
   if (!aSelection || !aCancel || !aHandled) {
     return NS_ERROR_NULL_POINTER;
   }
   // initialize out params
   *aCancel = false;
   *aHandled = false;
@@ -1774,17 +1774,17 @@ nsHTMLEditRules::SplitMailCites(nsISelec
     }
     *aHandled = true;
   }
   return NS_OK;
 }
 
 
 nsresult
-nsHTMLEditRules::WillDeleteSelection(nsISelection* aSelection,
+nsHTMLEditRules::WillDeleteSelection(nsTypedSelection* aSelection,
                                      nsIEditor::EDirection aAction,
                                      nsIEditor::EStripWrappers aStripWrappers,
                                      bool* aCancel,
                                      bool* aHandled)
 {
   MOZ_ASSERT(aStripWrappers == nsIEditor::eStrip ||
              aStripWrappers == nsIEditor::eNoStrip);
 
@@ -1975,34 +1975,33 @@ nsHTMLEditRules::WillDeleteSelection(nsI
         */
 
         bool moveOnly = true;
 
         res = nsEditor::GetNodeLocation(visNode, address_of(selNode), &selOffset);
         NS_ENSURE_SUCCESS(res, res);
 
         bool interLineIsRight;
-        nsCOMPtr<nsISelectionPrivate> selPriv(do_QueryInterface(aSelection));
-        res = selPriv->GetInterlinePosition(&interLineIsRight);
+        res = aSelection->GetInterlinePosition(&interLineIsRight);
         NS_ENSURE_SUCCESS(res, res);
 
         if (startNode == selNode &&
             startOffset -1 == selOffset &&
             !interLineIsRight)
         {
           moveOnly = false;
         }
         
         if (moveOnly)
         {
           // Go to the position after the <hr>, but to the end of the <hr> line
           // by setting the interline position to left.
           ++selOffset;
           res = aSelection->Collapse(selNode, selOffset);
-          selPriv->SetInterlinePosition(false);
+          aSelection->SetInterlinePosition(false);
           mDidExplicitlySetInterline = true;
           *aHandled = true;
 
           // There is one exception to the move only case.
           // If the <hr> is followed by a <br> we want to delete the <br>.
 
           PRInt16 otherWSType;
           nsCOMPtr<nsIDOMNode> otherNode;
@@ -2345,18 +2344,17 @@ nsHTMLEditRules::WillDeleteSelection(nsI
             res = aSelection->Collapse(selNode,selOffset);
             return res;
           }
         }
         
         // else blocks not same type, or not siblings.  Delete everything except
         // table elements.
         nsCOMPtr<nsIEnumerator> enumerator;
-        nsCOMPtr<nsISelectionPrivate> selPriv(do_QueryInterface(aSelection));
-        res = selPriv->GetEnumerator(getter_AddRefs(enumerator));
+        res = aSelection->GetEnumerator(getter_AddRefs(enumerator));
         NS_ENSURE_SUCCESS(res, res);
         NS_ENSURE_TRUE(enumerator, NS_ERROR_UNEXPECTED);
 
         join = true;
 
         for (enumerator->First(); NS_OK!=enumerator->IsDone(); enumerator->Next())
         {
           nsCOMPtr<nsISupports> currentItem;
--- a/editor/libeditor/html/nsHTMLEditRules.h
+++ b/editor/libeditor/html/nsHTMLEditRules.h
@@ -103,28 +103,29 @@ protected:
   {
     kBeforeBlock,
     kBlockEnd
   };
 
   // nsHTMLEditRules implementation methods
   nsresult WillInsert(nsISelection *aSelection, bool *aCancel);
   nsresult WillInsertText(  nsEditor::OperationID aAction,
-                            nsISelection *aSelection, 
+                            nsTypedSelection* aSelection,
                             bool            *aCancel,
                             bool            *aHandled,
                             const nsAString *inString,
                             nsAString       *outString,
                             PRInt32          aMaxLength);
   nsresult WillLoadHTML(nsISelection *aSelection, bool *aCancel);
-  nsresult WillInsertBreak(nsISelection *aSelection, bool *aCancel, bool *aHandled);
+  nsresult WillInsertBreak(nsTypedSelection* aSelection,
+                           bool* aCancel, bool* aHandled);
   nsresult StandardBreakImpl(nsIDOMNode *aNode, PRInt32 aOffset, nsISelection *aSelection);
   nsresult DidInsertBreak(nsISelection *aSelection, nsresult aResult);
   nsresult SplitMailCites(nsISelection *aSelection, bool aPlaintext, bool *aHandled);
-  nsresult WillDeleteSelection(nsISelection* aSelection,
+  nsresult WillDeleteSelection(nsTypedSelection* aSelection,
                                nsIEditor::EDirection aAction,
                                nsIEditor::EStripWrappers aStripWrappers,
                                bool* aCancel, bool* aHandled);
   nsresult DidDeleteSelection(nsISelection *aSelection, 
                               nsIEditor::EDirection aDir, 
                               nsresult aResult);
   nsresult InsertBRIfNeeded(nsISelection *aSelection);
   nsresult GetGoodSelPointForNode(nsIDOMNode *aNode, nsIEditor::EDirection aAction, 
--- a/editor/libeditor/html/nsHTMLEditor.h
+++ b/editor/libeditor/html/nsHTMLEditor.h
@@ -321,23 +321,16 @@ public:
   /* ------------ Utility Routines, not part of public API -------------- */
   NS_IMETHOD TypedText(const nsAString& aString, ETypingAction aAction);
   nsresult InsertNodeAtPoint( nsIDOMNode *aNode, 
                               nsCOMPtr<nsIDOMNode> *ioParent, 
                               PRInt32 *ioOffset, 
                               bool aNoEmptyNodes);
   virtual already_AddRefed<nsIDOMNode> FindUserSelectAllNode(nsIDOMNode* aNode);
 
-  /** returns the absolute position of the end points of aSelection
-    * in the document as a text stream.
-    */
-  nsresult GetTextSelectionOffsets(nsISelection *aSelection,
-                                   PRInt32 &aStartOffset, 
-                                   PRInt32 &aEndOffset);
-
   // Use this to assure that selection is set after attribute nodes when 
   //  trying to collapse selection at begining of a block node
   //  e.g., when setting at beginning of a table cell
   // This will stop at a table, however, since we don't want to
   //  "drill down" into nested tables.
   // aSelection is optional -- if null, we get current seletion
   nsresult CollapseSelectionToDeepestNonTableFirstChild(nsISelection *aSelection, nsIDOMNode *aNode);
 
--- a/editor/libeditor/text/nsPlaintextEditor.cpp
+++ b/editor/libeditor/text/nsPlaintextEditor.cpp
@@ -529,104 +529,16 @@ nsPlaintextEditor::InsertBR(nsCOMPtr<nsI
   res = GetNodeLocation(*outBRNode, address_of(selNode), &selOffset);
   NS_ENSURE_SUCCESS(res, res);
   nsCOMPtr<nsISelectionPrivate> selPriv(do_QueryInterface(selection));
   selPriv->SetInterlinePosition(true);
   return selection->Collapse(selNode, selOffset+1);
 }
 
 nsresult
-nsPlaintextEditor::GetTextSelectionOffsets(nsISelection *aSelection,
-                                           PRUint32 &aOutStartOffset, 
-                                           PRUint32 &aOutEndOffset)
-{
-  NS_ASSERTION(aSelection, "null selection");
-
-  nsresult rv;
-  nsCOMPtr<nsIDOMNode> startNode, endNode;
-  PRInt32 startNodeOffset, endNodeOffset;
-  aSelection->GetAnchorNode(getter_AddRefs(startNode));
-  aSelection->GetAnchorOffset(&startNodeOffset);
-  aSelection->GetFocusNode(getter_AddRefs(endNode));
-  aSelection->GetFocusOffset(&endNodeOffset);
-
-  dom::Element *rootElement = GetRoot();
-  nsCOMPtr<nsIDOMNode> rootNode = do_QueryInterface(rootElement);
-  NS_ENSURE_TRUE(rootNode, NS_ERROR_NULL_POINTER);
-
-  PRInt32 startOffset = -1;
-  PRInt32 endOffset = -1;
-
-  nsCOMPtr<nsIContentIterator> iter =
-    do_CreateInstance("@mozilla.org/content/post-content-iterator;1", &rv);
-  NS_ENSURE_SUCCESS(rv, rv);
-    
-#ifdef NS_DEBUG
-  PRInt32 nodeCount = 0; // only needed for the assertions below
-#endif
-  PRUint32 totalLength = 0;
-  iter->Init(rootElement);
-  for (; !iter->IsDone() && (startOffset == -1 || endOffset == -1); iter->Next()) {
-    nsCOMPtr<nsIDOMNode> currentNode = do_QueryInterface(iter->GetCurrentNode());
-    nsCOMPtr<nsIDOMCharacterData> textNode = do_QueryInterface(currentNode);
-    if (textNode) {
-      // Note that sometimes we have an empty #text-node as start/endNode,
-      // which we regard as not editable because the frame width == 0,
-      // see nsEditor::IsEditable().
-      bool editable = IsEditable(currentNode);
-      if (currentNode == startNode) {
-        startOffset = totalLength + (editable ? startNodeOffset : 0);
-      }
-      if (currentNode == endNode) {
-        endOffset = totalLength + (editable ? endNodeOffset : 0);
-      }
-      if (editable) {
-        PRUint32 length;
-        textNode->GetLength(&length);
-        totalLength += length;
-      }
-    }
-#ifdef NS_DEBUG
-    // The post content iterator might return the parent node (which is the
-    // editor's root node) as the last item.  Don't count the root node itself
-    // as one of its children!
-    if (!SameCOMIdentity(currentNode, rootNode)) {
-      ++nodeCount;
-    }
-#endif
-  }
-
-  if (endOffset == -1) {
-    NS_ASSERTION(endNode == rootNode, "failed to find the end node");
-    NS_ASSERTION(IsPasswordEditor() ||
-                 (endNodeOffset == nodeCount-1 || endNodeOffset == 0),
-                 "invalid end node offset");
-    endOffset = endNodeOffset == 0 ? 0 : totalLength;
-  }
-  if (startOffset == -1) {
-    NS_ASSERTION(startNode == rootNode, "failed to find the start node");
-    NS_ASSERTION(startNodeOffset == nodeCount-1 || startNodeOffset == 0,
-                 "invalid start node offset");
-    startOffset = startNodeOffset == 0 ? 0 : totalLength;
-  }
-
-  // Make sure aOutStartOffset <= aOutEndOffset.
-  if (startOffset <= endOffset) {
-    aOutStartOffset = startOffset;
-    aOutEndOffset = endOffset;
-  }
-  else {
-    aOutStartOffset = endOffset;
-    aOutEndOffset = startOffset;
-  }
-
-  return NS_OK;
-}
-
-nsresult
 nsPlaintextEditor::ExtendSelectionForDelete(nsISelection *aSelection,
                                             nsIEditor::EDirection *aAction)
 {
   nsresult result = NS_OK;
 
   bool bCollapsed = aSelection->Collapsed();
 
   if (*aAction == eNextWord || *aAction == ePreviousWord
--- a/editor/libeditor/text/nsPlaintextEditor.h
+++ b/editor/libeditor/text/nsPlaintextEditor.h
@@ -116,24 +116,16 @@ public:
   virtual nsresult UpdateIMEComposition(const nsAString &aCompositionString,
                                         nsIPrivateTextRangeList *aTextRange);
 
   virtual already_AddRefed<nsIContent> GetInputEventTargetContent();
 
   /* ------------ Utility Routines, not part of public API -------------- */
   NS_IMETHOD TypedText(const nsAString& aString, ETypingAction aAction);
 
-  /** Returns the absolute position of the end points of aSelection
-   * in the document as a text stream.
-   * Invariant: aStartOffset <= aEndOffset.
-   */
-  nsresult GetTextSelectionOffsets(nsISelection *aSelection,
-                                   PRUint32 &aStartOffset, 
-                                   PRUint32 &aEndOffset);
-
   nsresult InsertTextAt(const nsAString &aStringToInsert,
                         nsIDOMNode *aDestinationNode,
                         PRInt32 aDestOffset,
                         bool aDoDeleteSelection);
 
   virtual nsresult InsertFromDataTransfer(nsIDOMDataTransfer *aDataTransfer,
                                           PRInt32 aIndex,
                                           nsIDOMDocument *aSourceDoc,
--- a/editor/libeditor/text/nsTextEditRules.cpp
+++ b/editor/libeditor/text/nsTextEditRules.cpp
@@ -24,16 +24,17 @@
 #include "nsIContentIterator.h"
 #include "nsEditorUtils.h"
 #include "EditTxn.h"
 #include "nsEditProperty.h"
 #include "nsUnicharUtils.h"
 #include "DeleteTextTxn.h"
 #include "nsNodeIterator.h"
 #include "nsIDOMNodeFilter.h"
+#include "nsContentUtils.h"
 
 // for IBMBIDI
 #include "nsFrameSelection.h"
 
 #include "mozilla/Preferences.h"
 #include "mozilla/LookAndFeel.h"
 #include "mozilla/dom/Element.h"
 
@@ -328,17 +329,17 @@ nsTextEditRules::WillInsert(nsISelection
 
 nsresult
 nsTextEditRules::DidInsert(nsISelection *aSelection, nsresult aResult)
 {
   return NS_OK;
 }
 
 nsresult
-nsTextEditRules::WillInsertBreak(nsISelection *aSelection,
+nsTextEditRules::WillInsertBreak(nsTypedSelection* aSelection,
                                  bool *aCancel,
                                  bool *aHandled,
                                  PRInt32 aMaxLength)
 {
   if (!aSelection || !aCancel || !aHandled) { return NS_ERROR_NULL_POINTER; }
   CANCEL_OPERATION_IF_READONLY_OR_DISABLED
   *aHandled = false;
   if (IsSingleLineEditor()) {
@@ -535,17 +536,17 @@ nsTextEditRules::HandleNewLines(nsString
     // even if we're pasting newlines, don't paste leading/trailing ones
     aString.Trim(CRLF, true, true);
     break;
   }
 }
 
 nsresult
 nsTextEditRules::WillInsertText(nsEditor::OperationID aAction,
-                                nsISelection *aSelection, 
+                                nsTypedSelection* aSelection,
                                 bool            *aCancel,
                                 bool            *aHandled,
                                 const nsAString *inString,
                                 nsAString *outString,
                                 PRInt32          aMaxLength)
 {  
   if (!aSelection || !aCancel || !aHandled) { return NS_ERROR_NULL_POINTER; }
 
@@ -573,25 +574,23 @@ nsTextEditRules::WillInsertText(nsEditor
   // If we're exceeding the maxlength when composing IME, we need to clean up
   // the composing text, so we shouldn't return early.
   if (truncated && outString->IsEmpty() &&
       aAction != nsEditor::kOpInsertIMEText) {
     *aCancel = true;
     return NS_OK;
   }
   
-  PRUint32 start = 0;
-  PRUint32 end = 0;  
+  PRInt32 start = 0;
+  PRInt32 end = 0;
 
   // handle password field docs
-  if (IsPasswordEditor())
-  {
-    res = mEditor->GetTextSelectionOffsets(aSelection, start, end);
-    NS_ASSERTION((NS_SUCCEEDED(res)), "getTextSelectionOffsets failed!");
-    NS_ENSURE_SUCCESS(res, res);
+  if (IsPasswordEditor()) {
+    nsContentUtils::GetSelectionInTextControl(aSelection, mEditor->GetRoot(),
+                                              start, end);
   }
 
   // if the selection isn't collapsed, delete it.
   bool bCollapsed;
   res = aSelection->GetIsCollapsed(&bCollapsed);
   NS_ENSURE_SUCCESS(res, res);
   if (!bCollapsed)
   {
@@ -692,18 +691,17 @@ nsTextEditRules::WillInsertText(nsEditor
     NS_ENSURE_SUCCESS(res, res);
 
     if (curNode) 
     {
       // Make the caret attach to the inserted text, unless this text ends with a LF, 
       // in which case make the caret attach to the next line.
       bool endsWithLF =
         !outString->IsEmpty() && outString->Last() == nsCRT::LF;
-      nsCOMPtr<nsISelectionPrivate>selPrivate(do_QueryInterface(aSelection));
-      selPrivate->SetInterlinePosition(endsWithLF);
+      aSelection->SetInterlinePosition(endsWithLF);
 
       aSelection->Collapse(curNode, curOffset);
     }
   }
   ASSERT_PASSWORD_LENGTHS_EQUAL()
   return res;
 }
 
@@ -750,17 +748,17 @@ nsTextEditRules::WillRemoveTextProperty(
 
 nsresult
 nsTextEditRules::DidRemoveTextProperty(nsISelection *aSelection, nsresult aResult)
 {
   return NS_OK;
 }
 
 nsresult
-nsTextEditRules::WillDeleteSelection(nsISelection *aSelection, 
+nsTextEditRules::WillDeleteSelection(nsTypedSelection* aSelection,
                                      nsIEditor::EDirection aCollapsedAction, 
                                      bool *aCancel,
                                      bool *aHandled)
 {
   if (!aSelection || !aCancel || !aHandled) { return NS_ERROR_NULL_POINTER; }
   CANCEL_OPERATION_IF_READONLY_OR_DISABLED
 
   // initialize out param
@@ -776,19 +774,19 @@ nsTextEditRules::WillDeleteSelection(nsI
   nsresult res = NS_OK;
 
   if (IsPasswordEditor())
   {
     res = mEditor->ExtendSelectionForDelete(aSelection, &aCollapsedAction);
     NS_ENSURE_SUCCESS(res, res);
 
     // manage the password buffer
-    PRUint32 start, end;
-    mEditor->GetTextSelectionOffsets(aSelection, start, end);
-    NS_ENSURE_SUCCESS(res, res);
+    PRInt32 start, end;
+    nsContentUtils::GetSelectionInTextControl(aSelection, mEditor->GetRoot(),
+                                              start, end);
 
     if (LookAndFeel::GetEchoPassword()) {
       HideLastPWInput();
       mLastStart = start;
       mLastLength = 0;
       if (mTimer)
       {
         mTimer->Cancel();
@@ -1135,17 +1133,17 @@ nsTextEditRules::CreateBogusNodeIfNeeded
 
   // Set selection.
   aSelection->CollapseNative(body, 0);
   return NS_OK;
 }
 
 
 nsresult
-nsTextEditRules::TruncateInsertionIfNeeded(nsISelection *aSelection, 
+nsTextEditRules::TruncateInsertionIfNeeded(nsTypedSelection* aSelection,
                                            const nsAString  *aInString,
                                            nsAString  *aOutString,
                                            PRInt32          aMaxLength,
                                            bool *aTruncated)
 {
   if (!aSelection || !aInString || !aOutString) {return NS_ERROR_NULL_POINTER;}
   
   nsresult res = NS_OK;
@@ -1167,19 +1165,19 @@ nsTextEditRules::TruncateInsertionIfNeed
     //   which will be replaced by new one.
     // If (resultingDocLength) is at or over max, cancel the insert
     // If (resultingDocLength) + (length of input) > max, 
     //    set aOutString to subset of inString so length = max
     PRInt32 docLength;
     res = mEditor->GetTextLength(&docLength);
     if (NS_FAILED(res)) { return res; }
 
-    PRUint32 start, end;
-    res = mEditor->GetTextSelectionOffsets(aSelection, start, end);
-    if (NS_FAILED(res)) { return res; }
+    PRInt32 start, end;
+    nsContentUtils::GetSelectionInTextControl(aSelection, mEditor->GetRoot(),
+                                              start, end);
 
     PRInt32 oldCompStrLength = mEditor->GetIMEBufferLength();
 
     const PRInt32 selectionLength = end - start;
     const PRInt32 resultingDocLength = docLength - selectionLength - oldCompStrLength;
     if (resultingDocLength >= aMaxLength)
     {
       aOutString->Truncate();
@@ -1204,17 +1202,17 @@ nsTextEditRules::TruncateInsertionIfNeed
 
 void
 nsTextEditRules::ResetIMETextPWBuf()
 {
   mPasswordIMEText.Truncate();
 }
 
 void
-nsTextEditRules::RemoveIMETextFromPWBuf(PRUint32 &aStart, nsAString *aIMEString)
+nsTextEditRules::RemoveIMETextFromPWBuf(PRInt32 &aStart, nsAString *aIMEString)
 {
   MOZ_ASSERT(aIMEString);
 
   // initialize PasswordIME
   if (mPasswordIMEText.IsEmpty()) {
     mPasswordIMEIndex = aStart;
   }
   else {
@@ -1237,22 +1235,21 @@ nsresult nsTextEditRules::HideLastPWInpu
   if (!mLastLength) {
     // Special case, we're trying to replace a range that no longer exists
     return NS_OK;
   }
 
   nsAutoString hiddenText;
   FillBufWithPWChars(&hiddenText, mLastLength);
 
-  nsCOMPtr<nsISelection> selection;
-  PRUint32 start, end;
-  nsresult res = mEditor->GetSelection(getter_AddRefs(selection));
-  NS_ENSURE_SUCCESS(res, res);
-  res = mEditor->GetTextSelectionOffsets(selection, start, end);
-  NS_ENSURE_SUCCESS(res, res);
+  nsRefPtr<nsTypedSelection> selection = mEditor->GetTypedSelection();
+  NS_ENSURE_TRUE(selection, NS_ERROR_NULL_POINTER);
+  PRInt32 start, end;
+  nsContentUtils::GetSelectionInTextControl(selection, mEditor->GetRoot(),
+                                            start, end);
 
   nsCOMPtr<nsIDOMNode> selNode = GetTextNode(selection, mEditor);
   NS_ENSURE_TRUE(selNode, NS_OK);
   
   nsCOMPtr<nsIDOMCharacterData> nodeAsText(do_QueryInterface(selNode));
   NS_ENSURE_TRUE(nodeAsText, NS_OK);
   
   nodeAsText->ReplaceData(mLastStart, mLastLength, hiddenText);
--- a/editor/libeditor/text/nsTextEditRules.h
+++ b/editor/libeditor/text/nsTextEditRules.h
@@ -86,33 +86,33 @@ public:
    *        contain.
    */
   static void FillBufWithPWChars(nsAString *aOutString, PRInt32 aLength);
 
 protected:
 
   // nsTextEditRules implementation methods
   nsresult WillInsertText(  nsEditor::OperationID aAction,
-                            nsISelection *aSelection, 
+                            nsTypedSelection* aSelection,
                             bool            *aCancel,
                             bool            *aHandled,
                             const nsAString *inString,
                             nsAString       *outString,
                             PRInt32          aMaxLength);
   nsresult DidInsertText(nsISelection *aSelection, nsresult aResult);
   nsresult GetTopEnclosingPre(nsIDOMNode *aNode, nsIDOMNode** aOutPreNode);
 
-  nsresult WillInsertBreak(nsISelection *aSelection, bool *aCancel,
+  nsresult WillInsertBreak(nsTypedSelection* aSelection, bool* aCancel,
                            bool *aHandled, PRInt32 aMaxLength);
   nsresult DidInsertBreak(nsISelection *aSelection, nsresult aResult);
 
   nsresult WillInsert(nsISelection *aSelection, bool *aCancel);
   nsresult DidInsert(nsISelection *aSelection, nsresult aResult);
 
-  nsresult WillDeleteSelection(nsISelection *aSelection, 
+  nsresult WillDeleteSelection(nsTypedSelection* aSelection,
                                nsIEditor::EDirection aCollapsedAction, 
                                bool *aCancel,
                                bool *aHandled);
   nsresult DidDeleteSelection(nsISelection *aSelection, 
                               nsIEditor::EDirection aCollapsedAction, 
                               nsresult aResult);
 
   nsresult WillSetTextProperty(nsISelection *aSelection, bool *aCancel, bool *aHandled);
@@ -151,24 +151,24 @@ protected:
   /** creates a trailing break in the text doc if there is not one already */
   nsresult CreateTrailingBRIfNeeded();
   
  /** creates a bogus text node if the document has no editable content */
   nsresult CreateBogusNodeIfNeeded(nsISelection *aSelection);
 
   /** returns a truncated insertion string if insertion would place us
       over aMaxLength */
-  nsresult TruncateInsertionIfNeeded(nsISelection             *aSelection, 
+  nsresult TruncateInsertionIfNeeded(nsTypedSelection*         aSelection,
                                      const nsAString          *aInString,
                                      nsAString                *aOutString,
                                      PRInt32                   aMaxLength,
                                      bool                     *aTruncated);
 
   /** Remove IME composition text from password buffer */
-  void RemoveIMETextFromPWBuf(PRUint32 &aStart, nsAString *aIMEString);
+  void RemoveIMETextFromPWBuf(PRInt32 &aStart, nsAString *aIMEString);
 
   nsresult CreateMozBR(nsIDOMNode* inParent, PRInt32 inOffset,
                        nsIDOMNode** outBRNode = nsnull);
 
   nsresult CheckBidiLevelForDeletion(nsISelection         *aSelection,
                                      nsIDOMNode           *aSelNode, 
                                      PRInt32               aSelOffset, 
                                      nsIEditor::EDirection aAction,
--- a/editor/libeditor/text/tests/Makefile.in
+++ b/editor/libeditor/text/tests/Makefile.in
@@ -29,16 +29,17 @@ include $(topsrcdir)/config/rules.mk
 		test_bug625452.html \
 		test_bug629172.html \
 		test_bug638596.html \
 		test_bug641466.html \
 		test_bug645914.html \
 		test_bug681229.html \
 		test_bug692520.html \
 		test_bug740784.html \
+		test_bug757771.html \
 		test_dom_input_event_on_texteditor.html \
 		$(NULL)
 
 # disables the key handling test on gtk2 because gtk2 overrides some key events
 # on our editor, and the combinations depend on the system.
 ifneq ($(MOZ_WIDGET_TOOLKIT),gtk2)
 _TEST_FILES += \
 		test_texteditor_keyevent_handling.html \
new file mode 100644
--- /dev/null
+++ b/editor/libeditor/text/tests/test_bug757771.html
@@ -0,0 +1,31 @@
+<!DOCTYPE html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=757771
+-->
+<title>Test for Bug 757771</title>
+<script src="/tests/SimpleTest/SimpleTest.js"></script>
+<script src="/tests/SimpleTest/EventUtils.js"></script>
+<link rel="stylesheet" href="/tests/SimpleTest/test.css">
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=757771">Mozilla Bug 757771</a>
+<input value=foo maxlength=4>
+<input type=password value=password>
+<script>
+/** Test for Bug 757771 **/
+
+SimpleTest.waitForExplicitFinish();
+SimpleTest.waitForFocus(function() {
+  var textInput = document.querySelector("input");
+  textInput.focus();
+  textInput.select();
+  sendString("abcde");
+
+  var passwordInput = document.querySelector("input + input");
+  passwordInput.focus();
+  passwordInput.select();
+  sendString("hunter2");
+
+  ok(true, "No real tests, just crashes/asserts");
+
+  SimpleTest.finish();
+});
+</script>
--- a/gfx/ots/README.mozilla
+++ b/gfx/ots/README.mozilla
@@ -1,11 +1,11 @@
 This is the Sanitiser for OpenType project, from http://code.google.com/p/ots/.
 
-Current revision: r91
+Current revision: r92
 
 Applied local patches:
     ots-fix-vc10.patch - workaround for VS10 STL wrappers (bug 602558)
 
     ots-fix-sparc64.patch - fix alignment error on sparc64 (bug 643137)
 
     ots-graphite.patch - preserve Graphite layout tables (bug 631479)
 
--- a/gfx/ots/src/ots.cc
+++ b/gfx/ots/src/ots.cc
@@ -180,17 +180,19 @@ bool IsValidVersionTag(uint32_t tag) {
   return tag == Tag("\x00\x01\x00\x00") ||
          // OpenType fonts with CFF data have 'OTTO' tag.
          tag == Tag("OTTO") ||
          // Older Mac fonts might have 'true' or 'typ1' tag.
          tag == Tag("true") ||
          tag == Tag("typ1");
 }
 
-bool ProcessGeneric(ots::OpenTypeFile *header, ots::OTSStream *output,
+bool ProcessGeneric(ots::OpenTypeFile *header,
+                    uint32_t signature,
+                    ots::OTSStream *output,
                     const uint8_t *data, size_t length,
                     const std::vector<OpenTypeTable>& tables,
                     ots::Buffer& file);
 
 bool ProcessTTF(ots::OpenTypeFile *header,
                 ots::OTSStream *output, const uint8_t *data, size_t length) {
   ots::Buffer file(data, length);
 
@@ -258,17 +260,18 @@ bool ProcessTTF(ots::OpenTypeFile *heade
         !file.ReadU32(&table.length)) {
       return OTS_FAILURE_MSG_HDR("error reading table directory");
     }
 
     table.uncompressed_length = table.length;
     tables.push_back(table);
   }
 
-  return ProcessGeneric(header, output, data, length, tables, file);
+  return ProcessGeneric(header, header->version, output, data, length,
+                        tables, file);
 }
 
 bool ProcessWOFF(ots::OpenTypeFile *header,
                  ots::OTSStream *output, const uint8_t *data, size_t length) {
   ots::Buffer file(data, length);
 
   // we disallow all files > 1GB in size for sanity.
   if (length > 1024 * 1024 * 1024) {
@@ -416,20 +419,21 @@ bool ProcessWOFF(ots::OpenTypeFile *head
     if (block_end > std::numeric_limits<uint32_t>::max()) {
       return OTS_FAILURE_MSG_HDR("invalid private block size");
     }
   }
   if (block_end != Round4(length)) {
     return OTS_FAILURE_MSG_HDR("file length mismatch (trailing junk?)");
   }
 
-  return ProcessGeneric(header, output, data, length, tables, file);
+  return ProcessGeneric(header, woff_tag, output, data, length, tables, file);
 }
 
-bool ProcessGeneric(ots::OpenTypeFile *header, ots::OTSStream *output,
+bool ProcessGeneric(ots::OpenTypeFile *header, uint32_t signature,
+                    ots::OTSStream *output,
                     const uint8_t *data, size_t length,
                     const std::vector<OpenTypeTable>& tables,
                     ots::Buffer& file) {
   const size_t data_offset = file.offset();
 
   uint32_t uncompressed_sum = 0;
 
   for (unsigned i = 0; i < header->num_tables; ++i) {
@@ -480,20 +484,21 @@ bool ProcessGeneric(ots::OpenTypeFile *h
       if (uncompressed_sum + tables[i].uncompressed_length < uncompressed_sum) {
         return OTS_FAILURE_MSG_TAG("overflow of uncompressed sum", &tables[i].tag);
       }
 
       uncompressed_sum += tables[i].uncompressed_length;
     }
     // since we required that the file be < 1GB in length, and that the table
     // length is < 1GB, the following addtion doesn't overflow
-    const uint32_t end_byte = tables[i].offset + tables[i].length;
-    // Some fonts which are automatically generated by a font generator
-    // called TTX seems not to add 0-padding to the final table. It might be
-    // ok to accept these fonts so we round up the length of the font file.
+    uint32_t end_byte = tables[i].offset + tables[i].length;
+    // Tables in the WOFF file must be aligned 4-byte boundary.
+    if (signature == Tag("wOFF")) {
+        end_byte = Round4(end_byte);
+    }
     if (!end_byte || end_byte > length) {
       return OTS_FAILURE_MSG_TAG("table overruns end of file", &tables[i].tag);
     }
   }
 
   // All decompressed tables uncompressed must be <= 30MB.
   if (uncompressed_sum > 30 * 1024 * 1024) {
     return OTS_FAILURE_MSG_HDR("uncompressed sum exceeds 30MB");
--- a/hal/gonk/GonkSensor.cpp
+++ b/hal/gonk/GonkSensor.cpp
@@ -202,17 +202,17 @@ nsCOMPtr<nsIRunnable> PollSensor::mRunna
 class SwitchSensor : public RefCounted<SwitchSensor> {
   public:
     SwitchSensor(bool aActivate, sensor_t aSensor, pthread_t aThreadId) :
       mActivate(aActivate), mSensor(aSensor), mThreadId(aThreadId) { }
 
     void Switch() {
       int index = HardwareSensorToHalSensor(mSensor.type);
 
-      MOZ_ASSERT(sSensorStatus[index].count == 0 || mActivate);
+      MOZ_ASSERT(sSensorStatus[index].count || mActivate);
 
       SensorDevice& device = SensorDevice::getInstance();
       
       device.activate((void*)mThreadId, mSensor.handle, mActivate);
       device.setDelay((void*)mThreadId, mSensor.handle, DEFAULT_DEVICE_POLL_RATE);
 
       if (mActivate) {
         if (++sActivatedSensors == 1) {
--- a/ipc/testshell/XPCShellEnvironment.cpp
+++ b/ipc/testshell/XPCShellEnvironment.cpp
@@ -875,30 +875,16 @@ FullTrustSecMan::GetCxSubjectPrincipal(J
 NS_IMETHODIMP_(nsIPrincipal *)
 FullTrustSecMan::GetCxSubjectPrincipalAndFrame(JSContext *cx,
                                                JSStackFrame **fp)
 {
     *fp = nsnull;
     return mSystemPrincipal;
 }
 
-NS_IMETHODIMP
-FullTrustSecMan::PushContextPrincipal(JSContext *cx,
-                                      JSStackFrame *fp,
-                                      nsIPrincipal *principal)
-{
-    return NS_OK;
-}
-
-NS_IMETHODIMP
-FullTrustSecMan::PopContextPrincipal(JSContext *cx)
-{
-    return NS_OK;
-}
-
 NS_IMETHODIMP_(nsrefcnt)
 XPCShellDirProvider::AddRef()
 {
     return 2;
 }
 
 NS_IMETHODIMP_(nsrefcnt)
 XPCShellDirProvider::Release()
--- a/js/src/frontend/BytecodeCompiler.cpp
+++ b/js/src/frontend/BytecodeCompiler.cpp
@@ -94,17 +94,17 @@ frontend::CompileScript(JSContext *cx, J
     JS_ASSERT_IF(callerFrame, compileAndGo);
     JS_ASSERT_IF(staticLevel != 0, callerFrame);
 
     Parser parser(cx, principals, originPrincipals, chars, length, filename, lineno, version,
                   callerFrame, /* foldConstants = */ true, compileAndGo);
     if (!parser.init())
         return NULL;
 
-    SharedContext sc(cx, scopeChain, /* fun = */ NULL, /* funbox = */ NULL);
+    SharedContext sc(cx, scopeChain, /* fun = */ NULL, /* funbox = */ NULL, staticLevel);
 
     TreeContext tc(&parser, &sc);
     if (!tc.init())
         return NULL;
 
     BytecodeEmitter bce(&parser, &sc, lineno, noScriptRval, needScriptGlobal);
     if (!bce.init())
         return NULL;
@@ -114,18 +114,16 @@ frontend::CompileScript(JSContext *cx, J
                           ? &scopeChain->global()
                           : NULL;
 
     JS_ASSERT_IF(globalObj, globalObj->isNative());
     JS_ASSERT_IF(globalObj, JSCLASS_HAS_GLOBAL_FLAG_AND_SLOTS(globalObj->getClass()));
 
     GlobalScope globalScope(cx, globalObj);
     bce.globalScope = &globalScope;
-    if (!SetStaticLevel(&sc, staticLevel))
-        return NULL;
 
     /* If this is a direct call to eval, inherit the caller's strictness.  */
     if (callerFrame && callerFrame->isScriptFrame() && callerFrame->script()->strictModeCode)
         sc.setInStrictMode();
 
 #ifdef DEBUG
     bool savedCallerFun;
     savedCallerFun = false;
@@ -259,17 +257,18 @@ frontend::CompileFunctionBody(JSContext 
                               const char *filename, unsigned lineno, JSVersion version)
 {
     Parser parser(cx, principals, originPrincipals, chars, length, filename, lineno, version,
                   /* cfp = */ NULL, /* foldConstants = */ true, /* compileAndGo = */ false);
     if (!parser.init())
         return false;
 
     JS_ASSERT(fun);
-    SharedContext funsc(cx, /* scopeChain = */ NULL, fun, /* funbox = */ NULL);
+    SharedContext funsc(cx, /* scopeChain = */ NULL, fun, /* funbox = */ NULL,
+                        /* staticLevel = */ 0);
 
     TreeContext funtc(&parser, &funsc);
     if (!funtc.init())
         return NULL;
 
     BytecodeEmitter funbce(&parser, &funsc, lineno,
                            /* noScriptRval = */ false, /* needsScriptGlobal = */ false);
     if (!funbce.init())
--- a/js/src/frontend/BytecodeEmitter.cpp
+++ b/js/src/frontend/BytecodeEmitter.cpp
@@ -1071,17 +1071,20 @@ EmitEnterBlock(JSContext *cx, BytecodeEm
         /* Beware the empty destructuring dummy. */
         if (!dn) {
             blockObj->setAliased(i, bce->sc->bindingsAccessedDynamically());
             continue;
         }
 
         JS_ASSERT(dn->isDefn());
         JS_ASSERT(unsigned(dn->frameSlot() + depthPlusFixed) < JS_BIT(16));
-        dn->pn_cookie.set(dn->pn_cookie.level(), uint16_t(dn->frameSlot() + depthPlusFixed));
+        if (!dn->pn_cookie.set(cx, dn->pn_cookie.level(),
+                               uint16_t(dn->frameSlot() + depthPlusFixed)))
+            return false;
+
 #ifdef DEBUG
         for (ParseNode *pnu = dn->dn_uses; pnu; pnu = pnu->pn_link) {
             JS_ASSERT(pnu->pn_lexdef == dn);
             JS_ASSERT(!(pnu->pn_dflags & PND_BOUND));
             JS_ASSERT(pnu->pn_cookie.isFree());
         }
 #endif
 
@@ -1152,64 +1155,64 @@ TryConvertToGname(BytecodeEmitter *bce, 
     return false;
 }
 
 /*
  * BindNameToSlot attempts to optimize name gets and sets to stack slot loads
  * and stores, given the compile-time information in bce and a PNK_NAME node pn.
  * It returns false on error, true on success.
  *
- * The caller can inspect pn->pn_cookie for FREE_UPVAR_COOKIE to tell whether
- * optimization occurred, in which case BindNameToSlot also updated pn->pn_op.
- * If pn->pn_cookie is still FREE_UPVAR_COOKIE on return, pn->pn_op still may
- * have been optimized, e.g., from JSOP_NAME to JSOP_CALLEE.  Whether or not
+ * The caller can test pn->pn_cookie.isFree() to tell whether optimization
+ * occurred, in which case BindNameToSlot also updated pn->pn_op.  If
+ * pn->pn_cookie.isFree() is still true on return, pn->pn_op still may have
+ * been optimized, e.g., from JSOP_NAME to JSOP_CALLEE.  Whether or not
  * pn->pn_op was modified, if this function finds an argument or local variable
  * name, PND_CONST will be set in pn_dflags for read-only properties after a
  * successful return.
  *
  * NB: if you add more opcodes specialized from JSOP_NAME, etc., don't forget
  * to update the special cases in EmitFor (for-in) and EmitAssignment (= and
  * op=, e.g. +=).
  */
-static JSBool
+static bool
 BindNameToSlot(JSContext *cx, BytecodeEmitter *bce, ParseNode *pn)
 {
     Definition *dn;
     JSOp op;
     Definition::Kind dn_kind;
 
     JS_ASSERT(pn->isKind(PNK_NAME));
 
     /* Idempotency tests come first, since we may be called more than once. */
     if (pn->pn_dflags & PND_BOUND)
-        return JS_TRUE;
+        return true;
 
     /* No cookie initialized for callee; it is pre-bound by definition. */
     JS_ASSERT(!pn->isOp(JSOP_CALLEE));
 
     /*
      * The parser linked all uses (including forward references) to their
      * definitions, unless a with statement or direct eval intervened.
      */
     if (pn->isUsed()) {
         JS_ASSERT(pn->pn_cookie.isFree());
         dn = pn->pn_lexdef;
         JS_ASSERT(dn->isDefn());
         if (pn->isDeoptimized())
-            return JS_TRUE;
+            return true;
         pn->pn_dflags |= (dn->pn_dflags & PND_CONST);
     } else {
         if (!pn->isDefn())
-            return JS_TRUE;
+            return true;
         dn = (Definition *) pn;
     }
 
     op = pn->getOp();
     if (op == JSOP_NOP)
-        return JS_TRUE;
+        return true;
 
     JS_ASSERT(JOF_OPTYPE(op) == JOF_ATOM);
     RootedAtom atom(cx, pn->pn_atom);
     UpvarCookie cookie = dn->pn_cookie;
     dn_kind = dn->kind();
 
     /*
      * Turn attempts to mutate const-declared bindings into get ops (for
@@ -1226,89 +1229,89 @@ BindNameToSlot(JSContext *cx, BytecodeEm
         break;
       case JSOP_DELNAME:
         if (dn_kind != Definition::UNKNOWN) {
             if (bce->parser->callerFrame && dn->isTopLevel())
                 JS_ASSERT(bce->parser->compileAndGo);
             else
                 pn->setOp(JSOP_FALSE);
             pn->pn_dflags |= PND_BOUND;
-            return JS_TRUE;
+            return true;
         }
         break;
       default:
         if (pn->isConst()) {
             if (bce->sc->needStrictChecks()) {
                 JSAutoByteString name;
                 if (!js_AtomToPrintableString(cx, atom, &name) ||
                     !ReportStrictModeError(cx, bce->tokenStream(), pn, JSMSG_READ_ONLY, name.ptr()))
                 {
-                    return JS_FALSE;
+                    return false;
                 }
             }
             pn->setOp(op = JSOP_NAME);
         }
     }
 
     if (cookie.isFree()) {
         StackFrame *caller = bce->parser->callerFrame;
         if (caller) {
             JS_ASSERT(bce->parser->compileAndGo);
 
             /*
              * Don't generate upvars on the left side of a for loop. See
              * bug 470758.
              */
             if (bce->inForInit)
-                return JS_TRUE;
+                return true;
 
             JS_ASSERT(caller->isScriptFrame());
 
             /*
              * If this is an eval in the global scope, then unbound variables
              * must be globals, so try to use GNAME ops.
              */
             if (caller->isGlobalFrame() && TryConvertToGname(bce, pn, &op)) {
                 pn->setOp(op);
                 pn->pn_dflags |= PND_BOUND;
-                return JS_TRUE;
+                return true;
             }
 
             /*
              * Out of tricks, so we must rely on PICs to optimize named
              * accesses from direct eval called from function code.
              */
-            return JS_TRUE;
+            return true;
         }
 
         /* Optimize accesses to undeclared globals. */
         if (!TryConvertToGname(bce, pn, &op))
-            return JS_TRUE;
+            return true;
 
         pn->setOp(op);
         pn->pn_dflags |= PND_BOUND;
 
-        return JS_TRUE;
+        return true;
     }
 
     uint16_t level = cookie.level();
     JS_ASSERT(bce->sc->staticLevel >= level);
 
     const unsigned skip = bce->sc->staticLevel - level;
     if (skip != 0)
-        return JS_TRUE;
+        return true;
 
     /*
      * We are compiling a function body and may be able to optimize name
      * to stack slot. Look for an argument or variable in the function and
      * rewrite pn_op and update pn accordingly.
      */
     switch (dn_kind) {
       case Definition::UNKNOWN:
-        return JS_TRUE;
+        return true;
 
       case Definition::LET:
         switch (op) {
           case JSOP_NAME:     op = JSOP_GETLOCAL; break;
           case JSOP_SETNAME:  op = JSOP_SETLOCAL; break;
           case JSOP_INCNAME:  op = JSOP_INCLOCAL; break;
           case JSOP_NAMEINC:  op = JSOP_LOCALINC; break;
           case JSOP_DECNAME:  op = JSOP_DECLOCAL; break;
@@ -1362,17 +1365,17 @@ BindNameToSlot(JSContext *cx, BytecodeEm
             JS_ASSERT(op != JSOP_DELNAME);
             if (!bce->sc->funIsHeavyweight()) {
                 op = JSOP_CALLEE;
                 pn->pn_dflags |= PND_CONST;
             }
 
             pn->setOp(op);
             pn->pn_dflags |= PND_BOUND;
-            return JS_TRUE;
+            return true;
         }
         /* FALL THROUGH */
 
       default:
         JS_ASSERT_IF(dn_kind != Definition::FUNCTION,
                      dn_kind == Definition::VAR ||
                      dn_kind == Definition::CONST);
         switch (op) {
@@ -1386,19 +1389,20 @@ BindNameToSlot(JSContext *cx, BytecodeEm
           default: JS_NOT_REACHED("local");
         }
         JS_ASSERT_IF(dn_kind == Definition::CONST, pn->pn_dflags & PND_CONST);
         break;
     }
 
     JS_ASSERT(!pn->isOp(op));
     pn->setOp(op);
-    pn->pn_cookie.set(0, cookie.slot());
+    if (!pn->pn_cookie.set(bce->sc->context, 0, cookie.slot()))
+        return false;
     pn->pn_dflags |= PND_BOUND;
-    return JS_TRUE;
+    return true;
 }
 
 /*
  * If pn contains a useful expression, return true with *answer set to true.
  * If pn contains a useless expression, return true with *answer set to false.
  * Return false on error.
  *
  * The caller should initialize *answer to false and invoke this function on
@@ -4839,39 +4843,29 @@ EmitFunc(JSContext *cx, BytecodeEmitter 
         return EmitFunctionDefNop(cx, bce, pn->pn_index);
     }
 
     JS_ASSERT_IF(pn->pn_funbox->funIsHeavyweight(),
                  fun->kind() == JSFUN_INTERPRETED);
 
     {
         FunctionBox *funbox = pn->pn_funbox;
-        SharedContext sc(cx, /* scopeChain = */ NULL, fun, funbox);
-        BytecodeEmitter bce2(bce->parser, &sc, pn->pn_pos.begin.lineno,
-                             /* noScriptRval = */ false, /* needsScriptGlobal = */ false);
-        if (!bce2.init())
-            return false;
-
+        SharedContext sc(cx, /* scopeChain = */ NULL, fun, funbox, bce->sc->staticLevel + 1);
         sc.cxFlags = funbox->cxFlags;
         if (bce->sc->funMightAliasLocals())
             sc.setFunMightAliasLocals();  // inherit funMightAliasLocals from parent
-
         sc.bindings.transfer(cx, &funbox->bindings);
+
+        BytecodeEmitter bce2(bce->parser, &sc, pn->pn_pos.begin.lineno,
+                             /* noScriptRval = */ false, /* needsScriptGlobal = */ false);
+        if (!bce2.init())
+            return false;
         bce2.parent = bce;
         bce2.globalScope = bce->globalScope;
 
-        /*
-         * js::frontend::SetStaticLevel limited static nesting depth to fit in
-         * 16 bits and to reserve the all-ones value, thereby reserving the
-         * magic FREE_UPVAR_COOKIE value. Note the bce2.staticLevel assignment
-         * below.
-         */
-        JS_ASSERT(bce->sc->staticLevel < JS_BITMASK(16) - 1);
-        sc.staticLevel = bce->sc->staticLevel + 1;
-
         /* We measured the max scope depth when we parsed the function. */
         if (!EmitFunctionScript(cx, &bce2, pn->pn_body))
             return false;
     }
 
     /* Make the function object a literal in the outer script's pool. */
     unsigned index = bce->objectList.add(pn->pn_funbox);
 
--- a/js/src/frontend/ParseNode-inl.h
+++ b/js/src/frontend/ParseNode-inl.h
@@ -10,16 +10,32 @@
 #include "frontend/ParseNode.h"
 #include "frontend/TokenStream.h"
 #include "frontend/TreeContext.h"
 
 #include "frontend/TreeContext-inl.h"
 
 namespace js {
 
+inline bool
+UpvarCookie::set(JSContext *cx, unsigned newLevel, uint16_t newSlot)
+{
+    // This is an unsigned-to-uint16_t conversion, test for too-high values.
+    // In practice, recursion in Parser and/or BytecodeEmitter will blow the
+    // stack if we nest functions more than a few hundred deep, so this will
+    // never trigger.  Oh well.
+    if (newLevel >= FREE_LEVEL) {
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_TOO_DEEP, js_function_str);
+        return false;
+    }
+    level_ = newLevel;
+    slot_ = newSlot;
+    return true;
+}
+
 inline PropertyName *
 ParseNode::atom() const
 {
     JS_ASSERT(isKind(PNK_FUNCTION) || isKind(PNK_NAME));
     JSAtom *atom = isKind(PNK_FUNCTION) ? pn_funbox->function()->atom : pn_atom;
     return atom->asPropertyName();
 }
 
--- a/js/src/frontend/ParseNode.h
+++ b/js/src/frontend/ParseNode.h
@@ -23,48 +23,43 @@ namespace js {
  * as a two tuple of (level, slot).
  *
  * Some existing client code uses the level value as a delta, or level "skip"
  * quantity. We could probably document that through use of more types at some
  * point in the future.
  */
 class UpvarCookie
 {
-    uint32_t value;
-
-    static const uint32_t FREE_VALUE = 0xfffffffful;
+    uint16_t level_;
+    uint16_t slot_;
 
     void checkInvariants() {
         JS_STATIC_ASSERT(sizeof(UpvarCookie) == sizeof(uint32_t));
-        JS_STATIC_ASSERT(UPVAR_LEVEL_LIMIT < FREE_LEVEL);
     }
 
   public:
-    /*
-     * All levels above-and-including FREE_LEVEL are reserved so that
-     * FREE_VALUE can be used as a special value.
-     */
-    static const uint16_t FREE_LEVEL = 0x3fff;
+    // FREE_LEVEL is a distinguished value used to indicate the cookie is free.
+    static const uint16_t FREE_LEVEL = 0xffff;
+
+    static const uint16_t CALLEE_SLOT = 0xffff;
+
+    static bool isLevelReserved(uint16_t level) { return level == FREE_LEVEL; }
 
-    /*
-     * If a function has a higher static level than this limit, we will not
-     * optimize it using UPVAR opcodes.
-     */
-    static const uint16_t UPVAR_LEVEL_LIMIT = 16;
-    static const uint16_t CALLEE_SLOT = 0xffff;
-    static bool isLevelReserved(uint16_t level) { return level >= FREE_LEVEL; }
+    bool isFree() const { return level_ == FREE_LEVEL; }
+    uint16_t level() const { JS_ASSERT(!isFree()); return level_; }
+    uint16_t slot()  const { JS_ASSERT(!isFree()); return slot_; }
 
-    bool isFree() const { return value == FREE_VALUE; }
-    /* isFree check should be performed before using these accessors. */
-    uint16_t level() const { JS_ASSERT(!isFree()); return uint16_t(value >> 16); }
-    uint16_t slot() const { JS_ASSERT(!isFree()); return uint16_t(value); }
+    // This fails and issues an error message if newLevel is too large.
+    bool set(JSContext *cx, unsigned newLevel, uint16_t newSlot);
 
-    void set(const UpvarCookie &other) { set(other.level(), other.slot()); }
-    void set(uint16_t newLevel, uint16_t newSlot) { value = (uint32_t(newLevel) << 16) | newSlot; }
-    void makeFree() { set(0xffff, 0xffff); JS_ASSERT(isFree()); }
+    void makeFree() {
+        level_ = FREE_LEVEL;
+        slot_ = 0;      // value doesn't matter, won't be used
+        JS_ASSERT(isFree());
+    }
 };
 
 /*
  * Parsing builds a tree of nodes that directs code generation.  This tree is
  * not a concrete syntax tree in all respects (for example, || and && are left
  * associative, but (A && B && C) translates into the right-associated tree
  * <A && <B && C>> so that code generation can emit a left-associative branch
  * around <B && C> when A is false).  Nodes are labeled by kind, with a
@@ -1498,26 +1493,24 @@ struct ObjectBox {
     ObjectBox           *traceLink;
     ObjectBox           *emitLink;
     JSObject            *object;
     bool                isFunctionBox;
 
     ObjectBox(ObjectBox *traceLink, JSObject *obj);
 };
 
-#define JSFB_LEVEL_BITS 14
-
 struct FunctionBox : public ObjectBox
 {
     ParseNode       *node;
     FunctionBox     *siblings;
     FunctionBox     *kids;
     FunctionBox     *parent;
     Bindings        bindings;               /* bindings for this function */
-    uint32_t        level:JSFB_LEVEL_BITS;
+    uint16_t        level;
     uint16_t        ndefaults;
     bool            inLoop:1;               /* in a loop in parent function */
     bool            inWith:1;               /* some enclosing scope is a with-statement
                                                or E4X filter-expression */
     bool            inGenexpLambda:1;       /* lambda from generator expression */
 
     ContextFlags    cxFlags;
 
--- a/js/src/frontend/Parser.cpp
+++ b/js/src/frontend/Parser.cpp
@@ -261,17 +261,18 @@ Parser::parse(JSObject *chain)
     /*
      * Protect atoms from being collected by a GC activation, which might
      * - nest on this thread due to out of memory (the so-called "last ditch"
      *   GC attempted within js_NewGCThing), or
      * - run for any reason on another thread if this thread is suspended on
      *   an object lock before it finishes generating bytecode into a script
      *   protected from the GC by a root or a stack frame reference.
      */
-    SharedContext globalsc(context, chain, /* fun = */ NULL, /* funbox = */ NULL);
+    SharedContext globalsc(context, chain, /* fun = */ NULL, /* funbox = */ NULL,
+                           /* staticLevel = */ 0);
     TreeContext globaltc(this, &globalsc);
     if (!globaltc.init())
         return NULL;
     if (!GenerateBlockId(&globalsc, globalsc.bodyid))
         return NULL;
 
     ParseNode *pn = statements();
     if (pn) {
@@ -281,18 +282,16 @@ Parser::parse(JSObject *chain)
         } else if (foldConstants) {
             if (!FoldConstants(context, pn, this))
                 pn = NULL;
         }
     }
     return pn;
 }
 
-JS_STATIC_ASSERT(UpvarCookie::FREE_LEVEL == JS_BITMASK(JSFB_LEVEL_BITS));
-
 /*
  * Insist on a final return before control flows out of pn.  Try to be a bit
  * smart about loops: do {...; return e2;} while(0) at the end of a function
  * that contains an early return e1 will get a strict warning.  Similarly for
  * iloops: while (true){...} is treated as though ... returns.
  */
 #define ENDS_IN_OTHER   0
 #define ENDS_IN_RETURN  1
@@ -559,17 +558,18 @@ static bool
 BindLocalVariable(JSContext *cx, SharedContext *sc, ParseNode *pn, BindingKind kind)
 {
     JS_ASSERT(kind == VARIABLE || kind == CONSTANT);
 
     unsigned index = sc->bindings.numVars();
     if (!sc->bindings.add(cx, RootedAtom(cx, pn->pn_atom), kind))
         return false;
 
-    pn->pn_cookie.set(sc->staticLevel, index);
+    if (!pn->pn_cookie.set(cx, sc->staticLevel, index))
+        return false;
     pn->pn_dflags |= PND_BOUND;
     return true;
 }
 
 ParseNode *
 Parser::functionBody(FunctionBodyType type)
 {
     JS_ASSERT(tc->sc->inFunction());
@@ -927,17 +927,18 @@ js::DefineArg(ParseNode *pn, JSAtom *ato
     argpn->pn_dflags |= PND_INITIALIZED;
     if (!Define(argpn, atom, parser->tc))
         return false;
 
     ParseNode *argsbody = pn->pn_body;
     argsbody->append(argpn);
 
     argpn->setOp(JSOP_GETARG);
-    argpn->pn_cookie.set(parser->tc->sc->staticLevel, i);
+    if (!argpn->pn_cookie.set(parser->context, parser->tc->sc->staticLevel, i))
+        return false;
     argpn->pn_dflags |= PND_BOUND;
     return true;
 }
 
 /*
  * Parameter block types for the several Binder functions.  We use a common
  * helper function signature in order to share code among destructuring and
  * simple variable declaration parsers.  In the destructuring case, the binder
@@ -1080,18 +1081,16 @@ MatchOrInsertSemicolon(JSContext *cx, To
 
 static bool
 EnterFunction(SharedContext *outersc, SharedContext *funsc)
 {
     /* Initialize non-default members of funsc. */
     funsc->blockidGen = outersc->blockidGen;
     if (!GenerateBlockId(funsc, funsc->bodyid))
         return false;
-    if (!SetStaticLevel(funsc, outersc->staticLevel + 1))
-        return false;
 
     return true;
 }
 
 static bool
 DeoptimizeUsesWithin(Definition *dn, const TokenPos &pos)
 {
     unsigned ndeoptimized = 0;
@@ -1141,17 +1140,19 @@ LeaveFunction(ParseNode *fn, Parser *par
 
         for (AtomDefnRange r = funtc->lexdeps->all(); !r.empty(); r.popFront()) {
             JSAtom *atom = r.front().key();
             Definition *dn = r.front().value();
             JS_ASSERT(dn->isPlaceholder());
 
             if (atom == funName && kind == Expression) {
                 dn->setOp(JSOP_CALLEE);
-                dn->pn_cookie.set(funtc->sc->staticLevel, UpvarCookie::CALLEE_SLOT);
+                if (!dn->pn_cookie.set(parser->context, funtc->sc->staticLevel,
+                                       UpvarCookie::CALLEE_SLOT))
+                    return false;
                 dn->pn_dflags |= PND_BOUND;
                 foundCallee = 1;
                 continue;
             }
 
             Definition *outer_dn = tc->decls.lookupFirst(atom);
 
             /*
@@ -1334,17 +1335,18 @@ Parser::functionArguments(ParseNode **li
                  * anonymous positional parameter into the destructuring
                  * left-hand-side expression and accumulate it in list.
                  */
                 ParseNode *rhs = NameNode::create(PNK_NAME, context->runtime->atomState.emptyAtom,
                                                   this, this->tc->sc);
                 if (!rhs)
                     return false;
                 rhs->setOp(JSOP_GETARG);
-                rhs->pn_cookie.set(tc->sc->staticLevel, slot);
+                if (!rhs->pn_cookie.set(context, tc->sc->staticLevel, slot))
+                    return false;
                 rhs->pn_dflags |= PND_BOUND;
                 rhs->setDefn(true);
 
                 ParseNode *item = new_<BinaryNode>(PNK_ASSIGN, JSOP_NOP, lhs->pn_pos, lhs, rhs);
                 if (!item)
                     return false;
                 if (!list) {
                     list = ListNode::create(PNK_VAR, this);
@@ -1549,17 +1551,18 @@ Parser::functionDef(HandlePropertyName f
               case NONE:
               case ARGUMENT:
                 index = tc->sc->bindings.numVars();
                 if (!tc->sc->bindings.addVariable(context, funName))
                     return NULL;
                 /* FALL THROUGH */
 
               case VARIABLE:
-                pn->pn_cookie.set(tc->sc->staticLevel, index);
+                if (!pn->pn_cookie.set(context, tc->sc->staticLevel, index))
+                    return NULL;
                 pn->pn_dflags |= PND_BOUND;
                 break;
 
               default:;
             }
         }
     }
 
@@ -1570,17 +1573,18 @@ Parser::functionDef(HandlePropertyName f
         return NULL;
 
     /* Create box for fun->object early to protect against last-ditch GC. */
     FunctionBox *funbox = newFunctionBox(fun, pn, outertc);
     if (!funbox)
         return NULL;
 
     /* Initialize early for possible flags mutation via destructuringExpr. */
-    SharedContext funsc(context, /* scopeChain = */ NULL, fun, funbox);
+    SharedContext funsc(context, /* scopeChain = */ NULL, fun, funbox,
+                        outertc->sc->staticLevel + 1);
     TreeContext funtc(this, &funsc);
     if (!funtc.init())
         return NULL;
 
     if (!EnterFunction(outertc->sc, &funsc))
         return NULL;
 
     if (outertc->sc->inStrictMode())
@@ -2036,17 +2040,18 @@ BindLet(JSContext *cx, BindData *data, J
     /*
      * Assign block-local index to pn->pn_cookie right away, encoding it as an
      * upvar cookie whose skip tells the current static level. The emitter will
      * adjust the node's slot based on its stack depth model -- and, for global
      * and eval code, js::frontend::CompileScript will adjust the slot
      * again to include script->nfixed.
      */
     pn->setOp(JSOP_GETLOCAL);
-    pn->pn_cookie.set(tc->sc->staticLevel, uint16_t(blockCount));
+    if (!pn->pn_cookie.set(parser->context, tc->sc->staticLevel, uint16_t(blockCount)))
+        return false;
     pn->pn_dflags |= PND_LET | PND_BOUND;
 
     /*
      * Define the let binding's property before storing pn in the the binding's
      * slot indexed by blockCount off the class-reserved slot base.
      */
     bool redeclared;
     jsid id = AtomToId(atom);
@@ -5016,29 +5021,22 @@ GenexpGuard::maybeNoteGenerator(ParseNod
 /*
  * Any definitions nested within the comprehension expression of a generator
  * expression must move "down" one static level, which of course increases the
  * upvar-frame-skip count.
  */
 static bool
 BumpStaticLevel(ParseNode *pn, TreeContext *tc)
 {
-    if (!pn->pn_cookie.isFree()) {
-        unsigned level = pn->pn_cookie.level() + 1;
-
-        JS_ASSERT(level >= tc->sc->staticLevel);
-        if (level >= UpvarCookie::FREE_LEVEL) {
-            JS_ReportErrorNumber(tc->sc->context, js_GetErrorMessage, NULL,
-                                 JSMSG_TOO_DEEP, js_function_str);
-            return false;
-        }
-
-        pn->pn_cookie.set(level, pn->pn_cookie.slot());
-    }
-    return true;
+    if (pn->pn_cookie.isFree())
+        return true;
+
+    unsigned level = unsigned(pn->pn_cookie.level()) + 1;
+    JS_ASSERT(level >= tc->sc->staticLevel);
+    return pn->pn_cookie.set(tc->sc->context, level, pn->pn_cookie.slot());
 }
 
 static void
 AdjustBlockId(ParseNode *pn, unsigned adjust, SharedContext *sc)
 {
     JS_ASSERT(pn->isArity(PN_LIST) || pn->isArity(PN_FUNC) || pn->isArity(PN_NAME));
     pn->pn_blockid += adjust;
     if (pn->pn_blockid >= sc->blockidGen)
@@ -5494,17 +5492,18 @@ Parser::generatorExpr(ParseNode *kid)
         if (!fun)
             return NULL;
 
         /* Create box for fun->object early to protect against last-ditch GC. */
         FunctionBox *funbox = newFunctionBox(fun, genfn, outertc);
         if (!funbox)
             return NULL;
 
-        SharedContext gensc(context, /* scopeChain = */ NULL, fun, funbox);
+        SharedContext gensc(context, /* scopeChain = */ NULL, fun, funbox,
+                            outertc->sc->staticLevel + 1);
         TreeContext gentc(this, &gensc);
         if (!gentc.init())
             return NULL;
 
         if (!EnterFunction(outertc->sc, &gensc))
             return NULL;
 
         /*
@@ -6471,17 +6470,18 @@ Parser::xmlElementOrListRoot(JSBool allo
 ParseNode *
 Parser::parseXMLText(JSObject *chain, bool allowList)
 {
     /*
      * Push a compiler frame if we have no frames, or if the top frame is a
      * lightweight function activation, or if its scope chain doesn't match
      * the one passed to us.
      */
-    SharedContext xmlsc(context, chain, /* fun = */ NULL, /* funbox = */ NULL);
+    SharedContext xmlsc(context, chain, /* fun = */ NULL, /* funbox = */ NULL,
+                        /* staticLevel = */ 0);
     TreeContext xmltc(this, &xmlsc);
     if (!xmltc.init())
         return NULL;
     JS_ASSERT(!xmlsc.inStrictMode());
 
     /* Set XML-only mode to turn off special treatment of {expr} in XML. */
     tokenStream.setXMLOnlyMode();
     TokenKind tt = tokenStream.getToken(TSF_OPERAND);
--- a/js/src/frontend/TreeContext-inl.h
+++ b/js/src/frontend/TreeContext-inl.h
@@ -12,27 +12,27 @@
 #include "frontend/TreeContext.h"
 
 #include "frontend/ParseMaps-inl.h"
 
 namespace js {
 
 inline
 SharedContext::SharedContext(JSContext *cx, JSObject *scopeChain, JSFunction *fun,
-                             FunctionBox *funbox)
+                             FunctionBox *funbox, unsigned staticLevel)
   : context(cx),
     bodyid(0),
     blockidGen(0),
     topStmt(NULL),
     topScopeStmt(NULL),
     blockChain(cx),
     fun_(cx, fun),
     funbox_(funbox),
     scopeChain_(cx, scopeChain),
-    staticLevel(0),
+    staticLevel(staticLevel),
     bindings(cx),
     bindingsRoot(cx, &bindings),
     cxFlags(cx)
 {
     JS_ASSERT((fun && !scopeChain_) || (!fun && !funbox));
 }
 
 inline unsigned
--- a/js/src/frontend/TreeContext.cpp
+++ b/js/src/frontend/TreeContext.cpp
@@ -19,32 +19,16 @@ using namespace js::frontend;
 
 void
 TreeContext::trace(JSTracer *trc)
 {
     sc->bindings.trace(trc);
 }
 
 bool
-frontend::SetStaticLevel(SharedContext *sc, unsigned staticLevel)
-{
-    /*
-     * This is a lot simpler than error-checking every UpvarCookie::set, and
-     * practically speaking it leaves more than enough room for upvars.
-     */
-    if (UpvarCookie::isLevelReserved(staticLevel)) {
-        JS_ReportErrorNumber(sc->context, js_GetErrorMessage, NULL,
-                             JSMSG_TOO_DEEP, js_function_str);
-        return false;
-    }
-    sc->staticLevel = staticLevel;
-    return true;
-}
-
-bool
 frontend::GenerateBlockId(SharedContext *sc, uint32_t &blockid)
 {
     if (sc->blockidGen == JS_BIT(20)) {
         JS_ReportErrorNumber(sc->context, js_GetErrorMessage, NULL, JSMSG_NEED_DIET, "program");
         return false;
     }
     blockid = sc->blockidGen++;
     return true;
--- a/js/src/frontend/TreeContext.h
+++ b/js/src/frontend/TreeContext.h
@@ -143,27 +143,28 @@ struct SharedContext {
                                        names when it's a function's context */
     FunctionBox *const funbox_;     /* null or box for function we're compiling
                                        if inFunction() is true and not in
                                        js::frontend::CompileFunctionBody */
 
     const RootedObject scopeChain_; /* scope chain object for the script */
 
   public:
-    unsigned        staticLevel;    /* static compilation unit nesting level */
+    const unsigned  staticLevel;    /* static compilation unit nesting level */
 
     Bindings        bindings;       /* bindings in this code, including
                                        arguments if we're compiling a function */
     Bindings::AutoRooter bindingsRoot; /* root for stack allocated bindings. */
 
     ContextFlags    cxFlags;
 
     // If it's function code, fun must be non-NULL and scopeChain must be NULL.
     // If it's global code, fun and funbox must be NULL.
-    inline SharedContext(JSContext *cx, JSObject *scopeChain, JSFunction *fun, FunctionBox *funbox);
+    inline SharedContext(JSContext *cx, JSObject *scopeChain, JSFunction *fun, FunctionBox *funbox,
+                         unsigned staticLevel);
 
     // In theory, |fun*| flags are only relevant if |inFunction()| is true.
     // However, we get and set in some cases where |inFunction()| is false,
     // which is why |INFUNC| doesn't appear in all of the fun* and setFun*
     // functions below.
 #define INFUNC JS_ASSERT(inFunction())
 
     bool inStrictMode()                const {         return cxFlags.inStrictMode; }
@@ -364,19 +365,16 @@ struct StmtInfo {
 #define SIF_FOR_BLOCK    0x0004     /* for (let ...) induced block scope */
 
 #define SET_STATEMENT_TOP(stmt, top)                                          \
     ((stmt)->update = (top), (stmt)->breaks = (stmt)->continues = (-1))
 
 namespace frontend {
 
 bool
-SetStaticLevel(SharedContext *sc, unsigned staticLevel);
-
-bool
 GenerateBlockId(SharedContext *sc, uint32_t &blockid);
 
 /*
  * Push the C-stack-allocated struct at stmt onto the stmtInfo stack.
  */
 void
 PushStatement(SharedContext *sc, StmtInfo *stmt, StmtType type, ptrdiff_t top);
 
new file mode 100644
--- /dev/null
+++ b/js/src/jit-test/tests/basic/proxy-assign-inherited.js
@@ -0,0 +1,21 @@
+// When we assign to a property that a proxy claims is inherited, the
+// defineProperty handler call to create the new own property should get
+// the newly assigned value.
+
+var hits;
+var handlers = {
+  getOwnPropertyDescriptor: function(name) {
+    return undefined;
+  },
+  getPropertyDescriptor: function(name) {
+    return { value:42, writable:true, enumerable:true, configurable:true };
+  },
+  defineProperty: function(name, descriptor) {
+    hits++;
+    assertEq(name, 'x');
+    assertEq(descriptor.value, 43);
+  }
+};
+hits = 0;
+Proxy.create(handlers).x = 43;
+assertEq(hits, 1);
\ No newline at end of file
new file mode 100644
--- /dev/null
+++ b/js/src/jit-test/tests/basic/testBug762450.js
@@ -0,0 +1,7 @@
+function f(a, b, c) {
+    arguments[0] = 3;
+    return (c--) + 1;
+}
+var r = f();
+print(r);
+assertEq(r !== r, true);
rename from js/src/jit-test/tests/basic/bug557168-1.js
rename to js/src/jit-test/tests/e4x/bug557168-1.js
rename from js/src/jit-test/tests/basic/bug557168-2.js
rename to js/src/jit-test/tests/e4x/bug557168-2.js
rename from js/src/jit-test/tests/basic/bug557168-3.js
rename to js/src/jit-test/tests/e4x/bug557168-3.js
rename from js/src/jit-test/tests/basic/bug557168.js
rename to js/src/jit-test/tests/e4x/bug557168.js
rename from js/src/jit-test/tests/basic/bug569843.js
rename to js/src/jit-test/tests/e4x/bug569843.js
rename from js/src/jit-test/tests/basic/bug574280.js
rename to js/src/jit-test/tests/e4x/bug574280.js
rename from js/src/jit-test/tests/basic/bug596502-version.js
rename to js/src/jit-test/tests/e4x/bug596502-version.js
rename from js/src/jit-test/tests/basic/bug605200.js
rename to js/src/jit-test/tests/e4x/bug605200.js
rename from js/src/jit-test/tests/basic/bug613151.js
rename to js/src/jit-test/tests/e4x/bug613151.js
rename from js/src/jit-test/tests/basic/bug632206.js
rename to js/src/jit-test/tests/e4x/bug632206.js
rename from js/src/jit-test/tests/basic/bug651966.js
rename to js/src/jit-test/tests/e4x/bug651966.js
rename from js/src/jit-test/tests/basic/bug665812.js
rename to js/src/jit-test/tests/e4x/bug665812.js
rename from js/src/jit-test/tests/basic/bug672153.js
rename to js/src/jit-test/tests/e4x/bug672153.js
rename from js/src/jit-test/tests/basic/bug700799.js
rename to js/src/jit-test/tests/e4x/bug700799.js
rename from js/src/jit-test/tests/basic/bug716713.js
rename to js/src/jit-test/tests/e4x/bug716713.js
rename from js/src/jit-test/tests/basic/bug731724.js
rename to js/src/jit-test/tests/e4x/bug731724.js
rename from js/src/jit-test/tests/basic/bug731745.js
rename to js/src/jit-test/tests/e4x/bug731745.js