Merge Places and mozilla-central
authorMarco Bonardo <mbonardo@mozilla.com>
Wed, 08 Jun 2011 12:21:07 +0200
changeset 71234 79dcd5e5a6f418e5393110a5fc79664b32a36513
parent 71233 382193f2726e5c2a5748504c218d783b9d5e585f (current diff)
parent 71228 0b370bace7fb39f0c22c2b953c04d4a76818023a (diff)
child 71236 a58cdcdcac5fd5fc2a6872779f18e6825d80df03
push id159
push usereakhgari@mozilla.com
push dateTue, 16 Aug 2011 17:53:11 +0000
treeherdermozilla-beta@8786e3e49240 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone7.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Merge Places and mozilla-central
browser/themes/pinstripe/browser/Secure-background.gif
content/base/test/test_bug414796.html
dom/interfaces/core/nsIDOM3TypeInfo.idl
dom/interfaces/core/nsIDOMNotation.idl
js/src/jit-test/tests/basic/testStackQuotaExhausted.js
js/src/yarr/Makefile
js/src/yarr/jswtfbridge.h
js/src/yarr/pcre/AUTHORS
js/src/yarr/pcre/COPYING
js/src/yarr/pcre/chartables.c
js/src/yarr/pcre/dftables
js/src/yarr/pcre/pcre.h
js/src/yarr/pcre/pcre.pri
js/src/yarr/pcre/pcre_compile.cpp
js/src/yarr/pcre/pcre_exec.cpp
js/src/yarr/pcre/pcre_internal.h
js/src/yarr/pcre/pcre_tables.cpp
js/src/yarr/pcre/pcre_ucp_searchfuncs.cpp
js/src/yarr/pcre/pcre_xclass.cpp
js/src/yarr/pcre/ucpinternal.h
js/src/yarr/pcre/ucptable.cpp
js/src/yarr/wtf/ASCIICType.h
js/src/yarr/yarr/RegExpJitTables.h
js/src/yarr/yarr/RegexCommon.h
js/src/yarr/yarr/RegexCompiler.cpp
js/src/yarr/yarr/RegexCompiler.h
js/src/yarr/yarr/RegexJIT.cpp
js/src/yarr/yarr/RegexJIT.h
js/src/yarr/yarr/RegexParser.h
js/src/yarr/yarr/RegexPattern.h
mobile/chrome/content/bindings/setting.xml
mobile/chrome/content/firstrun/facebook.png
mobile/chrome/content/firstrun/features.png
mobile/chrome/content/firstrun/firstrun.xhtml
mobile/chrome/content/firstrun/mozilla.png
mobile/chrome/content/firstrun/nav-arrow.png
mobile/chrome/content/firstrun/twitter.png
mobile/locales/en-US/chrome/firstrun.dtd
mobile/themes/core/firstRun.css
toolkit/components/places/nsNavHistory.cpp
--- a/accessible/src/base/AccEvent.cpp
+++ b/accessible/src/base/AccEvent.cpp
@@ -308,18 +308,18 @@ AccMutationEvent::
 // AccHideEvent
 ////////////////////////////////////////////////////////////////////////////////
 
 AccHideEvent::
   AccHideEvent(nsAccessible* aTarget, nsINode* aTargetNode) :
   AccMutationEvent(::nsIAccessibleEvent::EVENT_HIDE, aTarget, aTargetNode)
 {
   mParent = mAccessible->GetParent();
-  mNextSibling = mAccessible->GetCachedNextSibling();
-  mPrevSibling = mAccessible->GetCachedPrevSibling();
+  mNextSibling = mAccessible->NextSibling();
+  mPrevSibling = mAccessible->PrevSibling();
 }
 
 
 ////////////////////////////////////////////////////////////////////////////////
 // AccShowEvent
 ////////////////////////////////////////////////////////////////////////////////
 
 AccShowEvent::
--- a/accessible/src/base/AccGroupInfo.cpp
+++ b/accessible/src/base/AccGroupInfo.cpp
@@ -147,27 +147,27 @@ AccGroupInfo::AccGroupInfo(nsAccessible*
   // parent. Or, if the parent is something other than a tree we will
   // return that.
 
   if (parentRole != nsIAccessibleRole::ROLE_GROUPING) {
     mParent = parent;
     return;
   }
 
-  nsAccessible* parentPrevSibling = parent->GetSiblingAtOffset(-1);
+  nsAccessible* parentPrevSibling = parent->PrevSibling();
   if (!parentPrevSibling)
     return;
 
   PRUint32 parentPrevSiblingRole = parentPrevSibling->Role();
   if (parentPrevSiblingRole == nsIAccessibleRole::ROLE_TEXT_LEAF) {
     // XXX Sometimes an empty text accessible is in the hierarchy here,
     // although the text does not appear to be rendered, GetRenderedText()
     // says that it is so we need to skip past it to find the true
     // previous sibling.
-    parentPrevSibling = parentPrevSibling->GetSiblingAtOffset(-1);
+    parentPrevSibling = parentPrevSibling->PrevSibling();
     if (parentPrevSibling)
       parentPrevSiblingRole = parentPrevSibling->Role();
   }
 
   // Previous sibling of parent group is a tree item, this is the
   // conceptual tree item parent.
   if (parentPrevSiblingRole == nsIAccessibleRole::ROLE_OUTLINEITEM)
     mParent = parentPrevSibling;
--- a/accessible/src/base/nsAccessible.cpp
+++ b/accessible/src/base/nsAccessible.cpp
@@ -336,40 +336,38 @@ nsAccessible::Description(nsString& aDes
 #define NS_MODIFIER_META     8
 
 // returns the accesskey modifier mask used in the given node's context
 // (i.e. chrome or content), or 0 if an error occurs
 static PRInt32
 GetAccessModifierMask(nsIContent* aContent)
 {
   // use ui.key.generalAccessKey (unless it is -1)
-  PRInt32 accessKey = -1;
-  nsresult rv = Preferences::GetInt("ui.key.generalAccessKey", accessKey);
-  if (NS_SUCCEEDED(rv) && accessKey != -1) {
-    switch (accessKey) {
-      case nsIDOMKeyEvent::DOM_VK_SHIFT:   return NS_MODIFIER_SHIFT;
-      case nsIDOMKeyEvent::DOM_VK_CONTROL: return NS_MODIFIER_CONTROL;
-      case nsIDOMKeyEvent::DOM_VK_ALT:     return NS_MODIFIER_ALT;
-      case nsIDOMKeyEvent::DOM_VK_META:    return NS_MODIFIER_META;
-      default:                             return 0;
-    }
+  switch (Preferences::GetInt("ui.key.generalAccessKey", -1)) {
+    case -1:                             break;
+    case nsIDOMKeyEvent::DOM_VK_SHIFT:   return NS_MODIFIER_SHIFT;
+    case nsIDOMKeyEvent::DOM_VK_CONTROL: return NS_MODIFIER_CONTROL;
+    case nsIDOMKeyEvent::DOM_VK_ALT:     return NS_MODIFIER_ALT;
+    case nsIDOMKeyEvent::DOM_VK_META:    return NS_MODIFIER_META;
+    default:                             return 0;
   }
 
   // get the docShell to this DOMNode, return 0 on failure
   nsCOMPtr<nsIDocument> document = aContent->GetCurrentDoc();
   if (!document)
     return 0;
   nsCOMPtr<nsISupports> container = document->GetContainer();
   if (!container)
     return 0;
   nsCOMPtr<nsIDocShellTreeItem> treeItem(do_QueryInterface(container));
   if (!treeItem)
     return 0;
 
   // determine the access modifier used in this context
+  nsresult rv = NS_ERROR_FAILURE;
   PRInt32 itemType, accessModifierMask = 0;
   treeItem->GetItemType(&itemType);
   switch (itemType) {
     case nsIDocShellTreeItem::typeChrome:
       rv = Preferences::GetInt("ui.key.chromeAccess", &accessModifierMask);
       break;
 
     case nsIDocShellTreeItem::typeContent:
@@ -447,27 +445,35 @@ nsAccessible::GetParent(nsIAccessible **
   return *aParent ? NS_OK : NS_ERROR_FAILURE;
 }
 
   /* readonly attribute nsIAccessible nextSibling; */
 NS_IMETHODIMP
 nsAccessible::GetNextSibling(nsIAccessible **aNextSibling) 
 {
   NS_ENSURE_ARG_POINTER(aNextSibling);
+  *aNextSibling = nsnull;
+
+  if (IsDefunct())
+    return NS_ERROR_FAILURE;
 
   nsresult rv = NS_OK;
   NS_IF_ADDREF(*aNextSibling = GetSiblingAtOffset(1, &rv));
   return rv;
 }
 
   /* readonly attribute nsIAccessible previousSibling; */
 NS_IMETHODIMP
 nsAccessible::GetPreviousSibling(nsIAccessible * *aPreviousSibling) 
 {
   NS_ENSURE_ARG_POINTER(aPreviousSibling);
+  *aPreviousSibling = nsnull;
+
+  if (IsDefunct())
+    return NS_ERROR_FAILURE;
 
   nsresult rv = NS_OK;
   NS_IF_ADDREF(*aPreviousSibling = GetSiblingAtOffset(-1, &rv));
   return rv;
 }
 
   /* readonly attribute nsIAccessible firstChild; */
 NS_IMETHODIMP
@@ -600,17 +606,17 @@ nsresult nsAccessible::GetTranslatedStri
 
 nsresult nsAccessible::GetFullKeyName(const nsAString& aModifierName, const nsAString& aKeyName, nsAString& aStringOut)
 {
   nsXPIDLString modifierName, separator;
 
   if (!gKeyStringBundle ||
       NS_FAILED(gKeyStringBundle->GetStringFromName(PromiseFlatString(aModifierName).get(), 
                                                     getter_Copies(modifierName))) ||
-      NS_FAILED(gKeyStringBundle->GetStringFromName(PromiseFlatString(NS_LITERAL_STRING("MODIFIER_SEPARATOR")).get(), 
+      NS_FAILED(gKeyStringBundle->GetStringFromName(NS_LITERAL_STRING("MODIFIER_SEPARATOR").get(), 
                                                     getter_Copies(separator)))) {
     return NS_ERROR_FAILURE;
   }
 
   aStringOut = modifierName + separator + aKeyName; 
   return NS_OK;
 }
 
@@ -3163,49 +3169,31 @@ nsAccessible::EnsureChildren()
 
   if (document)
     document->NotifyOfCachingEnd(this);
 
   return false;
 }
 
 nsAccessible*
-nsAccessible::GetSiblingAtOffset(PRInt32 aOffset, nsresult* aError)
+nsAccessible::GetSiblingAtOffset(PRInt32 aOffset, nsresult* aError) const
 {
-  if (IsDefunct()) {
-    if (aError)
-      *aError = NS_ERROR_FAILURE;
-
-    return nsnull;
-  }
-
-  nsAccessible *parent = GetParent();
-  if (!parent) {
+  if (!mParent || mIndexInParent == -1) {
     if (aError)
       *aError = NS_ERROR_UNEXPECTED;
 
     return nsnull;
   }
 
-  if (mIndexInParent == -1) {
-    if (aError)
-      *aError = NS_ERROR_UNEXPECTED;
-
+  if (aError && mIndexInParent + aOffset >= mParent->GetChildCount()) {
+    *aError = NS_OK; // fail peacefully
     return nsnull;
   }
 
-  if (aError) {
-    PRInt32 childCount = parent->GetChildCount();
-    if (mIndexInParent + aOffset >= childCount) {
-      *aError = NS_OK; // fail peacefully
-      return nsnull;
-    }
-  }
-
-  nsAccessible* child = parent->GetChildAt(mIndexInParent + aOffset);
+  nsAccessible* child = mParent->GetChildAt(mIndexInParent + aOffset);
   if (aError && !child)
     *aError = NS_ERROR_UNEXPECTED;
 
   return child;
 }
 
 nsAccessible *
 nsAccessible::GetFirstAvailableAccessible(nsINode *aStartNode) const
--- a/accessible/src/base/nsAccessible.h
+++ b/accessible/src/base/nsAccessible.h
@@ -300,47 +300,56 @@ public:
   virtual PRInt32 GetIndexInParent() const;
 
   /**
    * Return true if accessible has children;
    */
   PRBool HasChildren() { return !!GetChildAt(0); }
 
   /**
+   * Return next/previous sibling of the accessible.
+   */
+  inline nsAccessible* NextSibling() const
+    {  return GetSiblingAtOffset(1); }
+  inline nsAccessible* PrevSibling() const
+    { return GetSiblingAtOffset(-1); }
+
+  /**
    * Return embedded accessible children count.
    */
   PRInt32 GetEmbeddedChildCount();
 
   /**
    * Return embedded accessible child at the given index.
    */
   nsAccessible* GetEmbeddedChildAt(PRUint32 aIndex);
 
   /**
    * Return index of the given embedded accessible child.
    */
   PRInt32 GetIndexOfEmbeddedChild(nsAccessible* aChild);
 
   /**
-   * Return cached accessible of parent-child relatives.
+   * Return number of content children/content child at index. The content
+   * child is created from markup in contrast to it's never constructed by its
+   * parent accessible (like treeitem accessibles for XUL trees).
    */
-  nsAccessible* GetCachedNextSibling() const
-  {
-    return mParent ?
-      mParent->mChildren.SafeElementAt(mIndexInParent + 1, nsnull).get() : nsnull;
-  }
-  nsAccessible* GetCachedPrevSibling() const
-  {
-    return mParent ?
-      mParent->mChildren.SafeElementAt(mIndexInParent - 1, nsnull).get() : nsnull;
-  }
-  PRUint32 GetCachedChildCount() const { return mChildren.Length(); }
-  nsAccessible* GetCachedChildAt(PRUint32 aIndex) const { return mChildren.ElementAt(aIndex); }
+  PRUint32 ContentChildCount() const { return mChildren.Length(); }
+  nsAccessible* ContentChildAt(PRUint32 aIndex) const
+    { return mChildren.ElementAt(aIndex); }
+
+  /**
+   * Return true if children were initialized.
+   */
   inline bool AreChildrenCached() const
     { return !IsChildrenFlag(eChildrenUninitialized); }
+
+  /**
+   * Return true if the accessible is attached to tree.
+   */
   bool IsBoundToParent() const { return !!mParent; }
 
   //////////////////////////////////////////////////////////////////////////////
   // Miscellaneous methods
 
   /**
    * Handle accessible event, i.e. process it, notifies observers and fires
    * platform specific event.
@@ -498,17 +507,17 @@ protected:
    */
   virtual void BindToParent(nsAccessible* aParent, PRUint32 aIndexInParent);
   void UnbindFromParent();
 
   /**
    * Return sibling accessible at the given offset.
    */
   virtual nsAccessible* GetSiblingAtOffset(PRInt32 aOffset,
-                                           nsresult *aError = nsnull);
+                                           nsresult *aError = nsnull) const;
 
   /**
    * Flags used to describe the state and type of children.
    */
   enum ChildrenFlags {
     eChildrenUninitialized = 0, // children aren't initialized
     eMixedChildren = 1 << 0, // text leaf children are presented
     eEmbeddedChildren = 1 << 1 // all children are embedded objects
--- a/accessible/src/base/nsApplicationAccessible.cpp
+++ b/accessible/src/base/nsApplicationAccessible.cpp
@@ -423,25 +423,19 @@ nsApplicationAccessible::CacheChildren()
         GetAccService()->GetDocAccessible(docNode); // ensure creation
       }
     }
     windowEnumerator->HasMoreElements(&hasMore);
   }
 }
 
 nsAccessible*
-nsApplicationAccessible::GetSiblingAtOffset(PRInt32 aOffset, nsresult* aError)
+nsApplicationAccessible::GetSiblingAtOffset(PRInt32 aOffset,
+                                            nsresult* aError) const
 {
-  if (IsDefunct()) {
-    if (aError)
-      *aError = NS_ERROR_FAILURE;
-
-    return nsnull;
-  }
-
   if (aError)
     *aError = NS_OK; // fail peacefully
 
   return nsnull;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsIAccessNode and nsAccessNode
--- a/accessible/src/base/nsApplicationAccessible.h
+++ b/accessible/src/base/nsApplicationAccessible.h
@@ -131,16 +131,16 @@ public:
 
   virtual void InvalidateChildren();
 
 protected:
 
   // nsAccessible
   virtual void CacheChildren();
   virtual nsAccessible* GetSiblingAtOffset(PRInt32 aOffset,
-                                           nsresult *aError = nsnull);
+                                           nsresult *aError = nsnull) const;
 
 private:
   nsCOMPtr<nsIXULAppInfo> mAppInfo;
 };
 
 #endif
 
--- a/accessible/src/base/nsDocAccessible.cpp
+++ b/accessible/src/base/nsDocAccessible.cpp
@@ -1914,51 +1914,54 @@ nsDocAccessible::UpdateTreeInternal(nsAc
   return updateFlags;
 }
 
 void
 nsDocAccessible::CacheChildrenInSubtree(nsAccessible* aRoot)
 {
   aRoot->EnsureChildren();
 
-  PRUint32 count = aRoot->GetChildCount();
-  for (PRUint32 idx = 0; idx < count; idx++)  {
-    nsAccessible* child = aRoot->GetChildAt(idx);
+  // Make sure we create accessible tree defined in DOM only, i.e. if accessible
+  // provides specific tree (like XUL trees) then tree creation is handled by
+  // this accessible.
+  PRUint32 count = aRoot->ContentChildCount();
+  for (PRUint32 idx = 0; idx < count; idx++) {
+    nsAccessible* child = aRoot->ContentChildAt(idx);
     NS_ASSERTION(child, "Illicit tree change while tree is created!");
     // Don't cross document boundaries.
     if (child && child->IsContent())
       CacheChildrenInSubtree(child);
   }
 }
 
 void
 nsDocAccessible::UncacheChildrenInSubtree(nsAccessible* aRoot)
 {
   if (aRoot->IsElement())
     RemoveDependentIDsFor(aRoot);
 
-  PRUint32 count = aRoot->GetCachedChildCount();
+  PRUint32 count = aRoot->ContentChildCount();
   for (PRUint32 idx = 0; idx < count; idx++)
-    UncacheChildrenInSubtree(aRoot->GetCachedChildAt(idx));
+    UncacheChildrenInSubtree(aRoot->ContentChildAt(idx));
 
   if (aRoot->IsPrimaryForNode() &&
       mNodeToAccessibleMap.Get(aRoot->GetNode()) == aRoot)
     mNodeToAccessibleMap.Remove(aRoot->GetNode());
 }
 
 void
 nsDocAccessible::ShutdownChildrenInSubtree(nsAccessible* aAccessible)
 {
   // Traverse through children and shutdown them before this accessible. When
   // child gets shutdown then it removes itself from children array of its
   //parent. Use jdx index to process the cases if child is not attached to the
   // parent and as result doesn't remove itself from its children.
-  PRUint32 count = aAccessible->GetCachedChildCount();
+  PRUint32 count = aAccessible->ContentChildCount();
   for (PRUint32 idx = 0, jdx = 0; idx < count; idx++) {
-    nsAccessible* child = aAccessible->GetCachedChildAt(jdx);
+    nsAccessible* child = aAccessible->ContentChildAt(jdx);
     if (!child->IsBoundToParent()) {
       NS_ERROR("Parent refers to a child, child doesn't refer to parent!");
       jdx++;
     }
 
     ShutdownChildrenInSubtree(child);
   }
 
--- a/accessible/src/xul/nsXULTreeAccessible.cpp
+++ b/accessible/src/xul/nsXULTreeAccessible.cpp
@@ -966,17 +966,17 @@ nsXULTreeItemAccessibleBase::NativeState
     state |= states::INVISIBLE;
 
   return state;
 }
 
 PRInt32
 nsXULTreeItemAccessibleBase::GetIndexInParent() const
 {
-  return mParent ? mParent->GetCachedChildCount() + mRow : -1;
+  return mParent ? mParent->ContentChildCount() + mRow : -1;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULTreeItemAccessibleBase: nsAccessible protected methods
 
 void
 nsXULTreeItemAccessibleBase::DispatchClickEvent(nsIContent *aContent,
                                                 PRUint32 aActionIndex)
@@ -1003,25 +1003,18 @@ nsXULTreeItemAccessibleBase::DispatchCli
   }
 
   if (column)
     nsCoreUtils::DispatchClickEvent(mTree, mRow, column, pseudoElm);
 }
 
 nsAccessible*
 nsXULTreeItemAccessibleBase::GetSiblingAtOffset(PRInt32 aOffset,
-                                                nsresult* aError)
+                                                nsresult* aError) const
 {
-  if (IsDefunct()) {
-    if (aError)
-      *aError = NS_ERROR_FAILURE;
-
-    return nsnull;
-  }
-
   if (aError)
     *aError = NS_OK; // fail peacefully
 
   return mParent->GetChildAt(GetIndexInParent() + aOffset);
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULTreeItemAccessibleBase: protected implementation
@@ -1167,40 +1160,33 @@ nsXULTreeItemAccessible::CacheChildren()
 nsXULTreeColumnsAccessible::
   nsXULTreeColumnsAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsXULColumnsAccessible(aContent, aShell)
 {
 }
 
 nsAccessible*
 nsXULTreeColumnsAccessible::GetSiblingAtOffset(PRInt32 aOffset,
-                                               nsresult* aError)
+                                               nsresult* aError) const
 {
   if (aOffset < 0)
     return nsXULColumnsAccessible::GetSiblingAtOffset(aOffset, aError);
 
-  if (IsDefunct()) {
-    if (aError)
-      *aError = NS_ERROR_FAILURE;
-
-    return nsnull;
-  }
-
   if (aError)
-    *aError = NS_OK; // fail peacefully
+    *aError =  NS_OK; // fail peacefully
 
   nsCOMPtr<nsITreeBoxObject> tree = nsCoreUtils::GetTreeBoxObject(mContent);
   if (tree) {
     nsCOMPtr<nsITreeView> treeView;
     tree->GetView(getter_AddRefs(treeView));
     if (treeView) {
       PRInt32 rowCount = 0;
       treeView->GetRowCount(&rowCount);
       if (rowCount > 0 && aOffset <= rowCount) {
-        nsRefPtr<nsXULTreeAccessible> treeAcc = do_QueryObject(mParent);
+        nsRefPtr<nsXULTreeAccessible> treeAcc = do_QueryObject(GetParent());
 
         if (treeAcc)
           return treeAcc->GetTreeItemAccessible(aOffset - 1);
       }
     }
   }
 
   return nsnull;
--- a/accessible/src/xul/nsXULTreeAccessible.h
+++ b/accessible/src/xul/nsXULTreeAccessible.h
@@ -230,17 +230,17 @@ public:
   virtual void RowInvalidated(PRInt32 aStartColIdx, PRInt32 aEndColIdx) = 0;
 
 protected:
   enum { eAction_Click = 0, eAction_Expand = 1 };
 
   // nsAccessible
   virtual void DispatchClickEvent(nsIContent *aContent, PRUint32 aActionIndex);
   virtual nsAccessible* GetSiblingAtOffset(PRInt32 aOffset,
-                                           nsresult *aError = nsnull);
+                                           nsresult *aError = nsnull) const;
 
   // nsXULTreeItemAccessibleBase
 
   /**
    * Return true if the tree item accessible is expandable (contains subrows).
    */
   PRBool IsExpandable();
 
@@ -294,12 +294,12 @@ class nsXULTreeColumnsAccessible : publi
 {
 public:
   nsXULTreeColumnsAccessible(nsIContent *aContent, nsIWeakReference *aShell);
 
 protected:
 
   // nsAccessible
   virtual nsAccessible* GetSiblingAtOffset(PRInt32 aOffset,
-                                           nsresult *aError = nsnull);
+                                           nsresult *aError = nsnull) const;
 };
 
 #endif
--- a/accessible/src/xul/nsXULTreeGridAccessible.cpp
+++ b/accessible/src/xul/nsXULTreeGridAccessible.cpp
@@ -1239,27 +1239,20 @@ nsXULTreeGridCellAccessible::CellInvalid
   }
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULTreeGridCellAccessible: nsAccessible protected implementation
 
 nsAccessible*
 nsXULTreeGridCellAccessible::GetSiblingAtOffset(PRInt32 aOffset,
-                                                nsresult* aError)
+                                                nsresult* aError) const
 {
-  if (IsDefunct()) {
-    if (aError)
-      *aError = NS_ERROR_FAILURE;
-
-    return nsnull;
-  }
-
   if (aError)
-    *aError = NS_OK; // fail peacefully
+    *aError =  NS_OK; // fail peacefully
 
   nsCOMPtr<nsITreeColumn> columnAtOffset(mColumn), column;
   if (aOffset < 0) {
     for (PRInt32 index = aOffset; index < 0 && columnAtOffset; index++) {
       column = nsCoreUtils::GetPreviousSensibleColumn(columnAtOffset);
       column.swap(columnAtOffset);
     }
   } else {
@@ -1267,18 +1260,17 @@ nsXULTreeGridCellAccessible::GetSiblingA
       column = nsCoreUtils::GetNextSensibleColumn(columnAtOffset);
       column.swap(columnAtOffset);
     }
   }
 
   if (!columnAtOffset)
     return nsnull;
 
-  nsRefPtr<nsXULTreeItemAccessibleBase> rowAcc = do_QueryObject(mParent);
-
+  nsRefPtr<nsXULTreeItemAccessibleBase> rowAcc = do_QueryObject(GetParent());
   return rowAcc->GetCellAccessible(columnAtOffset);
 }
 
 void
 nsXULTreeGridCellAccessible::DispatchClickEvent(nsIContent *aContent,
                                                 PRUint32 aActionIndex)
 {
   if (IsDefunct())
--- a/accessible/src/xul/nsXULTreeGridAccessible.h
+++ b/accessible/src/xul/nsXULTreeGridAccessible.h
@@ -177,17 +177,17 @@ public:
    * Fire name or state change event if the accessible text or value has been
    * changed.
    */
   void CellInvalidated();
 
 protected:
   // nsAccessible
   virtual nsAccessible* GetSiblingAtOffset(PRInt32 aOffset,
-                                           nsresult *aError = nsnull);
+                                           nsresult *aError = nsnull) const;
   virtual void DispatchClickEvent(nsIContent *aContent, PRUint32 aActionIndex);
 
   // nsXULTreeGridCellAccessible
 
   /**
    * Return true if value of cell can be modified.
    */
   PRBool IsEditable() const;
--- a/browser/base/content/aboutDialog.css
+++ b/browser/base/content/aboutDialog.css
@@ -67,38 +67,8 @@
   margin: 0 40px;
 }
 
 #currentChannel {
   margin: 0;
   padding: 0;
   font-weight: bold;
 }
-
-#channelSelector {
-  margin-top: 10px;
-}
-
-#channelSelectorStart {
-  -moz-margin-start: 0;
-}
-
-#channelMenulist {
-  margin: 0;
-}
-
-.channel-description {
-  margin: 10px 0;
-}
-
-#detailsBox,
-#channelSelector,
-.channel-description {
-  -moz-transition: opacity 250ms;
-}
-
-#contentDeck:not([selectedIndex="0"]) > #detailsBox,
-#contentDeck:not([selectedIndex="1"]) > #channelSelector,
-#channelDescriptionDeck:not([selectedIndex="0"]) > #releaseDescription,
-#channelDescriptionDeck:not([selectedIndex="1"]) > #betaDescription,
-#channelDescriptionDeck:not([selectedIndex="2"]) > #auroraDescription {
-  opacity: 0;
-}
--- a/browser/base/content/aboutDialog.js
+++ b/browser/base/content/aboutDialog.js
@@ -83,17 +83,19 @@ function init(aEvent)
     document.getElementById("extra-trademark").hidden = true;
   }
 #endif
 
 #ifdef MOZ_UPDATER
   gAppUpdater = new appUpdater();
 #endif
 
-  gChannelSelector.init();
+  let defaults = Services.prefs.getDefaultBranch("");
+  let channelLabel = document.getElementById("currentChannel");
+  channelLabel.value = defaults.getCharPref("app.update.channel");
 
 #ifdef XP_MACOSX
   // it may not be sized at this point, and we need its width to calculate its position
   window.sizeToContent();
   window.moveTo((screen.availWidth / 2) - (window.outerWidth / 2), screen.availHeight / 5);
 #endif
 }
 
@@ -568,77 +570,8 @@ appUpdater.prototype =
     if (!aIID.equals(Components.interfaces.nsIProgressEventSink) &&
         !aIID.equals(Components.interfaces.nsIRequestObserver) &&
         !aIID.equals(Components.interfaces.nsISupports))
       throw Components.results.NS_ERROR_NO_INTERFACE;
     return this;
   }
 };
 #endif
-
-var gChannelSelector = {
-  validChannels: { release: 1, beta: 1, aurora: 1 },
-  
-  init: function() {
-    try {
-      this.channelValue = Services.prefs.getCharPref("app.update.desiredChannel");
-    } catch (e) {
-      let defaults = Services.prefs.getDefaultBranch("");
-      this.channelValue = defaults.getCharPref("app.update.channel");
-    }
-
-    // Only show channel selector UI on valid update channels.
-    if (this.channelValue in this.validChannels) {
-      document.getElementById("currentChannelText").hidden = false;
-      this.setChannelLabel(this.channelValue);
-      this.setChannelMenuitem(this.channelValue);
-    }
-  },
-
-  selectChannel: function(aSelectedItem) {
-    document.getElementById("channelDescriptionDeck").selectedPanel =
-      document.getElementById(aSelectedItem.value + "Description");
-    document.getElementById("channelMenulist").setAttribute("aria-describedby",
-      aSelectedItem.value + "Description");
-  },
-
-  cancel: function() {
-    this.setChannelMenuitem(this.channelValue);
-    this.hide();
-  },
-
-  apply: function() {
-    this.channelValue = document.getElementById("channelMenulist").selectedItem.value;
-    this.setChannelLabel(this.channelValue);
-
-    // Change app update channel.
-    Services.prefs.setCharPref("app.update.desiredChannel", this.channelValue);
-
-    // Stop any downloads in progress
-    gAppUpdater.aus.pauseDownload();
-    // App updater will look at app.update.desiredChannel for new channel value
-    // and will clear it when the update is complete.
-    gAppUpdater.isChecking = true;
-    gAppUpdater.checker.checkForUpdates(gAppUpdater.updateCheckListener, true);
-
-    this.hide();
-  },
-
-  show: function() {
-    document.getElementById("contentDeck").selectedPanel =
-      document.getElementById("channelSelector");
-  },
-
-  hide: function() {
-    document.getElementById("contentDeck").selectedPanel =
-      document.getElementById("detailsBox");  
-  },
-
-  setChannelLabel: function(aValue) {
-    let channelLabel = document.getElementById("currentChannel");
-    channelLabel.value = document.getElementById(aValue + "Menuitem").label;
-  },
-
-  setChannelMenuitem: function(aValue) {
-    document.getElementById("channelMenulist").selectedItem =
-      document.getElementById(aValue + "Menuitem");
-  }
-}
--- a/browser/base/content/aboutDialog.xul
+++ b/browser/base/content/aboutDialog.xul
@@ -75,95 +75,60 @@
   <vbox id="aboutDialogContainer">
     <hbox id="clientBox">
       <vbox id="leftBox" flex="1"/>
       <vbox id="rightBox" flex="1">
 #expand <label id="version" value="__MOZ_APP_VERSION__"/>
         <label id="distribution" class="text-blurb"/>
         <label id="distributionId" class="text-blurb"/>
 
-        <!-- Make sure the selectedIndex attribute is always set so that the CSS
-             selectors for transitions work -->        
-        <deck id="contentDeck" selectedIndex="0">
-          <vbox id="detailsBox" aria-describedby="communityDesc contributeDesc">
-            <vbox id="updateBox">
+        <vbox id="detailsBox" aria-describedby="communityDesc contributeDesc">
+          <vbox id="updateBox">
 #ifdef MOZ_UPDATER
-              <deck id="updateDeck" orient="vertical">
-                <hbox id="updateButtonBox" align="center">
-                  <button id="updateButton" align="start"
-                          oncommand="gAppUpdater.buttonOnCommand();"/>
-                  <spacer flex="1"/>
-                </hbox>
-                <hbox id="checkingForUpdates" align="center">
-                  <image class="update-throbber"/><label>&update.checkingForUpdates;</label>
-                </hbox>
-                <hbox id="checkingAddonCompat" align="center">
-                  <image class="update-throbber"/><label>&update.checkingAddonCompat;</label>
-                </hbox>
-                <hbox id="downloading" align="center">
-                  <image class="update-throbber"/><label>&update.downloading.start;</label><label id="downloadStatus"/><label>&update.downloading.end;</label>
-                </hbox>
-                <hbox id="downloadFailed" align="center">
-                  <label>&update.failed.start;</label><label id="failedLink" class="text-link">&update.failed.linkText;</label><label>&update.failed.end;</label>
-                </hbox>
-                <hbox id="adminDisabled" align="center">
-                  <label>&update.adminDisabled;</label>
-                </hbox>
-                <hbox id="noUpdatesFound" align="center">
-                  <label>&update.noUpdatesFound;</label>
-                </hbox>
-                <hbox id="manualUpdate" align="center">
-                  <label>&update.manual.start;</label><label id="manualLink" class="text-link"/><label>&update.manual.end;</label>
-                </hbox>
-              </deck>
+            <deck id="updateDeck" orient="vertical">
+              <hbox id="updateButtonBox" align="center">
+                <button id="updateButton" align="start"
+                        oncommand="gAppUpdater.buttonOnCommand();"/>
+                <spacer flex="1"/>
+              </hbox>
+              <hbox id="checkingForUpdates" align="center">
+                <image class="update-throbber"/><label>&update.checkingForUpdates;</label>
+              </hbox>
+              <hbox id="checkingAddonCompat" align="center">
+                <image class="update-throbber"/><label>&update.checkingAddonCompat;</label>
+              </hbox>
+              <hbox id="downloading" align="center">
+                <image class="update-throbber"/><label>&update.downloading.start;</label><label id="downloadStatus"/><label>&update.downloading.end;</label>
+              </hbox>
+              <hbox id="downloadFailed" align="center">
+                <label>&update.failed.start;</label><label id="failedLink" class="text-link">&update.failed.linkText;</label><label>&update.failed.end;</label>
+              </hbox>
+              <hbox id="adminDisabled" align="center">
+                <label>&update.adminDisabled;</label>
+              </hbox>
+              <hbox id="noUpdatesFound" align="center">
+                <label>&update.noUpdatesFound;</label>
+              </hbox>
+              <hbox id="manualUpdate" align="center">
+                <label>&update.manual.start;</label><label id="manualLink" class="text-link"/><label>&update.manual.end;</label>
+              </hbox>
+            </deck>
 #endif
-            </vbox>
-
-            <description class="text-blurb" id="currentChannelText" hidden="true">
-              &channel.description.start;<label id="currentChannel"/>&channel.description.end;<label id="channelChangeLink" class="text-link" onclick="gChannelSelector.show();">&channel.change;</label>
-            </description>
-            <description class="text-blurb" id="communityDesc">
-              &community.start2;<label class="text-link" href="http://www.mozilla.org/">&community.mozillaLink;</label>&community.middle2;<label class="text-link" href="about:credits">&community.creditsLink;</label>&community.end2;
-            </description>
-            <description class="text-blurb" id="contributeDesc">
-              &contribute.start;<label class="text-link" href="http://www.mozilla.org/contribute/">&contribute.getInvolvedLink;</label>&contribute.end;
-            </description>
           </vbox>
 
-          <vbox id="channelSelector">
-            <hbox pack="start" align="center">
-              <label id="channelSelectorStart">&channel.selector.start;</label>
-              <menulist id="channelMenulist" onselect="gChannelSelector.selectChannel(this.selectedItem);" aria-labelledby="channelSelectorStart channelMenulist channelSelectorEnd">
-                <menupopup>
-                  <menuitem id="releaseMenuitem" label="Release" value="release"/>
-                  <menuitem id="betaMenuitem" label="Beta" value="beta"/>
-                  <menuseparator/>
-                  <menuitem id="auroraMenuitem" label="Aurora" value="aurora"/>
-                </menupopup>
-              </menulist>
-              <label id="channelSelectorEnd">&channel.selector.end;</label>
-            </hbox>
-
-            <deck id="channelDescriptionDeck" selectedIndex="0">
-              <description id="releaseDescription" class="channel-description">&channel.release.description;</description>
-              <description id="betaDescription" class="channel-description">&channel.beta.description;</description>
-              <description id="auroraDescription" class="channel-description">&channel.aurora.description;</description>
-            </deck>
-
-            <hbox id="channelSelectorButtons" pack="end">
-#ifdef XP_UNIX
-              <button oncommand="gChannelSelector.cancel();" label="&channel.selector.cancelButton;"/>
-              <button oncommand="gChannelSelector.apply();" label="&channel.selector.applyButton;"/>
-#else
-              <button oncommand="gChannelSelector.apply();" label="&channel.selector.applyButton;"/>
-              <button oncommand="gChannelSelector.cancel();" label="&channel.selector.cancelButton;"/>
-#endif
-            </hbox>
-          </vbox>
-        </deck>
+          <description class="text-blurb" id="currentChannelText">
+            &channel.description.start;<label id="currentChannel"/>&channel.description.end;
+          </description>
+          <description class="text-blurb" id="communityDesc">
+            &community.start2;<label class="text-link" href="http://www.mozilla.org/">&community.mozillaLink;</label>&community.middle2;<label class="text-link" href="about:credits">&community.creditsLink;</label>&community.end2;
+          </description>
+          <description class="text-blurb" id="contributeDesc">
+            &contribute.start;<label class="text-link" href="http://www.mozilla.org/contribute/">&contribute.getInvolvedLink;</label>&contribute.end;
+          </description>
+        </vbox>
       </vbox>
     </hbox>
     <vbox id="bottomBox">
       <hbox pack="center">
         <label class="text-link bottom-link" href="about:license">&bottomLinks.license;</label>
         <label class="text-link bottom-link" href="about:rights">&bottomLinks.rights;</label>
         <label class="text-link bottom-link" href="http://www.mozilla.com/legal/privacy/">&bottomLinks.privacy;</label>
       </hbox>
--- a/browser/base/content/browser-sets.inc
+++ b/browser/base/content/browser-sets.inc
@@ -186,17 +186,17 @@
                  accesskey="&dontShowMessage.accesskey;"
                  type="checkbox"
                  oncommand="gPopupBlockerObserver.dontShowMessage();"/>
     <broadcaster id="blockedPopupsSeparator"/>
     <broadcaster id="isImage"/>
     <broadcaster id="isFrameImage"/>
     <broadcaster id="singleFeedMenuitemState" disabled="true"/>
     <broadcaster id="multipleFeedsMenuState" hidden="true"/>
-    <broadcaster id="tabviewGroupsNumber" groups="0"/>
+    <broadcaster id="tabviewGroupsNumber" groups="1"/>
 #ifdef MOZ_SERVICES_SYNC
     <broadcaster id="sync-setup-state"/>
     <broadcaster id="sync-syncnow-state"/>
 #endif
     <broadcaster id="workOfflineMenuitemState"/>
   </broadcasterset>
 
   <keyset id="mainKeyset">
--- a/browser/base/content/browser-tabview.js
+++ b/browser/base/content/browser-tabview.js
@@ -100,17 +100,17 @@ let TabView = {
       let data = sessionstore.getWindowValue(window, this.VISIBILITY_IDENTIFIER);
       if (data && data == "true") {
         this.show();
       } else {
         try {
           data = sessionstore.getWindowValue(window, this.GROUPS_IDENTIFIER);
           if (data) {
             let parsedData = JSON.parse(data);
-            this.updateGroupNumberBroadcaster(parsedData.totalNumber || 0);
+            this.updateGroupNumberBroadcaster(parsedData.totalNumber || 1);
           }
         } catch (e) { }
 
         let self = this;
         // if a tab is changed from hidden to unhidden and the iframe is not
         // initialized, load the iframe and setup the tab.
         this._tabShowEventListener = function (event) {
           if (!self._window)
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -2252,17 +2252,21 @@ function loadURI(uri, referrer, postData
     if (allowThirdPartyFixup) {
       flags = nsIWebNavigation.LOAD_FLAGS_ALLOW_THIRD_PARTY_FIXUP;
     }
     gBrowser.loadURIWithFlags(uri, flags, referrer, null, postData);
   } catch (e) {
   }
 }
 
-function getShortcutOrURI(aURL, aPostDataRef) {
+function getShortcutOrURI(aURL, aPostDataRef, aMayInheritPrincipal) {
+  // Initialize outparam to false
+  if (aMayInheritPrincipal)
+    aMayInheritPrincipal.value = false;
+
   var shortcutURL = null;
   var keyword = aURL;
   var param = "";
 
   var offset = aURL.indexOf(" ");
   if (offset > 0) {
     keyword = aURL.substr(0, offset);
     param = aURL.substr(offset + 1);
@@ -2324,16 +2328,21 @@ function getShortcutOrURI(aURL, aPostDat
   else if (param) {
     // This keyword doesn't take a parameter, but one was provided. Just return
     // the original URL.
     aPostDataRef.value = null;
 
     return aURL;
   }
 
+  // This URL came from a bookmark, so it's safe to let it inherit the current
+  // document's principal.
+  if (aMayInheritPrincipal)
+    aMayInheritPrincipal.value = true;
+
   return shortcutURL;
 }
 
 function getPostDataStream(aStringData, aKeyword, aEncKeyword, aType) {
   var dataStream = Cc["@mozilla.org/io/string-input-stream;1"].
                    createInstance(Ci.nsIStringInputStream);
   aStringData = aStringData.replace(/%s/g, aEncKeyword).replace(/%S/g, aKeyword);
   dataStream.data = aStringData;
@@ -2868,17 +2877,17 @@ var PrintPreviewListener = {
     gBrowser.selectedTab = this._tabBeforePrintPreview;
     this._tabBeforePrintPreview = null;
     gInPrintPreviewMode = false;
     this._toggleAffectedChrome();
     gBrowser.removeTab(this._printPreviewTab);
     this._printPreviewTab = null;
   },
   _toggleAffectedChrome: function () {
-    gNavToolbox.hidden = gInPrintPreviewMode;
+    gNavToolbox.collapsed = gInPrintPreviewMode;
 
     if (gInPrintPreviewMode)
       this._hideChrome();
     else
       this._showChrome();
 
     if (this._chromeState.sidebarOpen)
       toggleSidebar(this._sidebarCommand);
--- a/browser/base/content/tabbrowser.xml
+++ b/browser/base/content/tabbrowser.xml
@@ -1329,19 +1329,19 @@
 
               let flags = Ci.nsIWebNavigation.LOAD_FLAGS_NONE;
               if (aAllowThirdPartyFixup)
                 flags |= Ci.nsIWebNavigation.LOAD_FLAGS_ALLOW_THIRD_PARTY_FIXUP;
               if (aFromExternal)
                 flags |= Ci.nsIWebNavigation.LOAD_FLAGS_FROM_EXTERNAL;
               try {
                 b.loadURIWithFlags(aURI, flags, aReferrerURI, aCharset, aPostData);
-
+              } catch (ex) {
+                Cu.reportError(ex);
               }
-              catch (ex) { }
             }
 
             // We start our browsers out as inactive, and then maintain
             // activeness in the tab switcher.
             b.docShell.isActive = false;
 
             // Check if we're opening a tab related to the current tab and
             // move it to after the current tab.
--- a/browser/base/content/tabview/iq.js
+++ b/browser/base/content/tabview/iq.js
@@ -603,17 +603,17 @@ iQClass.prototype = {
       let cStyle = window.getComputedStyle(elem, null);
       for (let prop in css) {
         prop = prop.replace(rupper, "-$1").toLowerCase();
         iQ(elem).css(prop, cStyle.getPropertyValue(prop));
       }
     });
 
     this.css({
-      '-moz-transition-property': 'all', // TODO: just animate the properties we're changing
+      '-moz-transition-property': Object.keys(css).join(", "),
       '-moz-transition-duration': (duration / 1000) + 's',
       '-moz-transition-timing-function': easing
     });
 
     this.css(css);
 
     let self = this;
     setTimeout(function() {
--- a/browser/base/content/tabview/search.js
+++ b/browser/base/content/tabview/search.js
@@ -205,17 +205,17 @@ TabMatcher.prototype = {
   
   // ---------
   // Function: _filterForUnmatches
   // Given an array of <TabItem>s returns an unsorted array of tabs whose name
   // does not match the the search term.
   _filterForUnmatches: function TabMatcher__filterForUnmatches(tabs) {
     var self = this;
     return tabs.filter(function(tab) {
-      var name = tab.$tabTitle[0].innerHTML;
+      let name = tab.$tabTitle[0].textContent;
       let url = TabUtils.URLOf(tab);
       return !name.match(self.term, "i") && !url.match(self.term, "i");
     });
   },
   
   // ---------
   // Function: _getTabsForOtherWindows
   // Returns an array of <TabItem>s and <xul:tabs>s representing tabs
@@ -225,27 +225,18 @@ TabMatcher.prototype = {
   // been activated.
   _getTabsForOtherWindows: function TabMatcher__getTabsForOtherWindows() {
     var enumerator = Services.wm.getEnumerator("navigator:browser");
     var allTabs = [];
 
     while (enumerator.hasMoreElements()) {
       var win = enumerator.getNext();
       // This function gets tabs from other windows, not from the current window
-      if (win != gWindow) {
-        // If TabView is around iterate over all tabs, else get the currently
-        // shown tabs...
-        let tvWindow = win.TabView.getContentWindow();
-        if (tvWindow)
-          allTabs = allTabs.concat(tvWindow.TabItems.getItems());
-        else
-          // win.gBrowser.tabs isn't a proper array, so we can't use concat
-          for (let i = 0; i < win.gBrowser.tabs.length; i++)
-            allTabs.push(win.gBrowser.tabs[i]);
-      }
+      if (win != gWindow)
+        allTabs.push.apply(allTabs, win.gBrowser.tabs);
     }
     return allTabs;
   },
   
   // ----------
   // Function: matchedTabsFromOtherWindows
   // Returns an array of <TabItem>s and <xul:tab>s that match the search term
   // from all windows but the current window. <TabItem>s will be returned for
--- a/browser/base/content/tabview/ui.js
+++ b/browser/base/content/tabview/ui.js
@@ -994,17 +994,17 @@ let UI = {
 
     [
 #ifdef XP_UNIX
       "quitApplication",
 #else
       "redo",
 #endif
 #ifdef XP_MACOSX
-      "preferencesCmdMac", "minimizeWindow",
+      "preferencesCmdMac", "minimizeWindow", "hideThisAppCmdMac",
 #endif
       "newNavigator", "newNavigatorTab", "undo", "cut", "copy", "paste", 
       "selectAll", "find"
     ].forEach(function(key) {
       let element = gWindow.document.getElementById("key_" + key);
       keys[key] = element.getAttribute("key").toLocaleLowerCase().charCodeAt(0);
     });
 
@@ -1038,16 +1038,20 @@ let UI = {
         Keys.meta = false;
     });
 
     iQ(window).keypress(function(event) {
       if (event.metaKey)
         Keys.meta = true;
 
       function processBrowserKeys(evt) {
+        // let any keys with alt to pass through
+        if (evt.altKey)
+          return;
+
 #ifdef XP_MACOSX
         if (evt.metaKey) {
 #else
         if (evt.ctrlKey) {
 #endif
           let preventDefault = true;
           if (evt.shiftKey) {
             switch (evt.charCode) {
@@ -1072,16 +1076,17 @@ let UI = {
 #ifdef XP_UNIX
               case self._browserKeys.quitApplication:
 #else
               case self._browserKeys.redo:
 #endif
 #ifdef XP_MACOSX
               case self._browserKeys.preferencesCmdMac:
               case self._browserKeys.minimizeWindow:
+              case self._browserKeys.hideThisAppCmdMac:
 #endif
               case self._browserKeys.newNavigator:
               case self._browserKeys.newNavigatorTab:
               case self._browserKeys.undo:
               case self._browserKeys.cut:
               case self._browserKeys.copy:
               case self._browserKeys.paste:
               case self._browserKeys.selectAll:
--- a/browser/base/content/test/Makefile.in
+++ b/browser/base/content/test/Makefile.in
@@ -168,16 +168,17 @@ endif
                  browser_bug599325.js \
                  browser_bug609700.js \
                  browser_bug616836.js \
                  browser_bug623893.js \
                  browser_bug624734.js \
                  browser_bug647886.js \
                  browser_bug655584.js \
                  browser_findbarClose.js \
+                 browser_keywordBookmarklets.js \
                  browser_contextSearchTabPosition.js \
                  browser_ctrlTab.js \
                  browser_customize_popupNotification.js \
                  browser_disablechrome.js \
                  browser_discovery.js \
                  browser_duplicateIDs.js \
                  browser_gestureSupport.js \
                  browser_getshortcutoruri.js \
--- a/browser/base/content/test/browser_bug380960.js
+++ b/browser/base/content/test/browser_bug380960.js
@@ -56,16 +56,17 @@ function preperForNextText() {
     nextAsyncText(tab);
   });
 }
 
 function nextAsyncText(tab) {
   var gotCloseEvent = false;
 
   tab.addEventListener("TabClose", function () {
+    tab.removeEventListener("TabClose", arguments.callee, false);
     info("got TabClose event");
     gotCloseEvent = true;
 
     const DEFAULT_ANIMATION_LENGTH = 250;
     const MAX_WAIT_TIME = DEFAULT_ANIMATION_LENGTH * 7;
     var polls = Math.ceil(MAX_WAIT_TIME / DEFAULT_ANIMATION_LENGTH);
     var pollTabRemoved = setInterval(function () {
       --polls;
--- a/browser/base/content/test/browser_bug477014.js
+++ b/browser/base/content/test/browser_bug477014.js
@@ -47,35 +47,33 @@ function test() {
 
   function onPageShow(event) {
     // we get here if the test is executed before the pageshow
     // event for the window's first tab
     if (!tabToDetach ||
         tabToDetach.linkedBrowser.contentDocument != event.target)
       return;
 
+    event.currentTarget.removeEventListener("pageshow", onPageShow, false);
+
     if (!newWindow) {
-      gBrowser.removeEventListener("pageshow", onPageShow, false);
-
       // prepare the tab (set icon and busy state)
       // we have to set these only after onState* notification, otherwise
       // they're overriden
       setTimeout(function() {
         gBrowser.setIcon(tabToDetach, iconURLSpec);
         tabToDetach.setAttribute("busy", "true");
 
         // detach and set the listener on the new window
         newWindow = gBrowser.replaceTabWithWindow(tabToDetach);
         // wait for gBrowser to come along
-        function onLoad(event) {
-          newWindow.gBrowser
-                   .addEventListener("pageshow", onPageShow, false);
+        newWindow.addEventListener("load", function () {
           newWindow.removeEventListener("load", arguments.callee, false);
-        }
-        newWindow.addEventListener("load", onLoad, false);
+          newWindow.gBrowser.addEventListener("pageshow", onPageShow, false);
+        }, false);
       }, 0);
       return;
     }
 
     is(newWindow.gBrowser.selectedTab.hasAttribute("busy"), true);
     is(newWindow.gBrowser.getIcon(), iconURLSpec);
     newWindow.close();
     finish();
--- a/browser/base/content/test/browser_bug481560.js
+++ b/browser/base/content/test/browser_bug481560.js
@@ -4,20 +4,24 @@ function test() {
   var win = openDialog(getBrowserURL(), "_blank", "chrome,all,dialog=no");
 
   win.addEventListener("load", function () {
     win.removeEventListener("load", arguments.callee, false);
 
     win.content.addEventListener("focus", function () {
       win.content.removeEventListener("focus", arguments.callee, false);
 
-      win.gBrowser.selectedTab.addEventListener("TabClose", function () {
+      function onTabClose() {
         ok(false, "shouldn't have gotten the TabClose event for the last tab");
-      }, false);
+      }
+      var tab = win.gBrowser.selectedTab;
+      tab.addEventListener("TabClose", onTabClose, false);
 
       EventUtils.synthesizeKey("w", { accelKey: true }, win);
 
       ok(win.closed, "accel+w closed the window immediately");
 
+      tab.removeEventListener("TabClose", onTabClose, false);
+
       finish();
     }, false);
   }, false);
 }
--- a/browser/base/content/test/browser_bug517902.js
+++ b/browser/base/content/test/browser_bug517902.js
@@ -8,16 +8,17 @@ function test() {
   gBrowser.selectedBrowser.addEventListener("load", function () {
     gBrowser.selectedBrowser.removeEventListener("load", arguments.callee, true);
 
     var doc = gBrowser.contentDocument;
     var testImg = doc.getElementById("test-image");
     var pageInfo = BrowserPageInfo(doc, "mediaTab", testImg);
 
     pageInfo.addEventListener("load", function () {
+      pageInfo.removeEventListener("load", arguments.callee, true);
       pageInfo.onFinished.push(function () {
         executeSoon(function () {
           var pageInfoImg = pageInfo.document.getElementById("thepreviewimage");
 
           is(pageInfoImg.src, testImg.src, "selected image has the correct source");
           is(pageInfoImg.width, testImg.width, "selected image has the correct width");
           is(pageInfoImg.height, testImg.height, "selected image has the correct height");
 
--- a/browser/base/content/test/browser_bug550565.js
+++ b/browser/base/content/test/browser_bug550565.js
@@ -1,16 +1,18 @@
 function test() {
   waitForExplicitFinish();
 
   let testPath = getRootDirectory(gTestPath);
 
   let tab = gBrowser.addTab(testPath + "file_bug550565_popup.html");
 
-  tab.linkedBrowser.addEventListener('DOMContentLoaded', function() {
+  tab.linkedBrowser.addEventListener("DOMContentLoaded", function() {
+    tab.linkedBrowser.removeEventListener("DOMContentLoaded", arguments.callee, true);
+
     let expectedIcon = testPath + "file_bug550565_favicon.ico";
 
     is(gBrowser.getIcon(tab), expectedIcon, "Correct icon before pushState.");
     tab.linkedBrowser.contentWindow.history.pushState("page2", "page2", "page2");
     is(gBrowser.getIcon(tab), expectedIcon, "Correct icon after pushState.");
 
     gBrowser.removeTab(tab);
 
--- a/browser/base/content/test/browser_bug562649.js
+++ b/browser/base/content/test/browser_bug562649.js
@@ -11,14 +11,17 @@ function test() {
 
   gBrowser.selectedTab = gBrowser.addTab();
   gBrowser.removeCurrentTab();
   is(gBrowser.userTypedValue, URI, "userTypedValue matches test URI after switching tabs");
   is(gURLBar.value, URI, "location bar value matches test URI after switching tabs");
 
   waitForExplicitFinish();
   gBrowser.selectedBrowser.addEventListener("load", function () {
+    gBrowser.selectedBrowser.removeEventListener("load", arguments.callee, true);
+
     is(gBrowser.userTypedValue, null, "userTypedValue is null as the page has loaded");
     is(gURLBar.value, URI, "location bar value matches test URI as the page has loaded");
+
     gBrowser.removeCurrentTab();
     finish();
   }, true);
 }
--- a/browser/base/content/test/browser_bug580956.js
+++ b/browser/base/content/test/browser_bug580956.js
@@ -15,13 +15,16 @@ function test() {
   gPrefService.setIntPref("browser.sessionstore.max_tabs_undo", 0);
   gPrefService.clearUserPref("browser.sessionstore.max_tabs_undo");
   is(numClosedTabs(), 0, "There should be 0 closed tabs.");
   ok(!isUndoCloseEnabled(), "Undo Close Tab should be disabled.");
 
   var tab = gBrowser.addTab("http://mochi.test:8888/");
   var browser = gBrowser.getBrowserForTab(tab);
   browser.addEventListener("load", function() {
+    browser.removeEventListener("load", arguments.callee, true);
+
     gBrowser.removeTab(tab);
     ok(isUndoCloseEnabled(), "Undo Close Tab should be enabled.");
+
     finish();
   }, true);
 }
--- a/browser/base/content/test/browser_bug581242.js
+++ b/browser/base/content/test/browser_bug581242.js
@@ -39,14 +39,15 @@ function test() {
   let blanktab = gBrowser.addTab();
   gBrowser.selectedTab = blanktab;
   BrowserOpenAddonsMgr();
 
   is(blanktab, gBrowser.selectedTab, "Current tab should be blank tab");
   // Verify that about:addons loads
   waitForExplicitFinish();
   gBrowser.selectedBrowser.addEventListener("load", function() {
+    gBrowser.selectedBrowser.removeEventListener("load", arguments.callee, true);
     let browser = blanktab.linkedBrowser;
     is(browser.currentURI.spec, "about:addons", "about:addons should load into blank tab.");
     gBrowser.removeTab(blanktab);
     finish();
   }, true);
 }
--- a/browser/base/content/test/browser_bug585785.js
+++ b/browser/base/content/test/browser_bug585785.js
@@ -22,15 +22,17 @@ function checkAnimationState() {
     ok(true, "tab removed synchronously since the opening animation hasn't moved yet");
     finish();
     return;
   }
 
   info("tab didn't close immediately, so the tab opening animation must have started moving");
   info("waiting for the tab to close asynchronously");
   tab.addEventListener("transitionend", function (event) {
-    if (event.propertyName == "max-width")
+    if (event.propertyName == "max-width") {
+      tab.removeEventListener("transitionend", arguments.callee, false);
       executeSoon(function () {
         ok(!tab.parentNode, "tab removed asynchronously");
         finish();
       });
+    }
   }, false);
 }
--- a/browser/base/content/test/browser_bug594131.js
+++ b/browser/base/content/test/browser_bug594131.js
@@ -38,16 +38,18 @@ function test() {
   let backgroundPref = "browser.tabs.loadBookmarksInBackground";
   let newTab = gBrowser.addTab("http://example.com");
   waitForExplicitFinish();
   newTab.linkedBrowser.addEventListener("load", mainPart, true);
   
   Services.prefs.setBoolPref(backgroundPref, true);
   
   function mainPart() {
+    newTab.linkedBrowser.removeEventListener("load", mainPart, true);
+
     gBrowser.pinTab(newTab);
     gBrowser.selectedTab = newTab;
     
     openUILinkIn("http://example.org/", "current");
     isnot(gBrowser.selectedTab, newTab, "shouldn't load in background");
     
     if (Services.prefs.prefHasUserValue(backgroundPref))
       Services.prefs.clearUserPref(backgroundPref);
--- a/browser/base/content/test/browser_bug596687.js
+++ b/browser/base/content/test/browser_bug596687.js
@@ -1,20 +1,26 @@
 function test() {
   var tab = gBrowser.addTab(null, {skipAnimation: true});
   gBrowser.selectedTab = tab;
 
   var gotTabAttrModified = false;
   var gotTabClose = false;
 
-  tab.addEventListener("TabClose", function () {
+  function onTabClose() {
     gotTabClose = true;
+    tab.addEventListener("TabAttrModified", onTabAttrModified, false);
+  }
 
-    tab.addEventListener("TabAttrModified", function () {
-      gotTabAttrModified = true;
-    }, false);
-  }, false);
+  function onTabAttrModified() {
+    gotTabAttrModified = true;
+  }
+
+  tab.addEventListener("TabClose", onTabClose, false);
 
   gBrowser.removeTab(tab);
 
   ok(gotTabClose, "should have got the TabClose event");
   ok(!gotTabAttrModified, "shouldn't have got the TabAttrModified event after TabClose");
+
+  tab.removeEventListener("TabClose", onTabClose, false);
+  tab.removeEventListener("TabAttrModified", onTabAttrModified, false);
 }
--- a/browser/base/content/test/browser_bug609700.js
+++ b/browser/base/content/test/browser_bug609700.js
@@ -3,16 +3,17 @@ function test() {
 
   Services.ww.registerNotification(function (aSubject, aTopic, aData) {
     if (aTopic == "domwindowopened") {
       Services.ww.unregisterNotification(arguments.callee);
 
       ok(true, "duplicateTabIn opened a new window");
 
       aSubject.addEventListener("load", function () {
+        aSubject.removeEventListener("load", arguments.callee, false);
         executeSoon(function () {
           aSubject.close();
           finish();
         });
       }, false);
     }
   });
 
--- a/browser/base/content/test/browser_customize_popupNotification.js
+++ b/browser/base/content/test/browser_customize_popupNotification.js
@@ -5,16 +5,18 @@ http://creativecommons.org/publicdomain/
 function test() {
   waitForExplicitFinish();
 
   var newWin = openDialog(location, "", "chrome,all,dialog=no", "about:blank");
   registerCleanupFunction(function () {
     newWin.close();
   });
   newWin.addEventListener("load", function test_win_onLoad() {
+    newWin.removeEventListener("load", test_win_onLoad, false);
+
     // Remove the URL bar
     newWin.gURLBar.parentNode.removeChild(newWin.gURLBar);
 
     waitForFocus(function () {
       let PN = newWin.PopupNotifications;
       try {
         let notification = PN.show(newWin.gBrowser.selectedBrowser, "some-notification", "Some message");
         ok(notification, "showed the notification");
--- a/browser/base/content/test/browser_getshortcutoruri.js
+++ b/browser/base/content/test/browser_getshortcutoruri.js
@@ -6,19 +6,20 @@ function getPostDataString(aIS) {
             createInstance(Ci.nsIScriptableInputStream);
   sis.init(aIS);
   var dataLines = sis.read(aIS.available()).split("\n");
 
   // only want the last line
   return dataLines[dataLines.length-1];
 }
 
-function keywordResult(aURL, aPostData) {
+function keywordResult(aURL, aPostData, aIsUnsafe) {
   this.url = aURL;
   this.postData = aPostData;
+  this.isUnsafe = aIsUnsafe;
 }
 
 function keyWordData() {}
 keyWordData.prototype = {
   init: function(aKeyWord, aURL, aPostData, aSearchWord) {
     this.keyword = aKeyWord;
     this.uri = makeURI(aURL);
     this.postData = aPostData;
@@ -47,64 +48,72 @@ var testData = [
 
   [new bmKeywordData("bmpostget", "http://bmpostget/search1=%s", "search2=%s", "foo3"),
    new keywordResult("http://bmpostget/search1=foo3", "search2=foo3")],
 
   [new bmKeywordData("bmget-nosearch", "http://bmget-nosearch/", null, ""),
    new keywordResult("http://bmget-nosearch/", null)],
 
   [new searchKeywordData("searchget", "http://searchget/?search={searchTerms}", null, "foo4"),
-   new keywordResult("http://searchget/?search=foo4", null)],
+   new keywordResult("http://searchget/?search=foo4", null, true)],
 
   [new searchKeywordData("searchpost", "http://searchpost/", "search={searchTerms}", "foo5"),
-   new keywordResult("http://searchpost/", "search=foo5")],
+   new keywordResult("http://searchpost/", "search=foo5", true)],
 
   [new searchKeywordData("searchpostget", "http://searchpostget/?search1={searchTerms}", "search2={searchTerms}", "foo6"),
-   new keywordResult("http://searchpostget/?search1=foo6", "search2=foo6")],
+   new keywordResult("http://searchpostget/?search1=foo6", "search2=foo6", true)],
 
   // Bookmark keywords that don't take parameters should not be activated if a
   // parameter is passed (bug 420328).
   [new bmKeywordData("bmget-noparam", "http://bmget-noparam/", null, "foo7"),
-   new keywordResult(null, null)],
+   new keywordResult(null, null, true)],
   [new bmKeywordData("bmpost-noparam", "http://bmpost-noparam/", "not_a=param", "foo8"),
-   new keywordResult(null, null)],
+   new keywordResult(null, null, true)],
 
   // Test escaping (%s = escaped, %S = raw)
   // UTF-8 default
   [new bmKeywordData("bmget-escaping", "http://bmget/?esc=%s&raw=%S", null, "foé"),
    new keywordResult("http://bmget/?esc=fo%C3%A9&raw=foé", null)],
   // Explicitly-defined ISO-8859-1
   [new bmKeywordData("bmget-escaping2", "http://bmget/?esc=%s&raw=%S&mozcharset=ISO-8859-1", null, "foé"),
    new keywordResult("http://bmget/?esc=fo%E9&raw=foé", null)],
 
   // Bug 359809: Test escaping +, /, and @
   // UTF-8 default
   [new bmKeywordData("bmget-escaping", "http://bmget/?esc=%s&raw=%S", null, "+/@"),
    new keywordResult("http://bmget/?esc=%2B%2F%40&raw=+/@", null)],
   // Explicitly-defined ISO-8859-1
   [new bmKeywordData("bmget-escaping2", "http://bmget/?esc=%s&raw=%S&mozcharset=ISO-8859-1", null, "+/@"),
    new keywordResult("http://bmget/?esc=%2B%2F%40&raw=+/@", null)],
+
+  // Test using a non-bmKeywordData object, to test the behavior of
+  // getShortcutOrURI for non-keywords (setupKeywords only adds keywords for
+  // bmKeywordData objects)
+  [{keyword: "http://gavinsharp.com"},
+   new keywordResult(null, null, true)]
 ];
 
 function test() {
   setupKeywords();
 
   for each (var item in testData) {
     var [data, result] = item;
 
     var postData = {};
     var query = data.keyword;
     if (data.searchWord)
       query += " " + data.searchWord;
-    var url = getShortcutOrURI(query, postData);
+    var mayInheritPrincipal = {};
+    var url = getShortcutOrURI(query, postData, mayInheritPrincipal);
 
     // null result.url means we should expect the same query we sent in
     var expected = result.url || query;
     is(url, expected, "got correct URL for " + data.keyword);
     is(getPostDataString(postData.value), result.postData, "got correct postData for " + data.keyword);
+    is(mayInheritPrincipal.value, !result.isUnsafe, "got correct mayInheritPrincipal for " + data.keyword);
   }
 
   cleanupKeywords();
 }
 
 var gBMFolder = null;
 var gAddedEngines = [];
 function setupKeywords() {
new file mode 100644
--- /dev/null
+++ b/browser/base/content/test/browser_keywordBookmarklets.js
@@ -0,0 +1,38 @@
+/* Any copyright is dedicated to the Public Domain.
+   http://creativecommons.org/publicdomain/zero/1.0/ */
+
+function test() {
+  waitForExplicitFinish();
+
+  let bmFolder = Application.bookmarks.menu.addFolder("keyword-test");
+  let tab = gBrowser.selectedTab = gBrowser.addTab();
+
+  registerCleanupFunction (function () {
+    bmFolder.remove();
+    gBrowser.removeTab(tab);
+  });
+
+  let bm = bmFolder.addBookmark("bookmarklet", makeURI("javascript:1;"));
+  bm.keyword = "bm";
+
+  addPageShowListener(function () {
+    let originalPrincipal = gBrowser.contentPrincipal;
+
+    // Enter bookmarklet keyword in the URL bar
+    gURLBar.value = "bm";
+    gURLBar.focus();
+    EventUtils.synthesizeKey("VK_RETURN", {});
+
+    addPageShowListener(function () {
+      ok(gBrowser.contentPrincipal.equals(originalPrincipal), "javascript bookmarklet should inherit principal");
+      finish();
+    });
+  });
+}
+
+function addPageShowListener(func) {
+  gBrowser.selectedBrowser.addEventListener("pageshow", function loadListener() {
+    gBrowser.selectedBrowser.removeEventListener("pageshow", loadListener, false);
+    func();
+  });
+}
--- a/browser/base/content/test/browser_page_style_menu.js
+++ b/browser/base/content/test/browser_page_style_menu.js
@@ -1,14 +1,17 @@
 function test() {
   waitForExplicitFinish();
 
   var tab = gBrowser.addTab();
   gBrowser.selectedTab = tab;
-  tab.linkedBrowser.addEventListener("load", checkPageStyleMenu, true);
+  tab.linkedBrowser.addEventListener("load", function () {
+    tab.linkedBrowser.removeEventListener("load", arguments.callee, true);
+    checkPageStyleMenu();
+  }, true);
   let rootDir = getRootDirectory(gTestPath);
   content.location = rootDir + "page_style_sample.html";
 }
 
 function checkPageStyleMenu() {
   var menupopup = document.getElementById("pageStyleMenu")
                           .getElementsByTagName("menupopup")[0];
   stylesheetFillPopup(menupopup);
--- a/browser/base/content/test/browser_tabfocus.js
+++ b/browser/base/content/test/browser_tabfocus.js
@@ -19,16 +19,19 @@ function test() {
 
   var loadCount = 0;
   function check()
   {
     // wait for both tabs to load
     if (++loadCount != 2)
       return;
 
+    browser1.removeEventListener("load", check, true);
+    browser2.removeEventListener("load", check, true);
+
     window.focus();
 
     _browser_tabfocus_test_lastfocus = gURLBar;
     _browser_tabfocus_test_lastfocuswindow = window;
 
     window.addEventListener("focus", _browser_tabfocus_test_eventOccured, true);
     window.addEventListener("blur", _browser_tabfocus_test_eventOccured, true);
 
@@ -134,18 +137,18 @@ function test() {
     EventUtils.synthesizeKey("VK_F6", { });
     is(fm.focusedWindow, window, "switch document forward again with f6");
 
     browser1.style.MozUserFocus = "ignore";
     browser1.clientWidth;
     EventUtils.synthesizeKey("VK_F6", { });
     is(fm.focusedWindow, window, "switch document forward again with f6 when browser non-focusable");
 
-    window.addEventListener("focus", _browser_tabfocus_test_eventOccured, true);
-    window.addEventListener("blur", _browser_tabfocus_test_eventOccured, true);
+    window.removeEventListener("focus", _browser_tabfocus_test_eventOccured, true);
+    window.removeEventListener("blur", _browser_tabfocus_test_eventOccured, true);
 
     // next, check whether navigating forward, focusing the urlbar and then
     // navigating back maintains the focus in the urlbar.
     browser1.addEventListener("pageshow", _browser_tabfocus_navigation_test_eventOccured, true);
     button1.focus();
     browser1.contentWindow.location = testPage3;
   }
 
@@ -181,16 +184,17 @@ function _browser_tabfocus_navigation_te
   if (event.target instanceof Document) {
     var contentwin = event.target.defaultView;
     if (contentwin.location.toString().indexOf("3") > 0) {
       // just moved forward, so focus the urlbar and go back
       gURLBar.focus();
       setTimeout(function () contentwin.history.back(), 0);
     }
     else if (contentwin.location.toString().indexOf("2") > 0) {
+      event.currentTarget.removeEventListener("pageshow", _browser_tabfocus_navigation_test_eventOccured, true);
       is(window.document.activeElement, gURLBar.inputField, "urlbar still focused after navigating back");
       gBrowser.removeCurrentTab();
       gBrowser.removeCurrentTab();
       finish();
     }
   }
 }
 
--- a/browser/base/content/test/browser_typeAheadFind.js
+++ b/browser/base/content/test/browser_typeAheadFind.js
@@ -37,16 +37,17 @@
 
 let testWindow = null;
 
 function test() {
   waitForExplicitFinish();
 
   testWindow = OpenBrowserWindow();
   testWindow.addEventListener("load", function() {
+    testWindow.removeEventListener("load", arguments.callee, false);
     ok(true, "Load listener called");
 
     executeSoon(function() {
       let selectedBrowser = testWindow.gBrowser.selectedBrowser;
       selectedBrowser.addEventListener("pageshow", function() {
         selectedBrowser.removeEventListener("pageshow", arguments.callee,
                                             false);
         ok(true, "pageshow listener called");
--- a/browser/base/content/test/browser_zbug569342.js
+++ b/browser/base/content/test/browser_zbug569342.js
@@ -13,51 +13,51 @@ function load(url, cb) {
     cb();
   }, true);
 }
 
 function test() {
   waitForExplicitFinish();
 
   ok(gFindBar.hidden, "Find bar should not be visible");
-
-  run_test_1();
+  nextTest();
 }
 
-function run_test_1() {
-  load("about:config", function() {
+let urls = [
+  "about:config",
+  "about:addons",
+  "about:permissions"
+];
+
+function nextTest() {
+  let url = urls.shift();
+  if (url) {
+    testFindDisabled(url, nextTest);
+  } else {
+    // Make sure the find bar is re-enabled after disabled page is closed.
+    testFindEnabled("about:blank", finish);
+  }
+}
+
+function testFindDisabled(url, cb) {
+  load(url, function() {
     ok(gFindBar.hidden, "Find bar should not be visible");
     EventUtils.synthesizeKey("/", {}, gTab.linkedBrowser.contentWindow);
     ok(gFindBar.hidden, "Find bar should not be visible");
     EventUtils.synthesizeKey("f", { accelKey: true });
     ok(gFindBar.hidden, "Find bar should not be visible");
     ok(document.getElementById("cmd_find").getAttribute("disabled"),
        "Find command should be disabled");
 
     gBrowser.removeTab(gTab);
-    run_test_2();
+    cb();
   });
 }
 
-function run_test_2() {
-  load("about:addons", function() {
-    ok(gFindBar.hidden, "Find bar should not be visible");
-    EventUtils.synthesizeKey("/", {}, gTab.linkedBrowser.contentWindow);
-    ok(gFindBar.hidden, "Find bar should not be visible");
-    EventUtils.synthesizeKey("f", { accelKey: true });
-    ok(gFindBar.hidden, "Find bar should not be visible");
-    ok(document.getElementById("cmd_find").getAttribute("disabled"),
-       "Find command should be disabled");
-
-    gBrowser.removeTab(gTab);
-    run_test_3();
-  });
-}
-
-function run_test_3() {
-  load("about:blank", function() {
+function testFindEnabled(url, cb) {
+  load(url, function() {
     ok(!document.getElementById("cmd_find").getAttribute("disabled"),
        "Find command should not be disabled");
 
     gBrowser.removeTab(gTab);
-    finish();
+    cb();
   });
-}
\ No newline at end of file
+}
--- a/browser/base/content/test/tabview/Makefile.in
+++ b/browser/base/content/test/tabview/Makefile.in
@@ -139,16 +139,17 @@ include $(topsrcdir)/config/rules.mk
                  browser_tabview_bug645653.js \
                  browser_tabview_bug648882.js \
                  browser_tabview_bug649006.js \
                  browser_tabview_bug649307.js \
                  browser_tabview_bug650573.js \
                  browser_tabview_bug651311.js \
                  browser_tabview_bug654941.js \
                  browser_tabview_bug656778.js \
+                 browser_tabview_bug656913.js \
                  browser_tabview_dragdrop.js \
                  browser_tabview_exit_button.js \
                  browser_tabview_expander.js \
                  browser_tabview_firstrun_pref.js \
                  browser_tabview_group.js \
                  browser_tabview_launch.js \
                  browser_tabview_multiwindow_search.js \
                  browser_tabview_orphaned_tabs.js \
--- a/browser/base/content/test/tabview/browser_tabview_bug595804.js
+++ b/browser/base/content/test/tabview/browser_tabview_bug595804.js
@@ -77,16 +77,18 @@ function zoomInAndOut(transitionsExpecte
   };
   
   let onShownAgain = function() {
     contentWindow.removeEventListener("tabviewshown", onShownAgain, false);
     if (transitionsExpected)
       ok(transitioned >= 0, "There can be transitions");
     else
       ok(!transitioned, "There should have been no transitions");
+
+    contentWindow.document.removeEventListener("transitionend", onTransitionEnd, false);
     callback();
   };
   
   contentWindow.addEventListener("tabviewhidden", onHidden, false);
   contentWindow.addEventListener("tabviewshown", onShownAgain, false);
   
   // get this party started by hiding tab view
   TabView.toggle();
--- a/browser/base/content/test/tabview/browser_tabview_bug598375.js
+++ b/browser/base/content/test/tabview/browser_tabview_bug598375.js
@@ -6,14 +6,16 @@ function test() {
 
   newWindowWithTabView(function (win) {
     registerCleanupFunction(function () win.close());
 
     let cw = win.TabView.getContentWindow();
     let groupItem = cw.GroupItems.groupItems[0];
     groupItem.setBounds(new cw.Rect(cw.innerWidth - 200, 0, 200, 200));
 
-    whenTabViewIsHidden(finish, win);
+    whenTabViewIsHidden(function () waitForFocus(finish), win);
 
-    let button = cw.document.getElementById("exit-button");
-    EventUtils.synthesizeMouseAtCenter(button, {}, cw);
+    waitForFocus(function () {
+      let button = cw.document.getElementById("exit-button");
+      EventUtils.synthesizeMouseAtCenter(button, {}, cw);
+    }, cw);
   });
 }
--- a/browser/base/content/test/tabview/browser_tabview_bug628061.js
+++ b/browser/base/content/test/tabview/browser_tabview_bug628061.js
@@ -21,17 +21,33 @@ let state = {
         '{"1":{"bounds":{"left":15,"top":5,"width":280,"height":232},"id":1},' +
         '"2":{"bounds":{"left":309,"top":5,"width":267,"height":226},"id":2}}'
     }
   }]
 };
 
 function test() {
   waitForExplicitFinish();
+  testOne();
+}
 
+function testOne() {
+  newWindowWithTabView(
+    function(win) {
+      testTwo();
+      win.close();
+    },
+    function(win) {
+      registerCleanupFunction(function() win.close());
+      is(win.document.getElementById("tabviewGroupsNumber").getAttribute("groups"),
+         "1", "There is one group");
+    });
+}
+
+function testTwo() {
   newWindowWithState(state, function(win) {
     registerCleanupFunction(function() win.close());
 
-    is(win.document.getElementById("tabviewGroupsNumber").getAttribute("groups"), 
+    is(win.document.getElementById("tabviewGroupsNumber").getAttribute("groups"),
        "2", "There are two groups");
     waitForFocus(finish);
   });
 }
new file mode 100644
--- /dev/null
+++ b/browser/base/content/test/tabview/browser_tabview_bug656913.js
@@ -0,0 +1,45 @@
+/* Any copyright is dedicated to the Public Domain.
+   http://creativecommons.org/publicdomain/zero/1.0/ */
+
+// ----------
+function test() {
+  waitForExplicitFinish();
+
+  let urlBase = "http://mochi.test:8888/browser/browser/base/content/test/tabview/";
+  let newTab = gBrowser.addTab(urlBase + "search1.html");
+
+  registerCleanupFunction(function() {
+    if (gBrowser.tabs[1])
+      gBrowser.removeTab(gBrowser.tabs[1]);
+    TabView.hide();
+  });
+
+  afterAllTabsLoaded(function() {
+    showTabView(function() {
+      hideTabView(function() {
+        newTab.linkedBrowser.loadURI(urlBase + "dummy_page.html");
+
+        newWindowWithTabView(function(win) {
+          registerCleanupFunction(function() win.close());
+
+          let contentWindow = win.TabView.getContentWindow();
+
+          EventUtils.synthesizeKey("d", { }, contentWindow);
+          EventUtils.synthesizeKey("u", { }, contentWindow);
+          EventUtils.synthesizeKey("m", { }, contentWindow);
+
+          let resultsElement = contentWindow.document.getElementById("results");
+          let childElements = resultsElement.childNodes;
+
+          is(childElements.length, 1, "There is one result element");
+          is(childElements[0].childNodes[1].textContent, 
+             "This is a dummy test page", 
+             "The label matches the title of dummy page");
+
+          finish();
+        });
+      });
+    });
+  });
+}
+
--- a/browser/base/content/test/tabview/browser_tabview_multiwindow_search.js
+++ b/browser/base/content/test/tabview/browser_tabview_multiwindow_search.js
@@ -4,21 +4,23 @@
 let newWindows = [];
 
 function test() {
   waitForExplicitFinish();
   let windowOne = openDialog(location, "", "chrome,all,dialog=no", "data:text/html,");
   let windowTwo;
 
   windowOne.addEventListener("load", function() {
+    windowOne.removeEventListener("load", arguments.callee, false);
     windowOne.gBrowser.selectedBrowser.addEventListener("load", function() {
       windowOne.gBrowser.selectedBrowser.removeEventListener("load", arguments.callee, true);
 
       windowTwo = openDialog(location, "", "chrome,all,dialog=no", "http://mochi.test:8888/");
       windowTwo.addEventListener("load", function() {
+        windowTwo.removeEventListener("load", arguments.callee, false);
         windowTwo.gBrowser.selectedBrowser.addEventListener("load", function() {
           windowTwo.gBrowser.selectedBrowser.removeEventListener("load", arguments.callee, true);
 
           newWindows = [ windowOne, windowTwo ];
 
           // show the tab view
           window.addEventListener("tabviewshown", onTabViewWindowLoaded, false);
           ok(!TabView.isVisible(), "Tab View is hidden");
@@ -140,9 +142,9 @@ function whenWindowObservesOnce(win, top
       if (origWin && theWin != origWin)
         return;
       if(aTopic == origTopic) {
           windowWatcher.unregisterNotification(windowObserver);
           origFunc.apply(this, []);
       }
     }
     windowWatcher.registerNotification(windowObserver);
-}
\ No newline at end of file
+}
--- a/browser/base/content/urlbarBindings.xml
+++ b/browser/base/content/urlbarBindings.xml
@@ -255,16 +255,17 @@
 
       <method name="handleCommand">
         <parameter name="aTriggeringEvent"/>
         <body><![CDATA[
           if (aTriggeringEvent instanceof MouseEvent && aTriggeringEvent.button == 2)
             return; // Do nothing for right clicks
 
           var url = this.value;
+          var mayInheritPrincipal = false;
           var postData = null;
 
           var action = this._parseActionUrl(url);
           if (action) {
             url = action.param;
             if (this.hasAttribute("actiontype")) {
               if (action.type == "switchtab") {
                 this.handleRevert();
@@ -272,36 +273,39 @@
                 if (switchToTabHavingURI(url) &&
                     isTabEmpty(prevTab))
                   gBrowser.removeTab(prevTab);
               }
               return;
             }
           }
           else {
-            [url, postData] = this._canonizeURL(aTriggeringEvent);
+            [url, postData, mayInheritPrincipal] = this._canonizeURL(aTriggeringEvent);
             if (!url)
               return;
           }
 
           this.value = url;
           gBrowser.userTypedValue = url;
           try {
             addToUrlbarHistory(url);
           } catch (ex) {
             // Things may go wrong when adding url to session history,
             // but don't let that interfere with the loading of the url.
             Cu.reportError(ex);
           }
 
           function loadCurrent() {
+            let flags = Ci.nsIWebNavigation.LOAD_FLAGS_ALLOW_THIRD_PARTY_FIXUP;
             // Pass LOAD_FLAGS_DISALLOW_INHERIT_OWNER to prevent any loads from
-            // inheriting the currently loaded document's principal.
-            let flags = Ci.nsIWebNavigation.LOAD_FLAGS_ALLOW_THIRD_PARTY_FIXUP |
-                        Ci.nsIWebNavigation.LOAD_FLAGS_DISALLOW_INHERIT_OWNER;
+            // inheriting the currently loaded document's principal, unless this
+            // URL is marked as safe to inherit (e.g. came from a bookmark
+            // keyword).
+            if (!mayInheritPrincipal)
+              flags |= Ci.nsIWebNavigation.LOAD_FLAGS_DISALLOW_INHERIT_OWNER;
             gBrowser.loadURIWithFlags(url, flags, null, null, postData);
           }
 
           if (aTriggeringEvent instanceof MouseEvent) {
             // We have a mouse event (from the go button), so use the standard
             // UI link behaviors
             let where = whereToOpenLink(aTriggeringEvent, false, false);
             if (where == "current") {
@@ -334,17 +338,17 @@
         ]]></body>
       </method>
 
       <method name="_canonizeURL">
         <parameter name="aTriggeringEvent"/>
         <body><![CDATA[
           var url = this.value;
           if (!url)
-            return ["", null];
+            return ["", null, false];
 
           // Only add the suffix when the URL bar value isn't already "URL-like",
           // and only if we get a keyboard event, to match user expectations.
           if (!/^\s*(www|https?)\b|\/\s*$/i.test(url) &&
               (aTriggeringEvent instanceof KeyEvent)) {
 #ifdef XP_MACOSX
             let accel = aTriggeringEvent.metaKey;
 #else
@@ -397,19 +401,20 @@
               } else
                 url = url + (existingSuffix == -1 ? suffix : "/");
 
               url = "http://www." + url;
             }
           }
 
           var postData = {};
-          url = getShortcutOrURI(url, postData);
+          var mayInheritPrincipal = { value: false };
+          url = getShortcutOrURI(url, postData, mayInheritPrincipal);
 
-          return [url, postData.value];
+          return [url, postData.value, mayInheritPrincipal.value];
         ]]></body>
       </method>
 
       <field name="_contentIsCropped">false</field>
 
       <method name="_initURLTooltip">
         <body><![CDATA[
           if (this.focused || !this._contentIsCropped)
--- a/browser/branding/aurora/content/jar.mn
+++ b/browser/branding/aurora/content/jar.mn
@@ -1,11 +1,10 @@
 browser.jar:
 % content branding %content/branding/ contentaccessible=yes
   content/branding/about.png                     (about.png)
   content/branding/about-background.png          (about-background.png)
   content/branding/about-logo.png                (about-logo.png)
   content/branding/about-wordmark.png            (about-wordmark.png)
   content/branding/icon48.png                    (icon48.png)
   content/branding/icon64.png                    (icon64.png)
-  content/branding/icon128.png                   (../mozicon128.png)
   content/branding/icon16.png                    (../default16.png)
   content/branding/aboutDialog.css               (aboutDialog.css)
--- a/browser/branding/nightly/content/jar.mn
+++ b/browser/branding/nightly/content/jar.mn
@@ -1,11 +1,10 @@
 browser.jar:
 % content branding %content/branding/ contentaccessible=yes
   content/branding/about.png                     (about.png)
   content/branding/about-background.png          (about-background.png)
   content/branding/about-logo.png                (about-logo.png)
   content/branding/about-wordmark.png            (about-wordmark.png)
   content/branding/icon48.png                    (icon48.png)
   content/branding/icon64.png                    (icon64.png)
-  content/branding/icon128.png                   (../mozicon128.png)
   content/branding/icon16.png                    (../default16.png)
   content/branding/aboutDialog.css               (aboutDialog.css)
--- a/browser/branding/official/content/jar.mn
+++ b/browser/branding/official/content/jar.mn
@@ -1,10 +1,9 @@
 browser.jar:
 % content branding %content/branding/ contentaccessible=yes
   content/branding/about.png                     (about.png)
   content/branding/about-logo.png                (about-logo.png)
   content/branding/about-wordmark.png            (about-wordmark.png)
   content/branding/icon48.png                    (icon48.png)
   content/branding/icon64.png                    (icon64.png)
-  content/branding/icon128.png                   (../mozicon128.png)
   content/branding/icon16.png                    (../default16.png)
   content/branding/aboutDialog.css               (aboutDialog.css)
--- a/browser/branding/unofficial/content/jar.mn
+++ b/browser/branding/unofficial/content/jar.mn
@@ -1,11 +1,10 @@
 browser.jar:
 % content branding %content/branding/ contentaccessible=yes
   content/branding/about.png                     (about.png)
   content/branding/about-background.png          (about-background.png)
   content/branding/about-logo.png                (about-logo.png)
   content/branding/about-wordmark.png            (about-wordmark.png)
   content/branding/icon48.png                    (icon48.png)
   content/branding/icon64.png                    (icon64.png)
-  content/branding/icon128.png                   (../mozicon128.png)
   content/branding/icon16.png                    (../default16.png)
   content/branding/aboutDialog.css               (aboutDialog.css)
--- a/browser/components/preferences/aboutPermissions.js
+++ b/browser/components/preferences/aboutPermissions.js
@@ -140,16 +140,25 @@ Site.prototype = {
    *        The permission type string stored in permission manager.
    *        e.g. "cookie", "geo", "indexedDB", "popup", "image"
    * @param aResultObj
    *        An object that stores the permission value set for aType.
    *
    * @return A boolean indicating whether or not a permission is set.
    */
   getPermission: function Site_getPermission(aType, aResultObj) {
+    // Password saving isn't a nsIPermissionManager permission type, so handle
+    // it seperately.
+    if (aType == "password") {
+      aResultObj.value =  this.loginSavingEnabled ?
+                          Ci.nsIPermissionManager.ALLOW_ACTION :
+                          Ci.nsIPermissionManager.DENY_ACTION;
+      return true;
+    }
+
     let permissionValue;
     if (TEST_EXACT_PERM_TYPES.indexOf(aType) == -1) {
       permissionValue = Services.perms.testPermission(this.httpURI, aType);
     } else {
       permissionValue = Services.perms.testExactPermission(this.httpURI, aType);
     }
     aResultObj.value = permissionValue;
 
@@ -162,16 +171,23 @@ Site.prototype = {
    * @param aType
    *        The permission type string stored in permission manager.
    *        e.g. "cookie", "geo", "indexedDB", "popup", "image"
    * @param aPerm
    *        The permission value to set for the permission type. This should
    *        be one of the constants defined in nsIPermissionManager.
    */
   setPermission: function Site_setPermission(aType, aPerm) {
+    // Password saving isn't a nsIPermissionManager permission type, so handle
+    // it seperately.
+    if (aType == "password") {
+      this.loginSavingEnabled = aPerm == Ci.nsIPermissionManager.ALLOW_ACTION;
+      return;
+    }
+
     // Using httpURI is kind of bogus, but the permission manager stores the
     // permission for the host, so the right thing happens in the end.
     Services.perms.add(this.httpURI, aType, aPerm);
   },
 
   /**
    * Clears a user-set permission value for the site given a permission type.
    *
@@ -458,37 +474,41 @@ let AboutPermissions = {
   /**
    * Creates Site objects for the top-frecency sites in the places database and stores
    * them in _sites. The number of sites created is controlled by PLACES_SITES_LIMIT.
    */
   getSitesFromPlaces: function() {
     gSitesStmt.params.limit = this.PLACES_SITES_LIMIT;
     gSitesStmt.executeAsync({
       handleResult: function(aResults) {
+        AboutPermissions.startSitesListBatch();
         let row;
         while (row = aResults.getNextRow()) {
           let host = row.getResultByName("host");
           AboutPermissions.addHost(host);
         }
+        AboutPermissions.endSitesListBatch();
       },
       handleError: function(aError) {
         Cu.reportError("AboutPermissions: " + aError);
       },
       handleCompletion: function(aReason) {
         // Notify oberservers for testing purposes.
         Services.obs.notifyObservers(null, "browser-permissions-initialized", null);
       }
     });
   },
 
   /**
    * Finds sites that have non-default permissions and creates Site objects for
    * them if they are not already stored in _sites.
    */
   enumerateServices: function() {
+    this.startSitesListBatch();
+
     let logins = Services.logins.getAllLogins();
     logins.forEach(function(aLogin) {
       try {
         // aLogin.hostname is a string in origin URL format (e.g. "http://foo.com")
         let uri = NetUtil.newURI(aLogin.hostname);
         this.addHost(uri.host);
       } catch (e) {
         // newURI will throw for add-ons logins stored in chrome:// URIs 
@@ -510,16 +530,18 @@ let AboutPermissions = {
       while (enumerator.hasMoreElements()) {
         let permission = enumerator.getNext().QueryInterface(Ci.nsIPermission);
         // Only include sites with exceptions set for supported permission types.
         if (this._supportedPermissions.indexOf(permission.type) != -1) {
           this.addHost(permission.host);
         }
       }
     }
+
+    this.endSitesListBatch();
   },
 
   /**
    * Creates a new Site and adds it to _sites if it's not already there.
    *
    * @param aHost
    *        A host string.
    */
@@ -543,17 +565,29 @@ let AboutPermissions = {
     item.setAttribute("class", "site");
     item.setAttribute("value", aSite.host);
 
     aSite.getFavicon(function(aURL) {
       item.setAttribute("favicon", aURL);
     });
     aSite.listitem = item;
 
-    this.sitesList.appendChild(item);    
+    (this._listFragment || this.sitesList).appendChild(item);
+  },
+
+  startSitesListBatch: function () {
+    if (!this._listFragment)
+      this._listFragment = document.createDocumentFragment();
+  },
+
+  endSitesListBatch: function () {
+    if (this._listFragment) {
+      this.sitesList.appendChild(this._listFragment);
+      this._listFragment = null;
+    }
   },
 
   /**
    * Hides sites in richlistbox based on search text in sites-filter textbox.
    */
   filterSitesList: function() {
     let siteItems = this.sitesList.children;
     let filterValue = document.getElementById("sites-filter").value.toLowerCase();
@@ -651,54 +685,40 @@ let AboutPermissions = {
    * stored permission.
    *
    * @param aType
    *        The permission type string stored in permission manager.
    *        e.g. "cookie", "geo", "indexedDB", "popup", "image"
    */
   updatePermission: function(aType) {
     let allowItem = document.getElementById(aType + "-" + PermissionDefaults.ALLOW);
-    if (!this._selectedSite &&
-        this._noGlobalAllow.indexOf(aType) != -1) {
-      allowItem.hidden = true;
-      return;
-    }
-
-    allowItem.hidden = false;
+    allowItem.hidden = !this._selectedSite &&
+                       this._noGlobalAllow.indexOf(aType) != -1;
 
     let permissionMenulist = document.getElementById(aType + "-menulist");
     let permissionValue;    
     if (!this._selectedSite) {
-
       // If there is no selected site, we are updating the default permissions interface.
       permissionValue = PermissionDefaults[aType];
-    } else if (aType == "password") {
-      // Services.logins.getLoginSavingEnabled already looks at the default
-      // permission, so we don't need to.
-      permissionValue = this._selectedSite.loginSavingEnabled ?
-                        PermissionDefaults.ALLOW : PermissionDefaults.DENY;
     } else {
       let result = {};
       permissionValue = this._selectedSite.getPermission(aType, result) ?
                         result.value : PermissionDefaults[aType];
     }
 
     permissionMenulist.selectedItem = document.getElementById(aType + "-" + permissionValue);
   },
 
   onPermissionCommand: function(event) {
     let permissionType = event.currentTarget.getAttribute("type");
     let permissionValue = event.target.value;
 
     if (!this._selectedSite) {
       // If there is no selected site, we are setting the default permission.
       PermissionDefaults[permissionType] = permissionValue;
-    } else if (permissionType == "password") {
-      let isEnabled = permissionValue == PermissionDefaults.ALLOW;
-      this._selectedSite.loginSavingEnabled = isEnabled;
     } else {
       this._selectedSite.setPermission(permissionType, permissionValue);
     }
   },
 
   updateVisitCount: function() {
     this._selectedSite.getVisitCount(function(aCount) {
       let visitForm = AboutPermissions._stringBundle.GetStringFromName("visitCount");
--- a/browser/components/preferences/aboutPermissions.xul
+++ b/browser/components/preferences/aboutPermissions.xul
@@ -47,16 +47,17 @@
 %aboutPermissionsDTD;
 ]>
 
 <page xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
       xmlns:xhtml="http://www.w3.org/1999/xhtml"
       id="permissions-page" title="&permissionsManager.title;"
       onload="AboutPermissions.init();"
       onunload="AboutPermissions.cleanUp();"
+      disablefastfind="true"
       role="application">
 
   <script type="application/javascript"
           src="chrome://browser/content/preferences/aboutPermissions.js"/>
 
   <hbox flex="1" id="permissions-content">
 
     <vbox id="sites-box">
@@ -158,26 +159,26 @@
                       oncommand="AboutPermissions.onPermissionCommand(event);">
               <menupopup>
                 <menuitem id="cookie-1" value="1" label="&permission.allow;"/>
                 <menuitem id="cookie-8" value="8" label="&permission.allowForSession;"/>
                 <menuitem id="cookie-2" value="2" label="&permission.block;"/>
               </menupopup>
             </menulist>
             <button id="cookies-clear-all-button"
-                    label="&cookie.clearAll;"
+                    label="&cookie.removeAll;"
                     oncommand="Services.cookies.removeAll();"/>
             <button id="cookies-manage-all-button"
                     label="&cookie.manage;"
                     oncommand="AboutPermissions.manageCookies();"/>
           </hbox>
           <hbox id="cookies-count" align="center">
             <label id="cookies-label"/>
             <button id="cookies-clear-button"
-                    label="&cookie.clear;"
+                    label="&cookie.remove;"
                     oncommand="AboutPermissions.clearCookies();"/>
             <button id="cookies-manage-button"
                     label="&cookie.manage;"
                     oncommand="AboutPermissions.manageCookies();"/>
           </hbox>
         </vbox>
       </hbox>
 
--- a/browser/components/preferences/privacy.xul
+++ b/browser/components/preferences/privacy.xul
@@ -182,18 +182,18 @@
               >&dontrememberActions.clearHistory.label;</html:a>&dontrememberActions.post.label;</description>
             </vbox>
             <spacer flex="1" class="indent"/>
           </hbox>
         </vbox>
         <vbox id="historyCustomPane">
           <separator class="thin"/>
           <checkbox id="privateBrowsingAutoStart" class="indent"
-                    label="&privateBrowsingPermanent.label;"
-                    accesskey="&privateBrowsingPermanent.accesskey;"
+                    label="&privateBrowsingPermanent2.label;"
+                    accesskey="&privateBrowsingPermanent2.accesskey;"
                     preference="browser.privatebrowsing.autostart"/>
 
           <vbox class="indent">
             <vbox class="indent">
               <checkbox id="rememberHistory"
                         label="&rememberHistory.label;"
                         accesskey="&rememberHistory.accesskey;"
                         preference="places.history.enabled"/>
--- a/browser/components/preferences/tests/browser_permissions.js
+++ b/browser/components/preferences/tests/browser_permissions.js
@@ -20,16 +20,21 @@ const PERM_SESION = 8;
 const TEST_PERMS = {
   "password": PERM_ALLOW,
   "cookie": PERM_ALLOW,
   "geo": PERM_UNKNOWN,
   "indexedDB": PERM_UNKNOWN,
   "popup": PERM_DENY
 };
 
+const NO_GLOBAL_ALLOW = [
+  "geo",
+  "indexedDB"
+];
+
 // number of managed permissions in the interface
 const TEST_PERMS_COUNT = 5;
 
 function test() {
   waitForExplicitFinish();
   registerCleanupFunction(cleanUp);
 
   // add test history visit
@@ -138,16 +143,22 @@ var tests = [
     is(defaultsHeader, gHeaderDeck.selectedPanel,
        "correct header shown for all sites");
 
     ok(gBrowser.contentDocument.getElementById("passwords-count").hidden,
        "passwords count is hidden");
     ok(gBrowser.contentDocument.getElementById("cookies-count").hidden,
        "cookies count is hidden");
 
+    // Test to make sure "Allow" items hidden for certain permission types
+    NO_GLOBAL_ALLOW.forEach(function(aType) {
+      let menuitem = gBrowser.contentDocument.getElementById(aType + "-" + PERM_ALLOW);
+      ok(menuitem.hidden, aType + " allow menuitem hidden for all sites");
+    });
+
     runNextTest();
   },
 
   function test_all_sites_permission() {
     // there should be no user-set pref for cookie behavior
     is(Services.prefs.getIntPref("network.cookie.cookieBehavior"), PERM_UNKNOWN,
        "network.cookie.cookieBehavior is expected default");
 
@@ -190,16 +201,22 @@ var tests = [
        "correct header shown for a specific site");
     is(gSiteLabel.value, TEST_URI_2.host, "header updated for selected site");
 
     ok(!gBrowser.contentDocument.getElementById("passwords-count").hidden,
        "passwords count is not hidden");
     ok(!gBrowser.contentDocument.getElementById("cookies-count").hidden,
        "cookies count is not hidden");
 
+    // Test to make sure "Allow" items are *not* hidden for certain permission types
+    NO_GLOBAL_ALLOW.forEach(function(aType) {
+      let menuitem = gBrowser.contentDocument.getElementById(aType + "-" + PERM_ALLOW);
+      ok(!menuitem.hidden, aType  + " allow menuitem not hidden for single site");
+    });
+
     runNextTest();
   },
 
   function test_permissions() {
     let menulists = gBrowser.contentDocument.getElementsByClassName("pref-menulist");
     is(menulists.length, TEST_PERMS_COUNT, "got expected number of managed permissions");
 
     for (let i = 0; i < menulists.length; i++) {
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_certexceptionsui.js
+++ b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_certexceptionsui.js
@@ -58,16 +58,17 @@ function test() {
   function step1() {
     let params = {
       exceptionAdded : false,
       location: INVALID_CERT_LOCATION,
       handlePrivateBrowsing : true,
       prefetchCert: true,
     };
     function testCheckbox() {
+      win.removeEventListener("load", testCheckbox, false);
       Services.obs.addObserver(function (aSubject, aTopic, aData) {
         Services.obs.removeObserver(arguments.callee, "cert-exception-ui-ready", false);
         ok(win.gCert, "The certificate information should be available now");
 
         let checkbox = win.document.getElementById("permanent");
         ok(checkbox.hasAttribute("disabled"),
           "the permanent checkbox should be disabled when handling the private browsing mode");
         ok(!checkbox.hasAttribute("checked"),
@@ -83,16 +84,17 @@ function test() {
   // Test the certificate excetions dialog as it is invoked from the Preferences dialog
   function step2() {
     let params = {
       exceptionAdded : false,
       location: INVALID_CERT_LOCATION,
       prefetchCert: true,
     };
     function testCheckbox() {
+      win.removeEventListener("load", testCheckbox, false);
       Services.obs.addObserver(function (aSubject, aTopic, aData) {
         Services.obs.removeObserver(arguments.callee, "cert-exception-ui-ready", false);
         ok(win.gCert, "The certificate information should be available now");
 
         let checkbox = win.document.getElementById("permanent");
         ok(!checkbox.hasAttribute("disabled"),
           "the permanent checkbox should not be disabled when not handling the private browsing mode");
         ok(checkbox.hasAttribute("checked"),
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_pageinfo.js
+++ b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_pageinfo.js
@@ -47,34 +47,38 @@ function test() {
     let tab1 = gBrowser.addTab();
     gBrowser.selectedTab = tab1;
     let browser1 = gBrowser.getBrowserForTab(tab1);
     browser1.addEventListener("load", function () {
       browser1.removeEventListener("load", arguments.callee, true);
 
       let pageInfo1 = BrowserPageInfo();
       pageInfo1.addEventListener("load", function () {
+        pageInfo1.removeEventListener("load", arguments.callee, false);
 
         let tab2 = gBrowser.addTab();
         gBrowser.selectedTab = tab2;
         let browser2 = gBrowser.getBrowserForTab(tab2);
         browser2.addEventListener("load", function () {
           browser2.removeEventListener("load", arguments.callee, true);
 
           let pageInfo2 = BrowserPageInfo();
           pageInfo2.addEventListener("load", function () {
+            pageInfo2.removeEventListener("load", arguments.callee, false);
 
             pageInfo1.addEventListener("unload", function () {
+              pageInfo1.removeEventListener("unload", arguments.callee, false);
               pageInfo1 = null;
               ok(true, "Page info 1 being closed as expected");
               if (!pageInfo2)
                 aCallBack();
             }, false);
 
             pageInfo2.addEventListener("unload", function () {
+              pageInfo2.removeEventListener("unload", arguments.callee, false);
               pageInfo2 = null;
               ok(true, "Page info 2 being closed as expected");
               if (!pageInfo1)
                 aCallBack();
             }, false);
 
             pb.privateBrowsingEnabled = aPBMode;
           }, false);
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_urlbarfocus.js
+++ b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_urlbarfocus.js
@@ -54,31 +54,37 @@ function test() {
       "URL Bar should not be focused before entering the private browsing mode");
     // ensure that the URL bar is not empty initially
     isnot(gURLBar.value, "", "URL Bar should no longer be empty after leaving the private browsing mode");
 
     // enter private browsing mode
     pb.privateBrowsingEnabled = true;
     browser = gBrowser.selectedBrowser;
     browser.addEventListener("load", function() {
+      browser.removeEventListener("load", arguments.callee, true);
+
       // setTimeout is needed here because the onload handler of about:privatebrowsing sets the focus
       setTimeout(function() {
         // ensure that the URL bar is focused inside the private browsing mode
         is(document.commandDispatcher.focusedElement, gURLBar.inputField,
           "URL Bar should be focused inside the private browsing mode");
+
         // ensure that the URL bar is emptied inside the private browsing mode
         is(gURLBar.value, "", "URL Bar should be empty inside the private browsing mode");
 
         // leave private browsing mode
         pb.privateBrowsingEnabled = false;
         browser = gBrowser.selectedBrowser;
         browser.addEventListener("load", function() {
+          browser.removeEventListener("load", arguments.callee, true);
+
           // ensure that the URL bar is no longer focused after leaving the private browsing mode
           isnot(document.commandDispatcher.focusedElement, gURLBar.inputField,
             "URL Bar should no longer be focused after leaving the private browsing mode");
+
           // ensure that the URL bar is no longer empty after leaving the private browsing mode
           isnot(gURLBar.value, "", "URL Bar should no longer be empty after leaving the private browsing mode");
 
           gBrowser.removeCurrentTab();
           finish();
         }, true);
       }, 0);
     }, true);
--- a/browser/components/sessionstore/test/browser/browser_394759.js
+++ b/browser/components/sessionstore/test/browser/browser_394759.js
@@ -66,16 +66,18 @@ function test() {
   
     // make sure that the next closed window will increase getClosedWindowCount
     let max_windows_undo = gPrefService.getIntPref("browser.sessionstore.max_windows_undo");
     gPrefService.setIntPref("browser.sessionstore.max_windows_undo", max_windows_undo + 1);
     let closedWindowCount = ss.getClosedWindowCount();
   
     let newWin = openDialog(location, "", "chrome,all,dialog=no", testURL);
     newWin.addEventListener("load", function(aEvent) {
+      newWin.removeEventListener("load", arguments.callee, false);
+
       newWin.gBrowser.selectedBrowser.addEventListener("load", function(aEvent) {
         newWin.gBrowser.selectedBrowser.removeEventListener("load", arguments.callee, true);
 
         executeSoon(function() {
           newWin.gBrowser.addTab().linkedBrowser.stop();
           executeSoon(function() {
             // mark the window with some unique data to be restored later on
             ss.setWindowValue(newWin, uniqueKey, uniqueValue);
@@ -97,16 +99,18 @@ function test() {
                "undoCloseWindow actually returned a window");
             is(ss.getClosedWindowCount(), closedWindowCount,
                "The reopened window was removed from Recently Closed Windows");
 
             // SSTabRestored will fire more than once, so we need to make sure we count them
             let restoredTabs = 0;
             let expectedTabs = data.tabs.length;
             newWin2.addEventListener("load", function(aEvent) {
+              newWin2.removeEventListener("load", arguments.callee, false);
+
               newWin2.gBrowser.tabContainer.addEventListener("SSTabRestored", function(aEvent) {
                 if (++restoredTabs < expectedTabs)
                   return;
                 newWin2.gBrowser.tabContainer.removeEventListener("SSTabRestored", arguments.callee, true);
 
                 is(newWin2.gBrowser.tabs.length, 2,
                    "The window correctly restored 2 tabs");
                 is(newWin2.gBrowser.currentURI.spec, testURL,
@@ -155,31 +159,33 @@ function test() {
       }
       // hack to force window to be considered a popup (toolbar=no didn't work)
       let winData = windowsToOpen.shift();
       let settings = "chrome,dialog=no," +
                      (winData.isPopup ? "all=no" : "all");
       let url = "http://window" + windowsToOpen.length + ".example.com";
       let win = openDialog(location, "", settings, url);
       win.addEventListener("load", function(aEvent) {
+        win.removeEventListener("load", arguments.callee, false);
+
         win.gBrowser.selectedBrowser.addEventListener("DOMContentLoaded", function(aEvent) {
           win.gBrowser.selectedBrowser.removeEventListener("DOMContentLoaded", arguments.callee, true);
           // the window _should_ have state with a tab of url, but it doesn't
           // always happend before window.close(). addTab ensure we don't treat
           // this window as a stateless window
           win.gBrowser.addTab();
 
           executeSoon(function() {
             win.close();
             executeSoon(function() {
               openWindowRec(windowsToOpen, expectedResults, recCallback);
             });
           });
         }, true);
-      }, true);
+      }, false);
     }
 
     let windowsToOpen = [{isPopup: false},
                          {isPopup: false},
                          {isPopup: true},
                          {isPopup: true},
                          {isPopup: true}];
     let expectedResults = {mac: {popup: 3, normal: 0},
--- a/browser/components/sessionstore/test/browser/browser_461634.js
+++ b/browser/components/sessionstore/test/browser/browser_461634.js
@@ -43,71 +43,73 @@ function browserWindowsCount() {
       ++count;
   }
   return count;
 }
 
 function test() {
   /** Test for Bug 461634 **/
   is(browserWindowsCount(), 1, "Only one browser window should be open initially");
-  
+
   // test setup
   let ss = Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore);
   waitForExplicitFinish();
-  
+
   const REMEMBER = Date.now(), FORGET = Math.random();
   let test_state = { windows: [{ "tabs": [{ "entries": [] }], _closedTabs: [
     { state: { entries: [{ url: "http://www.example.net/" }] }, title: FORGET },
     { state: { entries: [{ url: "http://www.example.net/" }] }, title: REMEMBER },
     { state: { entries: [{ url: "http://www.example.net/" }] }, title: FORGET },
     { state: { entries: [{ url: "http://www.example.net/" }] }, title: REMEMBER },
   ] }] };
   let remember_count = 2;
-  
+
   function countByTitle(aClosedTabList, aTitle)
     aClosedTabList.filter(function(aData) aData.title == aTitle).length;
-  
+
   function testForError(aFunction) {
     try {
       aFunction();
       return false;
     }
     catch (ex) {
       return ex.name == "NS_ERROR_ILLEGAL_VALUE";
     }
   }
-  
+
   // open a window and add the above closed tab list
   let newWin = openDialog(location, "", "chrome,all,dialog=no");
   newWin.addEventListener("load", function(aEvent) {
+    newWin.removeEventListener("load", arguments.callee, false);
+
     gPrefService.setIntPref("browser.sessionstore.max_tabs_undo",
                             test_state.windows[0]._closedTabs.length);
     ss.setWindowState(newWin, JSON.stringify(test_state), true);
-    
+
     let closedTabs = JSON.parse(ss.getClosedTabData(newWin));
     is(closedTabs.length, test_state.windows[0]._closedTabs.length,
        "Closed tab list has the expected length");
     is(countByTitle(closedTabs, FORGET),
        test_state.windows[0]._closedTabs.length - remember_count,
        "The correct amout of tabs are to be forgotten");
     is(countByTitle(closedTabs, REMEMBER), remember_count,
        "Everything is set up.");
-    
+
     // all of the following calls with illegal arguments should throw NS_ERROR_ILLEGAL_VALUE
     ok(testForError(function() ss.forgetClosedTab({}, 0)),
        "Invalid window for forgetClosedTab throws");
     ok(testForError(function() ss.forgetClosedTab(newWin, -1)),
        "Invalid tab for forgetClosedTab throws");
     ok(testForError(function() ss.forgetClosedTab(newWin, test_state.windows[0]._closedTabs.length + 1)),
        "Invalid tab for forgetClosedTab throws");
-	   
+
     // Remove third tab, then first tab
     ss.forgetClosedTab(newWin, 2);
     ss.forgetClosedTab(newWin, null);
-    
+
     closedTabs = JSON.parse(ss.getClosedTabData(newWin));
     is(closedTabs.length, remember_count,
        "The correct amout of tabs was removed");
     is(countByTitle(closedTabs, FORGET), 0,
        "All tabs specifically forgotten were indeed removed");
     is(countByTitle(closedTabs, REMEMBER), remember_count,
        "... and tabs not specifically forgetten weren't.");
 
--- a/browser/components/sessionstore/test/browser/browser_464199.js
+++ b/browser/components/sessionstore/test/browser/browser_464199.js
@@ -42,21 +42,21 @@ function browserWindowsCount() {
       ++count;
   }
   return count;
 }
 
 function test() {
   /** Test for Bug 464199 **/
   is(browserWindowsCount(), 1, "Only one browser window should be open initially");
-  
+
   // test setup
   let ss = Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore);
   waitForExplicitFinish();
-  
+
   const REMEMBER = Date.now(), FORGET = Math.random();
   let test_state = { windows: [{ "tabs": [{ "entries": [] }], _closedTabs: [
     { state: { entries: [{ url: "http://www.example.net/" }] }, title: FORGET },
     { state: { entries: [{ url: "http://www.example.org/" }] }, title: REMEMBER },
     { state: { entries: [{ url: "http://www.example.net/" },
                          { url: "http://www.example.org/" }] }, title: FORGET },
     { state: { entries: [{ url: "http://example.net/" }] }, title: FORGET },
     { state: { entries: [{ url: "http://sub.example.net/" }] }, title: FORGET },
@@ -74,48 +74,50 @@ function test() {
                            ] }] }, title: FORGET },
     { state: { entries: [{ url: "http://www.example.org/form",
                            formdata: { "#url": "http://www.example.net/" }
                          }] }, title: REMEMBER },
     { state: { entries: [{ url: "http://www.example.org/form" }],
                extData: { "setTabValue": "http://example.net:80" } }, title: REMEMBER }
   ] }] };
   let remember_count = 5;
-  
+
   function countByTitle(aClosedTabList, aTitle)
     aClosedTabList.filter(function(aData) aData.title == aTitle).length;
-  
+
   // open a window and add the above closed tab list
   let newWin = openDialog(location, "", "chrome,all,dialog=no");
   newWin.addEventListener("load", function(aEvent) {
+    newWin.removeEventListener("load", arguments.callee, false);
+
     gPrefService.setIntPref("browser.sessionstore.max_tabs_undo",
                             test_state.windows[0]._closedTabs.length);
     ss.setWindowState(newWin, JSON.stringify(test_state), true);
     
     let closedTabs = JSON.parse(ss.getClosedTabData(newWin));
     is(closedTabs.length, test_state.windows[0]._closedTabs.length,
        "Closed tab list has the expected length");
     is(countByTitle(closedTabs, FORGET),
        test_state.windows[0]._closedTabs.length - remember_count,
        "The correct amout of tabs are to be forgotten");
     is(countByTitle(closedTabs, REMEMBER), remember_count,
        "Everything is set up.");
-    
+
     let pb = Cc["@mozilla.org/privatebrowsing;1"].
              getService(Ci.nsIPrivateBrowsingService);
     pb.removeDataFromDomain("example.net");
-    
+
     closedTabs = JSON.parse(ss.getClosedTabData(newWin));
     is(closedTabs.length, remember_count,
        "The correct amout of tabs was removed");
     is(countByTitle(closedTabs, FORGET), 0,
        "All tabs to be forgotten were indeed removed");
     is(countByTitle(closedTabs, REMEMBER), remember_count,
        "... and tabs to be remembered weren't.");
-    
+
     // clean up
     newWin.close();
     is(browserWindowsCount(), 1, "Only one browser window should be open eventually");
     if (gPrefService.prefHasUserValue("browser.sessionstore.max_tabs_undo"))
       gPrefService.clearUserPref("browser.sessionstore.max_tabs_undo");
     finish();
   }, false);
 }
--- a/browser/components/sessionstore/test/browser/browser_465223.js
+++ b/browser/components/sessionstore/test/browser/browser_465223.js
@@ -42,50 +42,52 @@ function browserWindowsCount() {
       ++count;
   }
   return count;
 }
 
 function test() {
   /** Test for Bug 465223 **/
   is(browserWindowsCount(), 1, "Only one browser window should be open initially");
-  
+
   // test setup
   let ss = Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore);
   waitForExplicitFinish();
-  
+
   let uniqueKey1 = "bug 465223.1";
   let uniqueKey2 = "bug 465223.2";
   let uniqueValue1 = "unik" + Date.now();
   let uniqueValue2 = "pi != " + Math.random();
-  
+
   // open a window and set a value on it
   let newWin = openDialog(location, "_blank", "chrome,all,dialog=no");
   newWin.addEventListener("load", function(aEvent) {
+    newWin.removeEventListener("load", arguments.callee, false);
+
     ss.setWindowValue(newWin, uniqueKey1, uniqueValue1);
-    
+
     let newState = { windows: [{ tabs:[{ entries: [] }], extData: {} }] };
     newState.windows[0].extData[uniqueKey2] = uniqueValue2;
     ss.setWindowState(newWin, JSON.stringify(newState), false);
-    
+
     is(newWin.gBrowser.tabs.length, 2,
        "original tab wasn't overwritten");
     is(ss.getWindowValue(newWin, uniqueKey1), uniqueValue1,
        "window value wasn't overwritten when the tabs weren't");
     is(ss.getWindowValue(newWin, uniqueKey2), uniqueValue2,
        "new window value was correctly added");
-    
+
     newState.windows[0].extData[uniqueKey2] = uniqueValue1;
     ss.setWindowState(newWin, JSON.stringify(newState), true);
-    
+
     is(newWin.gBrowser.tabs.length, 1,
        "original tabs were overwritten");
     is(ss.getWindowValue(newWin, uniqueKey1), "",
        "window value was cleared");
     is(ss.getWindowValue(newWin, uniqueKey2), uniqueValue1,
        "window value was correctly overwritten");
-    
+
     // clean up
     newWin.close();
     is(browserWindowsCount(), 1, "Only one browser window should be open eventually");
     finish();
   }, false);
 }
--- a/browser/components/sessionstore/test/browser/browser_477657.js
+++ b/browser/components/sessionstore/test/browser/browser_477657.js
@@ -52,60 +52,62 @@ function test() {
   if ("nsILocalFileMac" in Ci)
     return;
 
   let ss = Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore);
   waitForExplicitFinish();
   
   let newWin = openDialog(location, "_blank", "chrome,all,dialog=no");
   newWin.addEventListener("load", function(aEvent) {
+    newWin.removeEventListener("load", arguments.callee, false);
+
     let newState = { windows: [{
       tabs: [{ entries: [] }],
       _closedTabs: [{
         state: { entries: [{ url: "about:" }]},
         title: "About:"
       }],
       sizemode: "maximized"
     }] };
-    
+
     let uniqueKey = "bug 477657";
     let uniqueValue = "unik" + Date.now();
-  
+
     ss.setWindowValue(newWin, uniqueKey, uniqueValue);
     is(ss.getWindowValue(newWin, uniqueKey), uniqueValue,
        "window value was set before the window was overwritten");
     ss.setWindowState(newWin, JSON.stringify(newState), true);
-    
+
     // use setTimeout(..., 0) to mirror sss_restoreWindowFeatures
     setTimeout(function() {
       is(ss.getWindowValue(newWin, uniqueKey), "",
          "window value was implicitly cleared");
-      
+
       is(newWin.windowState, newWin.STATE_MAXIMIZED,
          "the window was maximized");
-      
+
       is(JSON.parse(ss.getClosedTabData(newWin)).length, 1,
          "the closed tab was added before the window was overwritten");
       delete newState.windows[0]._closedTabs;
       delete newState.windows[0].sizemode;
       ss.setWindowState(newWin, JSON.stringify(newState), true);
-      
+
       setTimeout(function() {
         is(JSON.parse(ss.getClosedTabData(newWin)).length, 0,
            "closed tabs were implicitly cleared");
-        
+
         is(newWin.windowState, newWin.STATE_MAXIMIZED,
            "the window remains maximized");
         newState.windows[0].sizemode = "normal";
         ss.setWindowState(newWin, JSON.stringify(newState), true);
-        
+
         setTimeout(function() {
           isnot(newWin.windowState, newWin.STATE_MAXIMIZED,
                 "the window was explicitly unmaximized");
-          
+
           newWin.close();
           is(browserWindowsCount(), 1, "Only one browser window should be open eventually");
           finish();
         }, 0);
       }, 0);
     }, 0);
   }, false);
 }
--- a/browser/components/sessionstore/test/browser/browser_514751.js
+++ b/browser/components/sessionstore/test/browser/browser_514751.js
@@ -61,16 +61,18 @@ function test() {
           {}
         ]
       }]
     }]
   };
 
   var theWin = openDialog(location, "", "chrome,all,dialog=no");
   theWin.addEventListener("load", function () {
+    theWin.removeEventListener("load", arguments.callee, false);
+
     executeSoon(function () {
       var gotError = false;
       try {
         ss.setWindowState(theWin, JSON.stringify(state), true);
       } catch (e) {
         if (/NS_ERROR_MALFORMED_URI/.test(e))
           gotError = true;
       }
--- a/browser/components/sessionstore/test/browser/browser_528776.js
+++ b/browser/components/sessionstore/test/browser/browser_528776.js
@@ -15,14 +15,15 @@ function browserWindowsCount(expected) {
 
 function test() {
   waitForExplicitFinish();
 
   browserWindowsCount(1);
 
   var win = openDialog(location, "", "chrome,all,dialog=no");
   win.addEventListener("load", function () {
+    win.removeEventListener("load", arguments.calle, false);
     browserWindowsCount(2);
     win.close();
     browserWindowsCount(1);
     finish();
   }, false);
 }
--- a/browser/components/sessionstore/test/browser/browser_579868.js
+++ b/browser/components/sessionstore/test/browser/browser_579868.js
@@ -32,20 +32,22 @@
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 function test() {
   let tab1 = gBrowser.addTab("about:robots");
   let tab2 = gBrowser.addTab("about:mozilla");
-  tab1.addEventListener("load", mainPart, true);
+  tab1.linkedBrowser.addEventListener("load", mainPart, true);
   waitForExplicitFinish();
 
   function mainPart() {
+    tab1.linkedBrowser.removeEventListener("load", mainPart, true);
+
     // Tell the session storer that the tab is pinned
     let newTabState = '{"entries":[{"url":"about:robots"}],"pinned":true,"userTypedValue":"Hello World!"}';
     let ss = Cc["@mozilla.org/browser/sessionstore;1"]
                .getService(Ci.nsISessionStore);
     ss.setTabState(tab1, newTabState);
 
     // Undo pinning
     gBrowser.unpinTab(tab1);
--- a/browser/components/sessionstore/test/browser/browser_579879.js
+++ b/browser/components/sessionstore/test/browser/browser_579879.js
@@ -1,15 +1,17 @@
 function test() {
   waitForExplicitFinish();
 
   var tab1 = gBrowser.addTab("data:text/plain,foo");
   gBrowser.pinTab(tab1);
 
   tab1.linkedBrowser.addEventListener("load", function () {
+    tab1.linkedBrowser.removeEventListener("load", arguments.callee, true);
+
     var tab2 = gBrowser.addTab();
     gBrowser.pinTab(tab2);
 
     is(Array.indexOf(gBrowser.tabs, tab1), 0, "pinned tab 1 is at the first position");
     gBrowser.removeTab(tab1);
     tab1 = undoCloseTab();
     ok(tab1.pinned, "pinned tab 1 has been restored as a pinned tab");
     is(Array.indexOf(gBrowser.tabs, tab1), 0, "pinned tab 1 has been restored to the first position");
--- a/browser/components/sessionstore/test/browser/browser_580512.js
+++ b/browser/components/sessionstore/test/browser/browser_580512.js
@@ -39,16 +39,17 @@ function checkSecondWin(win) {
 function openWinWithCb(cb, argURIs, expectedURIs) {
   if (!expectedURIs)
     expectedURIs = argURIs;
 
   var win = openDialog("chrome://browser/content/", "_blank",
                        "chrome,all,dialog=no", argURIs.join("|"));
 
   win.addEventListener("load", function () {
+    win.removeEventListener("load", arguments.callee, false);
     info("the window loaded");
 
     var expectedLoads = expectedURIs.length;
 
     win.gBrowser.addTabsProgressListener({
       onStateChange: function (aBrowser, aWebProgress, aRequest, aStateFlags, aStatus) {
         if (aRequest &&
             aStateFlags & Ci.nsIWebProgressListener.STATE_STOP &&
--- a/browser/components/sessionstore/test/browser/browser_589246.js
+++ b/browser/components/sessionstore/test/browser/browser_589246.js
@@ -201,17 +201,20 @@ function onStateRestored(aSubject, aTopi
 
     newWin.gBrowser.selectedBrowser.addEventListener("load", function() {
       newWin.gBrowser.selectedBrowser.removeEventListener("load", arguments.callee, true);
 
       // pin this tab
       if (shouldPinTab)
         newWin.gBrowser.pinTab(newWin.gBrowser.selectedTab);
 
-      newWin.addEventListener("unload", onWindowUnloaded, false);
+      newWin.addEventListener("unload", function () {
+        newWin.removeEventListener("unload", arguments.callee, false);
+        onWindowUnloaded();
+      }, false);
       // Open a new tab as well. On Windows/Linux this will be restored when the
       // new window is opened below (in onWindowUnloaded). On OS X we'll just
       // restore the pinned tabs, leaving the unpinned tab in the closedWindowsData.
       if (shouldOpenTabs) {
         let newTab = newWin.gBrowser.addTab("about:config");
         let newTab2 = newWin.gBrowser.addTab("about:buildconfig");
 
         newTab.linkedBrowser.addEventListener("load", function() {
@@ -252,16 +255,18 @@ function onWindowUnloaded() {
   let previousClosedWindowData = ss.getClosedWindowData();
 
   // Now we want to open a new window
   let newWin = openDialog(location, "_blank", "chrome,all,dialog=no", "about:robots");
   newWin.addEventListener("load", function(aEvent) {
     newWin.removeEventListener("load", arguments.callee, false);
 
     newWin.gBrowser.selectedBrowser.addEventListener("load", function () {
+      newWin.gBrowser.selectedBrowser.removeEventListener("load", arguments.callee, true);
+
       // Good enough for checking the state
       afterTestCallback(previousClosedWindowData, ss.getClosedWindowData());
       afterTestCleanup(newWin);
     }, true);
 
   }, false);
 }
 
--- a/browser/components/sessionstore/test/browser/browser_597071.js
+++ b/browser/components/sessionstore/test/browser/browser_597071.js
@@ -68,28 +68,31 @@ function test() {
 
   // set this window to be a popup.
   ss.setWindowState(window, JSON.stringify(popupState), true);
 
   // open a new non-popup window
   let newWin = openDialog(location, "", "chrome,all,dialog=no", "http://example.com");
   newWin.addEventListener("load", function(aEvent) {
     newWin.removeEventListener("load", arguments.callee, false);
+
     newWin.gBrowser.addEventListener("load", function(aEvent) {
       newWin.gBrowser.removeEventListener("load", arguments.callee, true);
 
       newWin.gBrowser.addTab().linkedBrowser.stop();
       // make sure there are 2 windows open
       is(browserWindowsCount(), 2, "there should be 2 windows open currently");
       // make sure sessionstore sees this window
       let state = JSON.parse(ss.getBrowserState());
       is(state.windows.length, 2, "sessionstore knows about this window");
 
       newWin.close();
       newWin.addEventListener("unload", function(aEvent) {
+        newWin.removeEventListener("unload", arguments.callee, false);
+
         is(ss.getClosedWindowCount(), closedWindowCount + 1,
            "increased closed window count");
         is(browserWindowsCount(), 1, "there should be 1 window open currently");
 
         try {
           Services.prefs.clearUserPref("browser.sessionstore.max_windows_undo");
         } catch (e) {}
         ss.setBrowserState(currentState);
--- a/browser/components/sessionstore/test/browser/browser_615394-SSWindowState_events.js
+++ b/browser/components/sessionstore/test/browser/browser_615394-SSWindowState_events.js
@@ -287,21 +287,23 @@ function test_setWindowState() {
 function test_setBrowserState() {
   // We'll track events per window so we are sure that they are each happening once
   // pre window.
   let windowEvents = {};
   windowEvents[getOuterWindowID(window)] = { busyEventCount: 0, readyEventCount: 0 };
 
   // waitForBrowserState does it's own observing for windows, but doesn't attach
   // the listeners we want here, so do it ourselves.
+  let newWindow;
   function windowObserver(aSubject, aTopic, aData) {
     if (aTopic == "domwindowopened") {
-      let newWindow = aSubject.QueryInterface(Ci.nsIDOMWindow);
+      newWindow = aSubject.QueryInterface(Ci.nsIDOMWindow);
       newWindow.addEventListener("load", function() {
         newWindow.removeEventListener("load", arguments.callee, false);
+
         Services.ww.unregisterNotification(windowObserver);
 
         windowEvents[getOuterWindowID(newWindow)] = { busyEventCount: 0, readyEventCount: 0 };
 
         newWindow.addEventListener("SSWindowStateBusy", onSSWindowStateBusy, false);
         newWindow.addEventListener("SSWindowStateReady", onSSWindowStateReady, false);
       }, false);
     }
@@ -327,16 +329,18 @@ function test_setBrowserState() {
       is(winEvents.readyEventCount, 1,
          "[test_setBrowserState] window" + id + " ready event count correct");
       checkedWindows++;
     }
     is(checkedWindows, 2,
        "[test_setBrowserState] checked 2 windows");
     window.removeEventListener("SSWindowStateBusy", onSSWindowStateBusy, false);
     window.removeEventListener("SSWindowStateReady", onSSWindowStateReady, false);
+    newWindow.removeEventListener("SSWindowStateBusy", onSSWindowStateBusy, false);
+    newWindow.removeEventListener("SSWindowStateReady", onSSWindowStateReady, false);
     runNextTest();
   });
 }
 
 
 function test_undoCloseWindow() {
   let newWindow, reopenedWindow;
 
@@ -352,16 +356,17 @@ function test_undoCloseWindow() {
     // Close the window which isn't window
     newWindow.close();
     reopenedWindow = ss.undoCloseWindow(0);
     reopenedWindow.addEventListener("SSWindowStateBusy", onSSWindowStateBusy, false);
     reopenedWindow.addEventListener("SSWindowStateReady", onSSWindowStateReady, false);
 
     reopenedWindow.addEventListener("load", function() {
       reopenedWindow.removeEventListener("load", arguments.callee, false);
+
       reopenedWindow.gBrowser.tabContainer.addEventListener("SSTabRestored", onSSTabRestored, false);
     }, false);
   });
 
   let busyEventCount = 0,
       readyEventCount = 0,
       tabRestoredCount = 0;
   // These will listen to the reopened closed window...
--- a/browser/components/shell/test/browser_420786.js
+++ b/browser/components/shell/test/browser_420786.js
@@ -1,14 +1,16 @@
 const DG_BACKGROUND = "/desktop/gnome/background"
 const DG_IMAGE_KEY = DG_BACKGROUND + "/picture_filename";
 const DG_OPTION_KEY = DG_BACKGROUND + "/picture_options";
 const DG_DRAW_BG_KEY = DG_BACKGROUND + "/draw_background";
 
 function onPageLoad() {
+  gBrowser.selectedBrowser.removeEventListener("load", onPageLoad, true);
+
   var bs = Cc["@mozilla.org/intl/stringbundle;1"].
            getService(Ci.nsIStringBundleService);
   var brandName = bs.createBundle("chrome://branding/locale/brand.properties").
                   GetStringFromName("brandShortName");
 
   var dirSvc = Cc["@mozilla.org/file/directory_service;1"].
                getService(Ci.nsIDirectoryServiceProvider);
   var homeDir = dirSvc.getFile("Home", {});
--- a/browser/components/test/browser/browser_bug538331.js
+++ b/browser/components/test/browser/browser_bug538331.js
@@ -160,17 +160,20 @@ var gWindowCatcher = {
 
   observe: function(subject, topic, data) {
     if (topic != "domwindowopened")
       return;
 
     this.windowsOpen++;
     let win = subject.QueryInterface(Ci.nsIDOMWindow);
     info("window catcher caught window opening: " + win.document.documentURI);
-    win.addEventListener("load", this.windowLoad.bind(this, win), false);
+    win.addEventListener("load", function () {
+      win.removeEventListener("load", arguments.callee, false);
+      gWindowCatcher.windowLoad(win);
+    }, false);
   }
 };
 
 function finish_test()
 {
   // Reset browser.startup.homepage_override.mstone to the original value or
   // clear it if it didn't exist.
   if (gOriginalMStone) {
@@ -352,17 +355,20 @@ function testShowNotification()
           }
         }
         // The last test opens an url and verifies the url from the updates.xml
         // is correct.
         if (i == (BG_NOTIFY_TESTS.length - 1)) {
           // Wait for any windows caught by the windowcatcher to close
           gWindowCatcher.finish(function () {
             button.click();
-            gBrowser.selectedBrowser.addEventListener("load", testNotificationURL, true);
+            gBrowser.selectedBrowser.addEventListener("load", function () {
+              gBrowser.selectedBrowser.removeEventListener("load", arguments.callee, true);
+              testNotificationURL();
+            }, true);
           });
         } else {
           notifyBox.removeAllNotifications(true);
         }
       } else if (i == (BG_NOTIFY_TESTS.length - 1)) {
         // If updateBox is null the test has already reported errors so bail
         finish_test();
       }
--- a/browser/locales/en-US/chrome/browser/aboutDialog.dtd
+++ b/browser/locales/en-US/chrome/browser/aboutDialog.dtd
@@ -55,26 +55,8 @@
 <!ENTITY update.downloading.start   "Downloading update — ">
 <!ENTITY update.downloading.end     "">
 
 <!-- LOCALIZATION NOTE (channel.description.start,channel.description.end): channel.description.start and
      channel.description.end create one sentence, with the current channel label inserted in between.
      example: You are currently on the _Stable_ update channel. -->
 <!ENTITY channel.description.start  "You are currently on the ">
 <!ENTITY channel.description.end    " update channel. ">
-
-<!ENTITY channel.change             "Change">
-
-<!ENTITY channel.release.description       "Enjoy the tried and tested final release being used by hundreds of millions around the world. Stay in control of your online experience with super speed, easy customization and the latest Web technologies.">
-<!ENTITY channel.beta.description          "Experience cutting edge features with more stability. Provide feedback to help refine and polish what will be in the final release.">
-<!ENTITY channel.aurora.description        "Experience the newest innovations in an unstable environment that's not for the faint of heart. Provide feedback on features and performance to help determine what makes the final release.">
-
-<!-- LOCALIZATION NOTE (channel.selector.start,channel.selector.end): channel.selector.start and
-     channel.selector.end create one sentence, with a channel selection menulist instered in between.
-     This is all in one line, so try to make the localized text short.
-     example: Switch to the [Stable] update channel. -->
-<!ENTITY channel.selector.start          "Switch to the">
-<!ENTITY channel.selector.end            "update channel.">
-
-<!-- LOCALIZATION NOTE (channel.selector.applyButton): This button applies the user's choice to switch
-     to a new update channel and starts the application update process. -->
-<!ENTITY channel.selector.applyButton    "Apply and Update">
-<!ENTITY channel.selector.cancelButton   "Cancel">
--- a/browser/locales/en-US/chrome/browser/aboutRobots.dtd
+++ b/browser/locales/en-US/chrome/browser/aboutRobots.dtd
@@ -18,10 +18,10 @@
 <!-- Book: Hitchhiker's Guide To The Galaxy. What the Sirius Cybernetics Corporation calls robots. -->
 <!ENTITY robots.errorLongDesc3 "Robots are Your Plastic Pal Who's Fun To Be With.">
 <!-- TV: Futurama. Bender's first line is "Bite my shiny metal ass." -->
 <!ENTITY robots.errorLongDesc4 "Robots have shiny metal posteriors which should not be bitten.">
 <!-- TV: Battlestar Galactica (2004 series). From the opening text. -->
 <!ENTITY robots.errorTrailerDescText "And they have a plan.">
 <!-- TV: Battlestar Galactica (2004 series). Common expletive referring to Cylons. -->
 <!ENTITY robots.imgtitle "Frakkin' Toasters">
-<!-- Book: Hitchiker's Guide To The Galaxy. Arthur presses a button and it warns him. -->
+<!-- Book: Hitchhiker's Guide To The Galaxy. Arthur presses a button and it warns him. -->
 <!ENTITY robots.dontpress "Please do not press this button again.">
--- a/browser/locales/en-US/chrome/browser/preferences/aboutPermissions.dtd
+++ b/browser/locales/en-US/chrome/browser/preferences/aboutPermissions.dtd
@@ -17,19 +17,19 @@
 <!ENTITY permission.allow                "Allow">
 <!ENTITY permission.allowForSession      "Allow for Session">
 <!ENTITY permission.block                "Block">
 
 <!ENTITY password.label                  "Store Passwords">
 <!ENTITY password.manage                 "Manage Passwords…">
 
 <!ENTITY cookie.label                    "Set Cookies">
-<!ENTITY cookie.clear                    "Clear Cookies">
+<!ENTITY cookie.remove                   "Remove Cookies">
 <!ENTITY cookie.manage                   "Manage Cookies…">
-<!ENTITY cookie.clearAll                 "Clear All Cookies">
+<!ENTITY cookie.removeAll                "Remove All Cookies">
 
 <!ENTITY geo.label                       "Share Location">
 
 <!-- LOCALIZATION NOTE (indexedDB.label): This is describing indexedDB storage
      using the same language used for the permIndexedDB string in browser/pageInfo.dtd -->
 <!ENTITY indexedDB.label                 "Maintain Offline Storage">
 
 <!ENTITY popup.label                     "Open Pop-up Windows">
--- a/browser/locales/en-US/chrome/browser/preferences/privacy.dtd
+++ b/browser/locales/en-US/chrome/browser/preferences/privacy.dtd
@@ -56,18 +56,18 @@
 <!ENTITY  dontrememberDescription.label  "&brandShortName; will use the same settings as private browsing, and will not remember any history as you browse the Web.">
 
 <!-- LOCALIZATION NOTE (dontrememberActions.pre.label): include a trailing space as needed -->
 <!-- LOCALIZATION NOTE (dontrememberActions.post.label): include a starting space as needed -->
 <!ENTITY  dontrememberActions.pre.label          "You may also want to ">
 <!ENTITY  dontrememberActions.clearHistory.label "clear all current history">
 <!ENTITY  dontrememberActions.post.label         ".">
 
-<!ENTITY  privateBrowsingPermanent.label "Permanent Private Browsing mode">
-<!ENTITY  privateBrowsingPermanent.accesskey "P">
+<!ENTITY  privateBrowsingPermanent2.label "Always use private browsing mode">
+<!ENTITY  privateBrowsingPermanent2.accesskey "p">
 
 <!ENTITY  rememberHistory.label      "Remember my browsing history">
 <!ENTITY  rememberHistory.accesskey  "b">
 
 <!ENTITY  rememberDownload.label         "Remember download history">
 <!ENTITY  rememberDownload.accesskey     "d">
 
 <!ENTITY  rememberSearchForm.label       "Remember search and form history">
--- a/browser/locales/en-US/chrome/overrides/appstrings.properties
+++ b/browser/locales/en-US/chrome/overrides/appstrings.properties
@@ -58,9 +58,10 @@ externalProtocolTitle=External Protocol 
 externalProtocolPrompt=An external application must be launched to handle %1$S: links.\n\n\nRequested link:\n\n%2$S\n\nApplication: %3$S\n\n\nIf you were not expecting this request it may be an attempt to exploit a weakness in that other program. Cancel this request unless you are sure it is not malicious.\n
 #LOCALIZATION NOTE (externalProtocolUnknown): The following string is shown if the application name can't be determined
 externalProtocolUnknown=<Unknown>
 externalProtocolChkMsg=Remember my choice for all links of this type.
 externalProtocolLaunchBtn=Launch application
 malwareBlocked=The site at %S has been reported as an attack site and has been blocked based on your security preferences.
 phishingBlocked=The web site at %S has been reported as a web forgery designed to trick users into sharing personal or financial information.
 cspFrameAncestorBlocked=This page has a content security policy that prevents it from being embedded in this way.
+corruptedContentError=The page you are trying to view cannot be shown because an error in the data transmission was detected.
 remoteXUL=This page uses an unsupported technology that is no longer available by default in Firefox.
--- a/browser/locales/en-US/chrome/overrides/netError.dtd
+++ b/browser/locales/en-US/chrome/overrides/netError.dtd
@@ -166,16 +166,20 @@ be temporary, and you can try again late
 <!ENTITY phishingBlocked.longDesc "
 <p>Entering any personal information on this page may result in identity theft or other fraud.</p>
 <p>These types of web forgeries are used in scams known as phishing attacks, in which fraudulent web pages and emails are used to imitate sources you may trust.</p>
 ">
 
 <!ENTITY cspFrameAncestorBlocked.title "Blocked by Content Security Policy">
 <!ENTITY cspFrameAncestorBlocked.longDesc "<p>&brandShortName; prevented this page from loading in this way because the page has a content security policy that disallows it.</p>">
 
+<!ENTITY corruptedContentError.title "Corrupted Content Error">
+<!ENTITY corruptedContentError.longDesc "<p>The page you are trying to view cannot be shown because an error in the data transmission was detected.</p><ul><li>Please contact the website owners to inform them of this problem.</li></ul>">
+
+
 <!ENTITY securityOverride.linkText "Or you can add an exception…">
 <!ENTITY securityOverride.getMeOutOfHereButton "Get me out of here!">
 <!ENTITY securityOverride.exceptionButtonLabel "Add Exception…">
 
 <!-- LOCALIZATION NOTE (securityOverride.warningContent) - Do not translate the
 contents of the <button> tags. It uses strings already defined above. The
 button is included here (instead of netError.xhtml) because it exposes
 functionality specific to firefox. -->
deleted file mode 100644
index 2f4ed89d0cd7c03c8348342a5bb4a72ca9ac8cda..0000000000000000000000000000000000000000
GIT binary patch
literal 0
Hc$@<O00001
--- a/browser/themes/pinstripe/browser/jar.mn
+++ b/browser/themes/pinstripe/browser/jar.mn
@@ -37,17 +37,16 @@ browser.jar:
   skin/classic/browser/reload-stop-go.png
   skin/classic/browser/searchbar-dropmarker.png
   skin/classic/browser/searchbar.css
   skin/classic/browser/Search.png
   skin/classic/browser/section_collapsed.png
   skin/classic/browser/section_collapsed-rtl.png
   skin/classic/browser/section_expanded.png
   skin/classic/browser/Secure-Glyph-White.png
-  skin/classic/browser/Secure-background.gif
   skin/classic/browser/Toolbar.png
   skin/classic/browser/toolbarbutton-dropmarker.png
   skin/classic/browser/urlbar-arrow.png
   skin/classic/browser/urlbar-popup-blocked.png
   skin/classic/browser/feeds/subscribe.css                  (feeds/subscribe.css)
   skin/classic/browser/feeds/subscribe-ui.css               (feeds/subscribe-ui.css)
   skin/classic/browser/feeds/feedIcon.png                   (feeds/feedIcon.png)
   skin/classic/browser/feeds/feedIcon16.png                 (feeds/feedIcon16.png)
--- a/build/automation.py.in
+++ b/build/automation.py.in
@@ -329,16 +329,17 @@ class Automation(object):
     # Set up permissions database
     locations = self.readLocations()
     self.setupPermissionsDatabase(profileDir,
       {'allowXULXBL':[(l.host, 'noxul' not in l.options) for l in locations]});
 
     part = """\
 user_pref("browser.console.showInPanel", true);
 user_pref("browser.dom.window.dump.enabled", true);
+user_pref("browser.firstrun.show.localepicker", false);
 user_pref("dom.allow_scripts_to_close_windows", true);
 user_pref("dom.disable_open_during_load", false);
 user_pref("dom.max_script_run_time", 0); // no slow script dialogs
 user_pref("dom.max_chrome_script_run_time", 0);
 user_pref("dom.popup_maximum", -1);
 user_pref("dom.send_after_paint_to_content", true);
 user_pref("dom.successive_dialog_time_limit", 0);
 user_pref("signed.applets.codebase_principal_support", true);
--- a/build/unix/elfhack/elf.cpp
+++ b/build/unix/elfhack/elf.cpp
@@ -36,17 +36,17 @@
  * ***** END LICENSE BLOCK ***** */
 
 #undef NDEBUG
 #include <cstring>
 #include <assert.h>
 #include "elfxx.h"
 
 template <class endian, typename R, typename T>
-inline void Elf_Ehdr_Traits::swap(T &t, R &r)
+void Elf_Ehdr_Traits::swap(T &t, R &r)
 {
     memcpy(r.e_ident, t.e_ident, sizeof(r.e_ident));
     r.e_type = endian::swap(t.e_type);
     r.e_machine = endian::swap(t.e_machine);
     r.e_version = endian::swap(t.e_version);
     r.e_entry = endian::swap(t.e_entry);
     r.e_phoff = endian::swap(t.e_phoff);
     r.e_shoff = endian::swap(t.e_shoff);
@@ -55,52 +55,52 @@ inline void Elf_Ehdr_Traits::swap(T &t, 
     r.e_phentsize = endian::swap(t.e_phentsize);
     r.e_phnum = endian::swap(t.e_phnum);
     r.e_shentsize = endian::swap(t.e_shentsize);
     r.e_shnum = endian::swap(t.e_shnum);
     r.e_shstrndx = endian::swap(t.e_shstrndx);
 }
 
 template <class endian, typename R, typename T>
-inline void Elf_Phdr_Traits::swap(T &t, R &r)
+void Elf_Phdr_Traits::swap(T &t, R &r)
 {
     r.p_type = endian::swap(t.p_type);
     r.p_offset = endian::swap(t.p_offset);
     r.p_vaddr = endian::swap(t.p_vaddr);
     r.p_paddr = endian::swap(t.p_paddr);
     r.p_filesz = endian::swap(t.p_filesz);
     r.p_memsz = endian::swap(t.p_memsz);
     r.p_flags = endian::swap(t.p_flags);
     r.p_align = endian::swap(t.p_align);
 }
 
 template <class endian, typename R, typename T>
-inline void Elf_Shdr_Traits::swap(T &t, R &r)
+void Elf_Shdr_Traits::swap(T &t, R &r)
 {
     r.sh_name = endian::swap(t.sh_name);
     r.sh_type = endian::swap(t.sh_type);
     r.sh_flags = endian::swap(t.sh_flags);
     r.sh_addr = endian::swap(t.sh_addr);
     r.sh_offset = endian::swap(t.sh_offset);
     r.sh_size = endian::swap(t.sh_size);
     r.sh_link = endian::swap(t.sh_link);
     r.sh_info = endian::swap(t.sh_info);
     r.sh_addralign = endian::swap(t.sh_addralign);
     r.sh_entsize = endian::swap(t.sh_entsize);
 }
 
 template <class endian, typename R, typename T>
-inline void Elf_Dyn_Traits::swap(T &t, R &r)
+void Elf_Dyn_Traits::swap(T &t, R &r)
 {
     r.d_tag = endian::swap(t.d_tag);
     r.d_un.d_val = endian::swap(t.d_un.d_val);
 }
 
 template <class endian, typename R, typename T>
-inline void Elf_Sym_Traits::swap(T &t, R &r)
+void Elf_Sym_Traits::swap(T &t, R &r)
 {
     r.st_name = endian::swap(t.st_name);
     r.st_value = endian::swap(t.st_value);
     r.st_size = endian::swap(t.st_size);
     r.st_info = t.st_info;
     r.st_other = t.st_other;
     r.st_shndx = endian::swap(t.st_shndx);
 }
@@ -113,24 +113,24 @@ struct _Rel_info {
         r = endian::swap(ELF32_R_INFO(ELF64_R_SYM(t), ELF64_R_TYPE(t)));
     }
     static inline void swap(Elf32_Word &t, Elf64_Xword &r) {
         r = endian::swap(ELF64_R_INFO(ELF32_R_SYM(t), ELF32_R_TYPE(t)));
     }
 };
 
 template <class endian, typename R, typename T>
-inline void Elf_Rel_Traits::swap(T &t, R &r)
+void Elf_Rel_Traits::swap(T &t, R &r)
 {
     r.r_offset = endian::swap(t.r_offset);
     _Rel_info<endian>::swap(t.r_info, r.r_info);
 }
 
 template <class endian, typename R, typename T>
-inline void Elf_Rela_Traits::swap(T &t, R &r)
+void Elf_Rela_Traits::swap(T &t, R &r)
 {
     r.r_offset = endian::swap(t.r_offset);
     _Rel_info<endian>::swap(t.r_info, r.r_info);
     r.r_addend = endian::swap(t.r_addend);
 }
 
 static const Elf32_Shdr null32_section =
     { 0, SHT_NULL, 0, 0, 0, 0, SHN_UNDEF, 0, 0, 0 };
--- a/caps/src/nsScriptSecurityManager.cpp
+++ b/caps/src/nsScriptSecurityManager.cpp
@@ -2794,17 +2794,19 @@ nsScriptSecurityManager::RequestCapabili
                                            const char *capability, PRInt16* canEnable)
 {
     if (NS_FAILED(aPrincipal->CanEnableCapability(capability, canEnable)))
         return NS_ERROR_FAILURE;
     if (*canEnable == nsIPrincipal::ENABLE_WITH_USER_PERMISSION)
     {
         // Prompt user for permission to enable capability.
         JSContext* cx = GetCurrentJSContext();
-        PRBool remember;
+        // The actual value is irrelevant but we shouldn't be handing out
+        // malformed JSBools to XPConnect.
+        PRBool remember = PR_FALSE;
         if (CheckConfirmDialog(cx, aPrincipal, capability, &remember))
             *canEnable = nsIPrincipal::ENABLE_GRANTED;
         else
             *canEnable = nsIPrincipal::ENABLE_DENIED;
         if (remember)
         {
             //-- Save principal to prefs and to mPrincipals
             if (NS_FAILED(aPrincipal->SetCanEnableCapability(capability, *canEnable)))
--- a/chrome/src/nsChromeRegistry.h
+++ b/chrome/src/nsChromeRegistry.h
@@ -111,17 +111,17 @@ public:
   static nsresult Canonify(nsIURL* aChromeURL);
 
 protected:
   void FlushSkinCaches();
   void FlushAllCaches();
 
   // Update the selected locale used by the chrome registry, and fire a
   // notification about this change
-  virtual void UpdateSelectedLocale() = 0;
+  virtual nsresult UpdateSelectedLocale() = 0;
 
   static void LogMessage(const char* aMsg, ...);
   static void LogMessageWithContext(nsIURI* aURL, PRUint32 aLineNumber, PRUint32 flags,
                                     const char* aMsg, ...);
 
   virtual nsIURI* GetBaseURIFromPackage(const nsCString& aPackage,
                                         const nsCString& aProvider,
                                         const nsCString& aPath) = 0;
--- a/chrome/src/nsChromeRegistryChrome.cpp
+++ b/chrome/src/nsChromeRegistryChrome.cpp
@@ -363,22 +363,19 @@ nsChromeRegistryChrome::Observe(nsISuppo
   if (!strcmp(NS_PREFBRANCH_PREFCHANGE_TOPIC_ID, aTopic)) {
     nsCOMPtr<nsIPrefBranch> prefs (do_QueryInterface(aSubject));
     NS_ASSERTION(prefs, "Bad observer call!");
 
     NS_ConvertUTF16toUTF8 pref(someData);
 
     if (pref.EqualsLiteral(MATCH_OS_LOCALE_PREF) ||
         pref.EqualsLiteral(SELECTED_LOCALE_PREF)) {
-      if (!mProfileLoaded) {
-        rv = SelectLocaleFromPref(prefs);
-        if (NS_FAILED(rv))
-          return rv;
-      }
-      FlushAllCaches();
+        rv = UpdateSelectedLocale();
+        if (NS_SUCCEEDED(rv) && mProfileLoaded)
+          FlushAllCaches();
     }
     else if (pref.EqualsLiteral(SELECTED_SKIN_PREF)) {
       nsXPIDLCString provider;
       rv = prefs->GetCharPref(pref.get(), getter_Copies(provider));
       if (NS_FAILED(rv)) {
         NS_ERROR("Couldn't get new skin pref!");
         return rv;
       }
@@ -421,29 +418,32 @@ nsChromeRegistryChrome::CheckForNewChrom
   mOverlayHash.Clear();
   mStyleHash.Clear();
   mOverrideTable.Clear();
 
   nsComponentManagerImpl::gComponentManager->RereadChromeManifests();
   return NS_OK;
 }
 
-void nsChromeRegistryChrome::UpdateSelectedLocale()
+nsresult nsChromeRegistryChrome::UpdateSelectedLocale()
 {
+  nsresult rv = NS_OK;
   nsCOMPtr<nsIPrefBranch> prefs(do_GetService(NS_PREFSERVICE_CONTRACTID));
   if (prefs) {
-    nsresult rv = SelectLocaleFromPref(prefs);
+    rv = SelectLocaleFromPref(prefs);
     if (NS_SUCCEEDED(rv)) {
       nsCOMPtr<nsIObserverService> obsSvc =
         mozilla::services::GetObserverService();
       NS_ASSERTION(obsSvc, "Couldn't get observer service.");
       obsSvc->NotifyObservers((nsIChromeRegistry*) this,
                               "selected-locale-has-changed", nsnull);
     }
   }
+
+  return rv;
 }
 
 static void
 SerializeURI(nsIURI* aURI,
              SerializedURI& aSerializedURI)
 {
   if (!aURI)
     return;
--- a/chrome/src/nsChromeRegistryChrome.h
+++ b/chrome/src/nsChromeRegistryChrome.h
@@ -78,17 +78,17 @@ class nsChromeRegistryChrome : public ns
   void SendRegisteredChrome(mozilla::dom::PContentParent* aChild);
 
  private:
   static PLDHashOperator CollectPackages(PLDHashTable *table,
                                          PLDHashEntryHdr *entry,
                                          PRUint32 number, void *arg);
 
   nsresult SelectLocaleFromPref(nsIPrefBranch* prefs);
-  NS_OVERRIDE void UpdateSelectedLocale();
+  NS_OVERRIDE nsresult UpdateSelectedLocale();
   NS_OVERRIDE nsIURI* GetBaseURIFromPackage(const nsCString& aPackage,
                                              const nsCString& aProvider,
                                              const nsCString& aPath);
   NS_OVERRIDE nsresult GetFlagsFromPackage(const nsCString& aPackage,
                                            PRUint32* aFlags);
 
   static const PLDHashTableOps kTableOps;
   static PLDHashNumber HashKey(PLDHashTable *table, const void *key);
--- a/chrome/src/nsChromeRegistryContent.cpp
+++ b/chrome/src/nsChromeRegistryContent.cpp
@@ -273,19 +273,19 @@ nsChromeRegistryContent::GetStyleOverlay
 
 NS_IMETHODIMP
 nsChromeRegistryContent::GetXULOverlays(nsIURI *aChromeURL,
                                         nsISimpleEnumerator **aResult)
 {
   CONTENT_NOT_IMPLEMENTED();
 }
 
-void nsChromeRegistryContent::UpdateSelectedLocale()
+nsresult nsChromeRegistryContent::UpdateSelectedLocale()
 {
-  CONTENT_NOTREACHED();
+  CONTENT_NOT_IMPLEMENTED();
 }
 
 void
 nsChromeRegistryContent::ManifestContent(ManifestProcessingContext& cx,
                                          int lineno, char *const * argv,
                                          bool platform, bool contentaccessible)
 {
   CONTENT_NOTREACHED();
--- a/chrome/src/nsChromeRegistryContent.h
+++ b/chrome/src/nsChromeRegistryContent.h
@@ -84,17 +84,17 @@ class nsChromeRegistryContent : public n
     nsCOMPtr<nsIURI> skinBaseURI;
     PRUint32         flags;
   };
   
   void RegisterPackage(const ChromePackage& aPackage);
   void RegisterResource(const ResourceMapping& aResource);
   void RegisterOverride(const OverrideMapping& aOverride);
 
-  NS_OVERRIDE void UpdateSelectedLocale();
+  NS_OVERRIDE nsresult UpdateSelectedLocale();
   NS_OVERRIDE nsIURI* GetBaseURIFromPackage(const nsCString& aPackage,
                                  const nsCString& aProvider,
                                  const nsCString& aPath);
   NS_OVERRIDE nsresult GetFlagsFromPackage(const nsCString& aPackage, PRUint32* aFlags);
 
   nsClassHashtable<nsCStringHashKey, PackageEntry> mPackagesHash;
   nsCString mLocale;
 
--- a/config/autoconf.mk.in
+++ b/config/autoconf.mk.in
@@ -248,17 +248,16 @@ MOZ_LIBVPX_INCLUDES = @MOZ_LIBVPX_INCLUD
 MOZ_NATIVE_ZLIB	= @SYSTEM_ZLIB@
 MOZ_NATIVE_BZ2	= @SYSTEM_BZ2@
 MOZ_NATIVE_JPEG	= @SYSTEM_JPEG@
 MOZ_NATIVE_PNG	= @SYSTEM_PNG@
 MOZ_TREE_CAIRO = @MOZ_TREE_CAIRO@
 MOZ_TREE_PIXMAN = @MOZ_TREE_PIXMAN@
 
 MOZ_UPDATE_XTERM = @MOZ_UPDATE_XTERM@
-MOZ_MATHML = @MOZ_MATHML@
 MOZ_CSS_ANIMATIONS = @MOZ_CSS_ANIMATIONS@
 MOZ_PERMISSIONS = @MOZ_PERMISSIONS@
 MOZ_XTF = @MOZ_XTF@
 MOZ_SVG_DLISTS = @MOZ_SVG_DLISTS@
 MOZ_CAIRO_CFLAGS = @MOZ_CAIRO_CFLAGS@
 MOZ_SMIL = @MOZ_SMIL@
 MOZ_XSLT_STANDALONE = @MOZ_XSLT_STANDALONE@
 
--- a/configure.in
+++ b/configure.in
@@ -2204,18 +2204,16 @@ ia64*-hpux*)
 
     MOZ_GFX_OPTIMIZE_MOBILE=1
     # If we're building with --enable-profiling, we need a frame pointer.
     if test -z "$MOZ_PROFILING"; then
         MOZ_OPTIMIZE_FLAGS="-Os -freorder-blocks -fno-reorder-functions -fomit-frame-pointer"
     else
         MOZ_OPTIMIZE_FLAGS="-Os -freorder-blocks -fno-reorder-functions -fno-omit-frame-pointer"
     fi
-    # The Maemo builders don't know about this flag
-    MOZ_ARM_VFP_FLAGS="-mfpu=vfp"
     ;;
 
 *-*linux*)
     # Note: both GNU_CC and INTEL_CC are set when using Intel's C compiler.
     # Similarly for GNU_CXX and INTEL_CXX.
     if test "$INTEL_CC" -o "$INTEL_CXX"; then
         # -Os has been broken on Intel's C/C++ compilers for quite a
         # while; Intel recommends against using it.
@@ -3439,51 +3437,16 @@ fi # $no_x
 
 AC_SUBST(XCFLAGS)
 AC_SUBST(XLDFLAGS)
 AC_SUBST(XLIBS)
 AC_SUBST(XEXT_LIBS)
 AC_SUBST(XT_LIBS)
 AC_SUBST(XSS_LIBS)
 
-if test "$CPU_ARCH" = "arm"; then
-  AC_MSG_CHECKING(for ARM SIMD support in compiler)
-  # We try to link so that this also fails when
-  # building with LTO.
-  AC_TRY_LINK([],
-                 [asm("uqadd8 r1, r1, r2");],
-                 result="yes", result="no")
-  AC_MSG_RESULT("$result")
-  if test "$result" = "yes"; then
-      AC_DEFINE(HAVE_ARM_SIMD)
-      HAVE_ARM_SIMD=1
-  fi
-
-  AC_MSG_CHECKING(for ARM NEON support in compiler)
-  _SAVE_CFLAGS="$CFLAGS"
-  if test "$GNU_CC"; then
-    # gcc needs -mfpu=neon to recognize NEON instructions
-    CFLAGS="$CFLAGS -mfpu=neon -mfloat-abi=softfp"
-  fi
-  # We try to link so that this also fails when
-  # building with LTO.
-  AC_TRY_LINK([],
-                 [asm("vadd.i8 d0, d0, d0");],
-                 result="yes", result="no")
-  AC_MSG_RESULT("$result")
-  if test "$result" = "yes"; then
-      AC_DEFINE(HAVE_ARM_NEON)
-      HAVE_ARM_NEON=1
-  fi
-  CFLAGS="$_SAVE_CFLAGS"
-fi # CPU_ARCH = arm
-
-AC_SUBST(HAVE_ARM_SIMD)
-AC_SUBST(HAVE_ARM_NEON)
-
 dnl ========================================================
 dnl = pthread support
 dnl = Start by checking whether the system support pthreads
 dnl ========================================================
 case "$target_os" in
 darwin*)
     USE_PTHREADS=1
     ;;
@@ -4330,39 +4293,39 @@ fi
 
 MOZ_ALLOCATING_FUNCS="strndup posix_memalign memalign valloc"
 AC_CHECK_FUNCS(strndup posix_memalign memalign valloc)
 
 dnl See if compiler supports some gcc-style attributes
 
 AC_CACHE_CHECK(for __attribute__((always_inline)),
                ac_cv_attribute_always_inline,
-               [AC_TRY_COMPILE([],
-                               [inline void f(void) __attribute__((always_inline));],
+               [AC_TRY_COMPILE([inline void f(void) __attribute__((always_inline));],
+                               [],
                                ac_cv_attribute_always_inline=yes,
                                ac_cv_attribute_always_inline=no)])
 
 AC_CACHE_CHECK(for __attribute__((malloc)),
                ac_cv_attribute_malloc,
-               [AC_TRY_COMPILE([],
-                               [void* f(int) __attribute__((malloc));],
+               [AC_TRY_COMPILE([void* f(int) __attribute__((malloc));],
+                               [],
                                ac_cv_attribute_malloc=yes,
                                ac_cv_attribute_malloc=no)])
 
 AC_CACHE_CHECK(for __attribute__((warn_unused_result)),
                ac_cv_attribute_warn_unused,
-               [AC_TRY_COMPILE([],
-                               [int f(void) __attribute__((warn_unused_result));],
+               [AC_TRY_COMPILE([int f(void) __attribute__((warn_unused_result));],
+                               [],
                                ac_cv_attribute_warn_unused=yes,
                                ac_cv_attribute_warn_unused=no)])
 
 AC_CACHE_CHECK(for __attribute__((noreturn)),
                ac_cv_attribute_noreturn,
-               [AC_TRY_COMPILE([],
-                               [void f(void) __attribute__((noreturn));],
+               [AC_TRY_COMPILE([void f(void) __attribute__((noreturn));],
+                               [],
                                ac_cv_attribute_noreturn=yes,
                                ac_cv_attribute_noreturn=no)])
  
 dnl End of C++ language/feature checks
 AC_LANG_C
 
 dnl ========================================================
 dnl =  Internationalization checks
@@ -4797,17 +4760,16 @@ MOZ_ARG_HEADER(Application)
 
 ENABLE_TESTS=1
 MOZ_ACTIVEX_SCRIPTING_SUPPORT=
 MOZ_BRANDING_DIRECTORY=
 MOZ_OFFICIAL_BRANDING=
 MOZ_FEEDS=1
 MOZ_INSTALLER=1
 MOZ_JSDEBUGGER=1
-MOZ_MATHML=1
 MOZ_CSS_ANIMATIONS=1
 MOZ_MORK=
 MOZ_MORKREADER=1
 MOZ_AUTH_EXTENSION=1
 MOZ_NO_ACTIVEX_SUPPORT=1
 MOZ_NO_FAST_LOAD=
 MOZ_OGG=1
 MOZ_RAW=
@@ -4837,17 +4799,16 @@ MOZ_PSM=1
 MOZ_RDF=1
 MOZ_REFLOW_PERF=
 MOZ_SAFE_BROWSING=
 MOZ_HELP_VIEWER=
 MOZ_SPELLCHECK=1
 MOZ_SPLASHSCREEN=
 MOZ_STORAGE=1
 MOZ_SVG_DLISTS=
-MOZ_THUMB2=
 MOZ_TIMELINE=
 MOZ_TOOLKIT_SEARCH=1
 MOZ_UI_LOCALE=en-US
 MOZ_UNIVERSALCHARDET=1
 MOZ_URL_CLASSIFIER=
 MOZ_XSLT_STANDALONE=
 MOZ_XTF=1
 MOZ_XUL=1
@@ -4889,17 +4850,16 @@ case "$target_os" in
 esac
 
 case "${target}" in
     *-android*|*-linuxandroid*)
         NSS_DISABLE_DBM=1
         USE_ARM_KUSER=1
         MOZ_INSTALLER=
         NECKO_WIFI=
-        MOZ_THUMB2=1
         MOZ_THEME_FASTSTRIPE=1
         MOZ_TREE_FREETYPE=1
         MOZ_MEMORY=1
         ;;
 esac
 
 MOZ_ARG_ENABLE_STRING(application,
 [  --enable-application=APP
@@ -6403,27 +6363,16 @@ MOZ_EXTENSIONS=`${PERL} ${srcdir}/build/
 dnl Ensure every extension exists, to avoid mostly-inscrutable error messages
 dnl when trying to build a nonexistent extension.
 for extension in $MOZ_EXTENSIONS; do
     if test ! -d "${srcdir}/extensions/${extension}"; then
         AC_MSG_ERROR([Unrecognized extension provided to --enable-extensions: ${extension}.])
     fi
 done
 
-dnl ========================================================
-dnl MathML on by default
-dnl ========================================================
-MOZ_ARG_DISABLE_BOOL(mathml,
-[  --disable-mathml        Disable MathML support],
-    MOZ_MATHML=,
-    MOZ_MATHML=1 )
-if test "$MOZ_MATHML"; then
-  AC_DEFINE(MOZ_MATHML)
-fi
-
 AC_DEFINE(MOZ_CSS_ANIMATIONS)
 
 dnl ========================================================
 dnl SVG Display Lists
 dnl ========================================================
 if test -n "$MOZ_SVG_DLISTS"; then
   AC_DEFINE(MOZ_SVG_DLISTS)
 fi
@@ -6971,18 +6920,16 @@ if test $MOZ_PLATFORM_MAEMO; then
          if test "$_LIB_FOUND"; then
             MOZ_PLATFORM_MAEMO_LIBS="$MOZ_PLATFORM_MAEMO_LIBS $LIBCONTENTACTION_LIBS"
             MOZ_PLATFORM_MAEMO_CFLAGS="$MOZ_PLATFORM_MAEMO_CFLAGS $LIBCONTENTACTION_CFLAGS"
             MOZ_ENABLE_CONTENTACTION=1
             AC_DEFINE(MOZ_ENABLE_CONTENTACTION)
             AC_SUBST(MOZ_ENABLE_CONTENTACTION)
          fi
       fi
-
-      MOZ_THUMB2=1
    fi
 
    PKG_CHECK_MODULES(LIBLOCATION,liblocation, _LIB_FOUND=1, _LIB_FOUND=)
    MOZ_PLATFORM_MAEMO_LIBS="$MOZ_PLATFORM_MAEMO_LIBS $LIBLOCATION_LIBS"
    MOZ_PLATFORM_MAEMO_CFLAGS="$MOZ_PLATFORM_MAEMO_CFLAGS $LIBLOCATION_CFLAGS"
    if test "$_LIB_FOUND"; then
       MOZ_MAEMO_LIBLOCATION=1
       AC_DEFINE(MOZ_MAEMO_LIBLOCATION)
@@ -7001,90 +6948,214 @@ if test $MOZ_PLATFORM_MAEMO; then
       AC_MSG_WARN([Cannot find maemo-meegotouch-interfaces-dev or libmdatauri-dev. Disabling meegotouch share ui.])
    fi
    AC_SUBST(MOZ_ENABLE_MEEGOTOUCHSHARE)
 
    AC_SUBST(MOZ_PLATFORM_MAEMO_LIBS)
    AC_SUBST(MOZ_PLATFORM_MAEMO_CFLAGS)
 fi
 
-dnl Setup default CPU arch for arm target
-case "$target_cpu" in
-  arm*)
-    MOZ_ARM_ARCH=armv7
-  ;;
+dnl ========================================================
+dnl = ARM toolchain tweaks
+dnl ========================================================
+
+dnl Defaults
+case "${target}" in
+arm-android-eabi)
+    MOZ_THUMB=yes
+    MOZ_ARCH=armv7-a
+    MOZ_FPU=vfp
+    MOZ_FLOAT_ABI=softfp
+    ;;
+arm*-*)
+    if test -n "$MOZ_PLATFORM_MAEMO"; then
+        MOZ_THUMB=no
+        MOZ_ARCH=armv7-a
+        MOZ_FLOAT_ABI=softfp
+    fi
+    if test "$MOZ_PLATFORM_MAEMO" = 6; then
+        MOZ_THUMB=yes
+    fi
+    ;;
+esac
+
+dnl Kept for compatibility with some buildbot mozconfig
+MOZ_ARG_DISABLE_BOOL(thumb2, [], MOZ_THUMB=no, MOZ_THUMB=yes)
+
+MOZ_ARG_WITH_STRING(thumb,
+[  --with-thumb[[=yes|no|toolchain-default]]]
+[                          Use Thumb instruction set (-mthumb)],
+    if test -z "$GNU_CC"; then
+        AC_MSG_ERROR([--with-thumb is not supported on non-GNU toolchains])
+    fi
+    MOZ_THUMB=$withval)
+
+MOZ_ARG_WITH_STRING(thumb-interwork,
+[  --with-thumb-interwork[[=yes|no|toolchain-default]]
+                           Use Thumb/ARM instuctions interwork (-mthumb-interwork)],
+    if test -z "$GNU_CC"; then
+        AC_MSG_ERROR([--with-thumb-interwork is not supported on non-GNU toolchains])
+    fi
+    MOZ_THUMB_INTERWORK=$withval)
+
+MOZ_ARG_WITH_STRING(arch,
+[  --with-arch=[[type|toolchain-default]]
+                           Use specific CPU features (-march=type)],
+    if test -z "$GNU_CC"; then
+        AC_MSG_ERROR([--with-arch is not supported on non-GNU toolchains])
+    fi
+    MOZ_ARCH=$withval)
+
+MOZ_ARG_WITH_STRING(fpu,
+[  --with-fpu=[[type|toolchain-default]]
+                           Use specific FPU type (-mfpu=type)],
+    if test -z "$GNU_CC"; then
+        AC_MSG_ERROR([--with-fpu is not supported on non-GNU toolchains])
+    fi
+    MOZ_FPU=$withval)
+
+MOZ_ARG_WITH_STRING(float-abi,
+[  --with-float-abi=[[type|toolchain-default]]
+                           Use specific arm float ABI (-mfloat-abi=type)],
+    if test -z "$GNU_CC"; then
+        AC_MSG_ERROR([--with-float-abi is not supported on non-GNU toolchains])
+    fi
+    MOZ_FLOAT_ABI=$withval)
+
+MOZ_ARG_WITH_STRING(soft-float,
+[  --with-soft-float[[=yes|no|toolchain-default]]
+                           Use soft float library (-msoft-float)],
+    if test -z "$GNU_CC"; then
+        AC_MSG_ERROR([--with-soft-float is not supported on non-GNU toolchains])
+    fi
+    MOZ_SOFT_FLOAT=$withval)
+
+case "$MOZ_ARCH" in
+toolchain-default|"")
+    arch_flag=""
+    ;;
+*)
+    arch_flag="-march=$MOZ_ARCH"
+    ;;
 esac
-dnl ========================================================
-dnl = Enable building the Thumb2 instruction set
-dnl ========================================================
-MOZ_ARG_ENABLE_BOOL(thumb2,
- [  --enable-thumb2         Enable Thumb2 instruction set (implies ARMv7)],
-    MOZ_THUMB2=1,
-    MOZ_THUMB2=)
-if test -n "$MOZ_THUMB2"; then
-  MOZ_ARM_ARCH=armv7
-fi
-
-dnl ========================================================
-dnl = Enable building for ARM specific CPU features
-dnl ========================================================
-MOZ_ARG_WITH_STRING(cpu-arch,
-[  --with-cpu-arch=arch      Use specific arm architecture CPU features, default armv7],
-    MOZ_ARM_ARCH=$withval)
-
-if test -n "$MOZ_THUMB2"; then
-  case "$target_cpu" in
-    arm*)
-      if test "$MOZ_ARM_ARCH" != "armv7"; then
-        AC_MSG_ERROR([--enable-thumb2 is not compatible with cpu-arch=$MOZ_ARM_ARCH])
-      fi
-      if test "$GNU_CC"; then
-        AC_DEFINE(MOZ_THUMB2)
-        AC_DEFINE(MOZ_ARM_ARCH)
-        CFLAGS="$CFLAGS -march=armv7-a -mthumb -mfloat-abi=softfp $MOZ_ARM_VFP_FLAGS"
-        CXXFLAGS="$CXXFLAGS -march=armv7-a -mthumb -mfloat-abi=softfp $MOZ_ARM_VFP_FLAGS"
-        ASFLAGS="$ASFLAGS -march=armv7-a -mthumb -mfloat-abi=softfp $MOZ_ARM_VFP_FLAGS"
-      else
-        AC_MSG_ERROR([--enable-thumb2 is not supported for non-GNU toolchains])
-      fi
-    ;;
-    *)
-      AC_MSG_ERROR([--enable-thumb2 is not supported for non-ARM CPU architectures])
-    ;;
-  esac
-elif test "$MOZ_ARM_ARCH" = "armv7"; then
-  case "$target_cpu" in
-    arm*)
-      if test "$GNU_CC"; then
-        AC_DEFINE(MOZ_ARM_ARCH)
-        CFLAGS="$CFLAGS -march=armv7-a -marm -mfloat-abi=softfp $MOZ_ARM_VFP_FLAGS"
-        CXXFLAGS="$CXXFLAGS -march=armv7-a -marm -mfloat-abi=softfp $MOZ_ARM_VFP_FLAGS"
-        ASFLAGS="$ASFLAGS -march=armv7-a -marm -mfloat-abi=softfp $MOZ_ARM_VFP_FLAGS"
-      else
-        AC_MSG_ERROR([--with-cpu-arch=armv7 is not supported for non-GNU toolchains])
-      fi
-    ;;
-    *)
-      AC_MSG_ERROR([--with-cpu-arch=armv7 is not supported for non-ARM CPU architectures])
-    ;;
-  esac
-else
-  case "$target_cpu" in
-    arm*)
-      if test "$GNU_CC"; then
-        CFLAGS="$CFLAGS -march=armv5te -mthumb-interwork -msoft-float"
-        CXXFLAGS="$CXXFLAGS -march=armv5te -mthumb-interwork -msoft-float"
-        ASFLAGS="$ASFLAGS -march=armv5te -mthumb-interwork -msoft-float"
-      fi
-      ;;
-  esac
+
+case "$MOZ_THUMB" in
+yes)
+    MOZ_THUMB2=1
+    thumb_flag="-mthumb"
+    ;;
+no)
+    MOZ_THUMB2=
+    thumb_flag="-marm"
+    ;;
+*)
+    _SAVE_CFLAGS="$CFLAGS"
+    CFLAGS="$arch_flag"
+    AC_TRY_COMPILE([],[return sizeof(__thumb2__);],
+        MOZ_THUMB2=1,
+        MOZ_THUMB2=)
+    CFLAGS="$_SAVE_CFLAGS"
+    thumb_flag=""
+    ;;
+esac
+
+if test "$MOZ_THUMB2" = 1; then
+    AC_DEFINE(MOZ_THUMB2)
+fi
+
+case "$MOZ_THUMB_INTERWORK" in
+yes)
+    thumb_interwork_flag="-mthumb-interwork"
+    ;;
+no)
+    thumb_interwork_flag="-mno-thumb-interwork"
+    ;;
+*) # toolchain-default
+    thumb_interwork_flag=""
+    ;;
+esac
+
+case "$MOZ_FPU" in
+toolchain-default|"")
+    fpu_flag=""
+    ;;
+*)
+    fpu_flag="-mfpu=$MOZ_FPU"
+    ;;
+esac
+
+case "$MOZ_FLOAT_ABI" in
+toolchain-default|"")
+    float_abi_flag=""
+    ;;
+*)
+    float_abi_flag="-mfloat-abi=$MOZ_FLOAT_ABI"
+    ;;
+esac
+
+case "$MOZ_SOFT_FLOAT" in
+yes)
+    soft_float_flag="-msoft-float"
+    ;;
+no)
+    soft_float_flag="-mno-soft-float"
+    ;;
+*) # toolchain-default
+    soft_float_flag=""
+    ;;
+esac
+
+dnl Use echo to avoid accumulating space characters
+all_flags=`echo $arch_flag $thumb_flag $thumb_interwork_flag $fpu_flag $float_abi_flag $soft_float_flag`
+if test -n "$all_flags"; then
+    _SAVE_CFLAGS="$CFLAGS"
+    CFLAGS="$all_flags"
+    AC_MSG_CHECKING(whether the chosen combination of compiler flags ($all_flags) works)
+    AC_TRY_COMPILE([],[return 0;],
+        AC_MSG_RESULT([yes]),
+        AC_MSG_ERROR([no]))
+
+    CFLAGS="$_SAVE_CFLAGS $all_flags"
+    CXXFLAGS="$CXXFLAGS $all_flags"
+    ASFLAGS="$ASFLAGS $all_flags"
+    if test -n "$thumb_flag"; then
+        LDFLAGS="$LDFLAGS $thumb_flag"
+    fi
 fi
 
 AC_SUBST(MOZ_THUMB2)
-AC_SUBST(MOZ_ARM_ARCH)
+
+if test "$CPU_ARCH" = "arm"; then
+  AC_MSG_CHECKING(for ARM SIMD support in compiler)
+  # We try to link so that this also fails when
+  # building with LTO.
+  AC_TRY_LINK([],
+                 [asm("uqadd8 r1, r1, r2");],
+                 result="yes", result="no")
+  AC_MSG_RESULT("$result")
+  if test "$result" = "yes"; then
+      AC_DEFINE(HAVE_ARM_SIMD)
+      HAVE_ARM_SIMD=1
+  fi
+
+  AC_MSG_CHECKING(for ARM NEON support in compiler)
+  # We try to link so that this also fails when
+  # building with LTO.
+  AC_TRY_LINK([],
+                 [asm(".fpu neon\n vadd.i8 d0, d0, d0");],
+                 result="yes", result="no")
+  AC_MSG_RESULT("$result")
+  if test "$result" = "yes"; then
+      AC_DEFINE(HAVE_ARM_NEON)
+      HAVE_ARM_NEON=1
+  fi
+fi # CPU_ARCH = arm
+
+AC_SUBST(HAVE_ARM_SIMD)
+AC_SUBST(HAVE_ARM_NEON)
 
 dnl ========================================================
 dnl = faststripe theme
 dnl ========================================================
 MOZ_ARG_ENABLE_BOOL(faststripe,
 [  --enable-faststripe     Use faststripe theme],
     MOZ_THEME_FASTSTRIPE=1,
     MOZ_THEME_FASTSTRIPE= )
@@ -7424,18 +7495,18 @@ dnl ====================================
 MOZ_ARG_ENABLE_BOOL(wrap-malloc,
 [  --enable-wrap-malloc    Wrap malloc calls (gnu linker only)],
     _WRAP_MALLOC=1,
     _WRAP_MALLOC= )
 
 if test -n "$_WRAP_MALLOC"; then
     if test "$GNU_CC"; then
     WRAP_MALLOC_CFLAGS="${LDFLAGS} ${WRAP_MALLOC_CFLAGS} -Wl,--wrap -Wl,malloc -Wl,--wrap -Wl,calloc -Wl,--wrap -Wl,valloc -Wl,--wrap -Wl,free -Wl,--wrap -Wl,realloc -Wl,--wrap -Wl,memalign -Wl,--wrap -Wl,__builtin_new -Wl,--wrap -Wl,__builtin_vec_new -Wl,--wrap -Wl,__builtin_delete -Wl,--wrap -Wl,__builtin_vec_delete -Wl,--wrap -Wl,PR_Free -Wl,--wrap -Wl,PR_Malloc -Wl,--wrap -Wl,PR_Calloc -Wl,--wrap -Wl,PR_Realloc -Wl,--wrap -Wl,strdup -Wl,--wrap -Wl,strndup -Wl,--wrap -Wl,posix_memalign"
-    MKSHLIB='$(CXX) $(DSO_LDOPTS) $(WRAP_MALLOC_CFLAGS) $(WRAP_MALLOC_LIB) -o $@'
-    MKCSHLIB='$(CC) $(DSO_LDOPTS) $(WRAP_MALLOC_CFLAGS) $(WRAP_MALLOC_LIB) -o $@'
+    MKSHLIB="$MKSHLIB"' $(WRAP_MALLOC_CFLAGS) $(WRAP_MALLOC_LIB)'
+    MKCSHLIB="$MKCSHLIB"' $(WRAP_MALLOC_CFLAGS) $(WRAP_MALLOC_LIB)'
     fi
 fi
 
 dnl ========================================================
 dnl = Location of malloc wrapper lib
 dnl ========================================================
 MOZ_ARG_WITH_STRING(wrap-malloc,
 [  --with-wrap-malloc=DIR  Location of malloc wrapper library],
@@ -8744,17 +8815,16 @@ AC_SUBST(IMPLIB)
 AC_SUBST(FILTER)
 AC_SUBST(BIN_FLAGS)
 AC_SUBST(NS_USE_NATIVE)
 AC_SUBST(MOZ_WIDGET_TOOLKIT)
 AC_SUBST(MOZ_UPDATE_XTERM)
 AC_SUBST(MINIMO)
 AC_SUBST(MOZ_PLATFORM_MAEMO)
 AC_SUBST(MOZ_AUTH_EXTENSION)
-AC_SUBST(MOZ_MATHML)
 AC_SUBST(MOZ_CSS_ANIMATIONS)
 AC_SUBST(MOZ_PERMISSIONS)
 AC_SUBST(MOZ_XTF)
 AC_SUBST(MOZ_PREF_EXTENSIONS)
 AC_SUBST(MOZ_SMIL)
 AC_SUBST(MOZ_XSLT_STANDALONE)
 AC_SUBST(MOZ_JS_LIBS)
 AC_SUBST(MOZ_PSM)
@@ -9289,22 +9359,16 @@ HOST_LDFLAGS="$_SUBDIR_HOST_LDFLAGS"
 RC=
 
 unset MAKEFILES
 unset CONFIG_FILES
 
 # No need to run subconfigures when building with LIBXUL_SDK_DIR
 if test "$COMPILE_ENVIRONMENT" -a -z "$LIBXUL_SDK_DIR"; then
 
-if test -n "$MOZ_THUMB2"; then
-  _SUBDIR_CONFIG_ARGS="$_SUBDIR_CONFIG_ARGS --enable-thumb2"
-fi
-if test -n "$MOZ_ARM_ARCH"; then
-  _SUBDIR_CONFIG_ARGS="$_SUBDIR_CONFIG_ARGS --with-cpu-arch=$MOZ_ARM_ARCH"
-fi
 if test -n "$_WRAP_MALLOC"; then
   _SUBDIR_CONFIG_ARGS="$_SUBDIR_CONFIG_ARGS --enable-wrap-malloc"
 fi
 
 if test -z "$MOZ_NATIVE_NSPR"; then
     ac_configure_args="$_SUBDIR_CONFIG_ARGS --with-dist-prefix=$MOZ_BUILD_ROOT/dist --with-mozilla"
     if test -z "$MOZ_DEBUG"; then
         ac_configure_args="$ac_configure_args --disable-debug"
--- a/content/Makefile.in
+++ b/content/Makefile.in
@@ -38,30 +38,26 @@
 DEPTH		= ..
 topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 MODULE		= content
-PARALLEL_DIRS		= base canvas events html smil svg xml xul xbl xslt
+PARALLEL_DIRS		= base canvas events html mathml smil svg xml xul xbl xslt
 
 ifdef MOZ_MEDIA
 PARALLEL_DIRS	+= media
 endif
 
 ifdef MOZ_XTF
 PARALLEL_DIRS   += xtf
 endif
 
-ifdef MOZ_MATHML
-PARALLEL_DIRS   += mathml
-endif
-
 ifdef ENABLE_TESTS
 TOOL_DIRS += test
 endif
 
 # Prevent floating point errors caused by VC++ optimizations
 ifeq ($(OS_ARCH)_$(GNU_CC),WINNT_)
 ifeq (,$(filter-out 1200 1300 1310,$(_MSC_VER)))
 CFLAGS += -Op
--- a/content/base/public/nsContentCreatorFunctions.h
+++ b/content/base/public/nsContentCreatorFunctions.h
@@ -106,21 +106,19 @@ NS_NewHTMLElement(nsIContent** aResult, 
                   mozilla::dom::FromParser aFromParser);
 
 // First argument should be nsHTMLTag, but that adds dependency to parser
 // for a bunch of files.
 already_AddRefed<nsGenericHTMLElement>
 CreateHTMLElement(PRUint32 aNodeType, already_AddRefed<nsINodeInfo> aNodeInfo,
                   mozilla::dom::FromParser aFromParser);
 
-#ifdef MOZ_MATHML
 nsresult
 NS_NewMathMLElement(nsIContent** aResult,
                      already_AddRefed<nsINodeInfo> aNodeInfo);
-#endif
 
 #ifdef MOZ_XUL
 nsresult
 NS_NewXULElement(nsIContent** aResult, already_AddRefed<nsINodeInfo> aNodeInfo);
 
 void
 NS_TrustedNewXULElement(nsIContent** aResult, already_AddRefed<nsINodeInfo> aNodeInfo);
 #endif
--- a/content/base/public/nsDOMFile.h
+++ b/content/base/public/nsDOMFile.h
@@ -59,17 +59,16 @@ class nsIInputStream;
 class nsIClassInfo;
 class nsIBlobBuilder;
 
 nsresult NS_NewBlobBuilder(nsISupports* *aSupports);
 void ParseSize(PRInt64 aSize, PRInt64& aStart, PRInt64& aEnd);
 
 class nsDOMFile : public nsIDOMFile,
                   public nsIXHRSendable,
-                  public nsICharsetDetectionObserver,
                   public nsIJSNativeInitializer
 {
 public:
   NS_DECL_ISUPPORTS
   NS_DECL_NSIDOMBLOB
   NS_DECL_NSIDOMFILE
   NS_DECL_NSIXHRSENDABLE
 
@@ -95,19 +94,16 @@ public:
   {
     NS_ASSERTION(mFile, "must have file");
     // Ensure non-null mContentType
     mContentType.SetIsVoid(PR_FALSE);
   }
 
   virtual ~nsDOMFile() {}
 
-  // from nsICharsetDetectionObserver
-  NS_IMETHOD Notify(const char *aCharset, nsDetectionConfident aConf);
-
   // nsIJSNativeInitializer
   NS_IMETHOD Initialize(nsISupports* aOwner,
                         JSContext* aCx,
                         JSObject* aObj,
                         PRUint32 aArgc,
                         jsval* aArgv);
 
   // DOMClassInfo constructor (for File("foo"))
@@ -119,23 +115,16 @@ protected:
 
   // start and length in 
   PRUint64 mStart;
   PRUint64 mLength;
 
   nsString mContentType;
   
   bool mIsFullFile;
-
-  // Used during charset detection
-  nsCString mCharset;
-  nsresult GuessCharset(nsIInputStream *aStream,
-                        nsACString &aCharset);
-  nsresult ConvertStream(nsIInputStream *aStream, const char *aCharset,
-                         nsAString &aResult);
 };
 
 class nsDOMMemoryFile : public nsDOMFile
 {
 public:
   nsDOMMemoryFile(void *aMemoryBuffer,
                   PRUint64 aLength,
                   const nsAString& aName,
--- a/content/base/public/nsIDOMFile.idl
+++ b/content/base/public/nsIDOMFile.idl
@@ -58,32 +58,24 @@ interface nsIDOMBlob : nsISupports
   // moz-filedata: protocol handler
   [noscript] DOMString getInternalUrl(in nsIPrincipal principal);
 
   [optional_argc] nsIDOMBlob mozSlice(in long long start,
                                       [optional] in long long end,
                                       [optional] in DOMString contentType);
 };
 
-[scriptable, uuid(91c9ebd9-2a4a-4a38-9412-ef492a2799be)]
+[scriptable, uuid(b096ef67-7b77-47f8-8e70-5d8ee36416bf)]
 interface nsIDOMFile : nsIDOMBlob
 {
   readonly attribute DOMString name;
   readonly attribute DOMString mozFullPath;
 
   // This performs no security checks!
   [noscript] readonly attribute DOMString mozFullPathInternal;
-
-  // These are all deprecated and not in spec. Will be removed in a future
-  // release
-  readonly attribute DOMString fileName;
-  readonly attribute unsigned long long fileSize;
-  DOMString getAsText(in DOMString encoding); // raises(FileException) on retrieval
-  DOMString getAsDataURL();             // raises(FileException) on retrieval
-  DOMString getAsBinary();              // raises(FileException) on retrieval
 };
 
 [scriptable, uuid(c4a77171-039b-4f84-97f9-820fb51626af)]
 interface nsIDOMMozBlobBuilder : nsISupports
 {
   nsIDOMBlob getBlob([optional] in DOMString contentType);
   [implicit_jscontext] void append(in jsval data);
 };
--- a/content/base/src/nsDOMAttribute.cpp
+++ b/content/base/src/nsDOMAttribute.cpp
@@ -550,22 +550,16 @@ nsDOMAttribute::GetIsId(PRBool* aReturn)
     *aReturn = PR_FALSE;
     return NS_OK;
   }
 
   *aReturn = mNodeInfo->Equals(idAtom, kNameSpaceID_None);
   return NS_OK;
 }
 
-NS_IMETHODIMP
-nsDOMAttribute::GetSchemaTypeInfo(nsIDOM3TypeInfo** aReturn)
-{
-  return NS_ERROR_NOT_IMPLEMENTED;
-}
-
 PRBool
 nsDOMAttribute::IsNodeOfType(PRUint32 aFlags) const
 {
     return !(aFlags & ~eATTRIBUTE);
 }
 
 PRUint32
 nsDOMAttribute::GetChildCount() const
--- a/content/base/src/nsDOMBlobBuilder.cpp
+++ b/content/base/src/nsDOMBlobBuilder.cpp
@@ -146,38 +146,38 @@ nsDOMMultipartBlob::MozSlice(PRInt64 aSt
   PRUint64 thisLength;
   rv = GetSize(&thisLength);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (!optional_argc) {
     aEnd = (PRInt64)thisLength;
   }
 
+  // Modifies aStart and aEnd.
   ParseSize((PRInt64)thisLength, aStart, aEnd);
 
   // If we clamped to nothing we create an empty blob
   nsTArray<nsCOMPtr<nsIDOMBlob> > blobs;
 
-  PRInt64 length = aEnd - aStart;
-  PRUint64 finalLength = length;
+  PRUint64 length = aEnd - aStart;
   PRUint64 skipStart = aStart;
 
-  NS_ABORT_IF_FALSE(aStart + length <= thisLength, "Er, what?");
+  NS_ABORT_IF_FALSE(PRUint64(aStart) + length <= thisLength, "Er, what?");
 
   // Prune the list of blobs if we can
   PRUint32 i;
   for (i = 0; length && skipStart && i < mBlobs.Length(); i++) {
     nsIDOMBlob* blob = mBlobs[i].get();
 
     PRUint64 l;
     rv = blob->GetSize(&l);
     NS_ENSURE_SUCCESS(rv, rv);
 
     if (skipStart < l) {
-      PRInt64 upperBound = NS_MIN<PRInt64>(l - skipStart, length);
+      PRUint64 upperBound = NS_MIN<PRUint64>(l - skipStart, length);
 
       nsCOMPtr<nsIDOMBlob> firstBlob;
       rv = mBlobs.ElementAt(i)->MozSlice(skipStart, skipStart + upperBound,
                                          aContentType, 2,
                                          getter_AddRefs(firstBlob));
       NS_ENSURE_SUCCESS(rv, rv);
 
       // Avoid wrapping a single blob inside an nsDOMMultipartBlob
@@ -207,17 +207,17 @@ nsDOMMultipartBlob::MozSlice(PRInt64 aSt
       rv = mBlobs.ElementAt(i)->MozSlice(0, length, aContentType, 2,
                                          getter_AddRefs(lastBlob));
       NS_ENSURE_SUCCESS(rv, rv);
 
       blobs.AppendElement(lastBlob);
     } else {
       blobs.AppendElement(blob);
     }
-    length -= NS_MIN<PRInt64>(l, length);
+    length -= NS_MIN<PRUint64>(l, length);
   }
 
   // we can create our blob now
   nsCOMPtr<nsIDOMBlob> blob = new nsDOMMultipartBlob(blobs, aContentType);
   blob.forget(aBlob);
   return NS_OK;
 }
 
--- a/content/base/src/nsDOMFile.cpp
+++ b/content/base/src/nsDOMFile.cpp
@@ -137,17 +137,16 @@ nsresult DataOwnerAdapter::Create(DataOw
 DOMCI_DATA(File, nsDOMFile)
 DOMCI_DATA(Blob, nsDOMFile)
 
 NS_INTERFACE_MAP_BEGIN(nsDOMFile)
   NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIDOMFile)
   NS_INTERFACE_MAP_ENTRY(nsIDOMBlob)
   NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIDOMFile, mIsFullFile)
   NS_INTERFACE_MAP_ENTRY(nsIXHRSendable)
-  NS_INTERFACE_MAP_ENTRY(nsICharsetDetectionObserver)
   NS_INTERFACE_MAP_ENTRY(nsIJSNativeInitializer)
   NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO_CONDITIONAL(File, mIsFullFile)
   NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO_CONDITIONAL(Blob, !mIsFullFile)
 NS_INTERFACE_MAP_END
 
 NS_IMPL_ADDREF(nsDOMFile)
 NS_IMPL_RELEASE(nsDOMFile)
 
@@ -169,28 +168,16 @@ DOMFileResult(nsresult rv)
 nsDOMFile::NewFile(nsISupports* *aNewObject)
 {
   nsCOMPtr<nsISupports> file = do_QueryObject(new nsDOMFile(nsnull));
   file.forget(aNewObject);
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsDOMFile::GetFileName(nsAString &aFileName)
-{
-  return GetName(aFileName);
-}
-
-NS_IMETHODIMP
-nsDOMFile::GetFileSize(PRUint64 *aFileSize)
-{
-  return GetSize(aFileSize);
-}
-
-NS_IMETHODIMP
 nsDOMFile::GetName(nsAString &aFileName)
 {
   NS_ASSERTION(mIsFullFile, "Should only be called on files");
   return mFile->GetLeafName(aFileName);
 }
 
 NS_IMETHODIMP
 nsDOMFile::GetMozFullPath(nsAString &aFileName)
@@ -354,241 +341,16 @@ nsDOMFile::GetInternalUrl(nsIPrincipal* 
                                               aPrincipal);
 
   CopyASCIItoUTF16(url, aURL);
   
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsDOMFile::GetAsText(const nsAString &aCharset, nsAString &aResult)
-{
-  aResult.Truncate();
-
-  nsCOMPtr<nsIInputStream> stream;
-  nsresult rv = GetInternalStream(getter_AddRefs(stream));
-  NS_ENSURE_SUCCESS(rv, DOMFileResult(rv));
-
-  nsCAutoString charsetGuess;
-  if (!aCharset.IsEmpty()) {
-    CopyUTF16toUTF8(aCharset, charsetGuess);
-  } else {
-    rv = GuessCharset(stream, charsetGuess);
-    NS_ENSURE_SUCCESS(rv, DOMFileResult(rv));
-
-    nsCOMPtr<nsISeekableStream> seekable = do_QueryInterface(stream);
-    if (!seekable) return NS_ERROR_FAILURE;
-    rv = seekable->Seek(nsISeekableStream::NS_SEEK_SET, 0);
-    NS_ENSURE_SUCCESS(rv, DOMFileResult(rv));
-  }
-
-  nsCAutoString charset;
-  nsCOMPtr<nsICharsetAlias> alias =
-    do_GetService(NS_CHARSETALIAS_CONTRACTID, &rv);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  rv = alias->GetPreferred(charsetGuess, charset);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  return DOMFileResult(ConvertStream(stream, charset.get(), aResult));
-}
-
-NS_IMETHODIMP
-nsDOMFile::GetAsDataURL(nsAString &aResult)
-{
-  aResult.AssignLiteral("data:");
-
-  nsresult rv;
-  if (!mContentType.Length()) {
-    nsCOMPtr<nsIMIMEService> mimeService =
-      do_GetService(NS_MIMESERVICE_CONTRACTID, &rv);
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    nsCAutoString contentType;
-    rv = mimeService->GetTypeFromFile(mFile, contentType);
-    if (NS_SUCCEEDED(rv)) {
-      CopyUTF8toUTF16(contentType, mContentType);
-    }
-  }
-
-  if (mContentType.Length()) {
-    aResult.Append(mContentType);
-  } else {
-    aResult.AppendLiteral("application/octet-stream");
-  }
-  aResult.AppendLiteral(";base64,");
-
-  nsCOMPtr<nsIInputStream> stream;
-  rv = GetInternalStream(getter_AddRefs(stream));
-  NS_ENSURE_SUCCESS(rv, DOMFileResult(rv));
-
-  char readBuf[4096];
-  PRUint32 leftOver = 0;
-  PRUint32 numRead;
-  do {
-    rv = stream->Read(readBuf + leftOver, sizeof(readBuf) - leftOver, &numRead);
-    NS_ENSURE_SUCCESS(rv, DOMFileResult(rv));
-
-    PRUint32 numEncode = numRead + leftOver;
-    leftOver = 0;
-
-    if (numEncode == 0) break;
-
-    // unless this is the end of the file, encode in multiples of 3
-    if (numRead > 0) {
-      leftOver = numEncode % 3;
-      numEncode -= leftOver;
-    }
-
-    // out buffer should be at least 4/3rds the read buf, plus a terminator
-    char *base64 = PL_Base64Encode(readBuf, numEncode, nsnull);
-    if (!base64) {
-      return DOMFileResult(NS_ERROR_OUT_OF_MEMORY);
-    }
-    nsDependentCString str(base64);
-    PRUint32 strLen = str.Length();
-    PRUint32 oldLength = aResult.Length();
-    AppendASCIItoUTF16(str, aResult);
-    PR_Free(base64);
-    if (aResult.Length() - oldLength != strLen) {
-      return DOMFileResult(NS_ERROR_OUT_OF_MEMORY);
-    }
-
-    if (leftOver) {
-      memmove(readBuf, readBuf + numEncode, leftOver);
-    }
-  } while (numRead > 0);
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsDOMFile::GetAsBinary(nsAString &aResult)
-{
-  aResult.Truncate();
-
-  nsCOMPtr<nsIInputStream> stream;
-  nsresult rv = GetInternalStream(getter_AddRefs(stream));
-  NS_ENSURE_SUCCESS(rv, DOMFileResult(rv));
-
-  PRUint32 numRead;
-  do {
-    char readBuf[4096];
-    rv = stream->Read(readBuf, sizeof(readBuf), &numRead);
-    NS_ENSURE_SUCCESS(rv, DOMFileResult(rv));
-    PRUint32 oldLength = aResult.Length();
-    AppendASCIItoUTF16(Substring(readBuf, readBuf + numRead), aResult);
-    if (aResult.Length() - oldLength != numRead) {
-      return DOMFileResult(NS_ERROR_OUT_OF_MEMORY);
-    }
-  } while (numRead > 0);
-
-  return NS_OK;
-}
-
-nsresult
-nsDOMFile::GuessCharset(nsIInputStream *aStream,
-                        nsACString &aCharset)
-{
-
-  if (!mCharset.IsEmpty()) {
-    aCharset = mCharset;
-    return NS_OK;
-  }
-
-  // First try the universal charset detector
-  nsCOMPtr<nsICharsetDetector> detector
-    = do_CreateInstance(NS_CHARSET_DETECTOR_CONTRACTID_BASE
-                        "universal_charset_detector");
-  if (!detector) {
-    // No universal charset detector, try the default charset detector
-    const nsAdoptingCString& detectorName =
-      Preferences::GetLocalizedCString("intl.charset.detector");
-    if (!detectorName.IsEmpty()) {
-      nsCAutoString detectorContractID;
-      detectorContractID.AssignLiteral(NS_CHARSET_DETECTOR_CONTRACTID_BASE);
-      detectorContractID += detectorName;
-      detector = do_CreateInstance(detectorContractID.get());
-    }
-  }
-
-  nsresult rv;
-  if (detector) {
-    detector->Init(this);
-
-    PRBool done;
-    PRUint32 numRead;
-    do {
-      char readBuf[4096];
-      rv = aStream->Read(readBuf, sizeof(readBuf), &numRead);
-      NS_ENSURE_SUCCESS(rv, rv);
-
-      rv = detector->DoIt(readBuf, numRead, &done);
-      NS_ENSURE_SUCCESS(rv, rv);
-    } while (!done && numRead > 0);
-
-    rv = detector->Done();
-    NS_ENSURE_SUCCESS(rv, rv);
-  } else {
-    // no charset detector available, check the BOM
-    unsigned char sniffBuf[4];
-    PRUint32 numRead;
-    rv = aStream->Read(reinterpret_cast<char*>(sniffBuf),
-                       sizeof(sniffBuf), &numRead);
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    if (numRead >= 4 &&
-        sniffBuf[0] == 0x00 &&
-        sniffBuf[1] == 0x00 &&
-        sniffBuf[2] == 0xfe &&
-        sniffBuf[3] == 0xff) {
-      mCharset = "UTF-32BE";
-    } else if (numRead >= 4 &&
-               sniffBuf[0] == 0xff &&
-               sniffBuf[1] == 0xfe &&
-               sniffBuf[2] == 0x00 &&
-               sniffBuf[3] == 0x00) {
-      mCharset = "UTF-32LE";
-    } else if (numRead >= 2 &&
-               sniffBuf[0] == 0xfe &&
-               sniffBuf[1] == 0xff) {
-      mCharset = "UTF-16BE";
-    } else if (numRead >= 2 &&
-               sniffBuf[0] == 0xff &&
-               sniffBuf[1] == 0xfe) {
-      mCharset = "UTF-16LE";
-    } else if (numRead >= 3 &&
-               sniffBuf[0] == 0xef &&
-               sniffBuf[1] == 0xbb &&
-               sniffBuf[2] == 0xbf) {
-      mCharset = "UTF-8";
-    }
-  }
-
-  if (mCharset.IsEmpty()) {
-    // no charset detected, default to the system charset
-    nsCOMPtr<nsIPlatformCharset> platformCharset =
-      do_GetService(NS_PLATFORMCHARSET_CONTRACTID, &rv);
-    if (NS_SUCCEEDED(rv)) {
-      rv = platformCharset->GetCharset(kPlatformCharsetSel_PlainTextInFile,
-                                       mCharset);
-    }
-  }
-
-  if (mCharset.IsEmpty()) {
-    // no sniffed or default charset, try UTF-8
-    mCharset.AssignLiteral("UTF-8");
-  }
-
-  aCharset = mCharset;
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
 nsDOMFile::GetSendInfo(nsIInputStream** aBody,
                        nsACString& aContentType,
                        nsACString& aCharset)
 {
   nsresult rv;
 
   nsCOMPtr<nsIInputStream> stream;
   rv = this->GetInternalStream(getter_AddRefs(stream));
@@ -602,24 +364,16 @@ nsDOMFile::GetSendInfo(nsIInputStream** 
 
   aCharset.Truncate();
 
   stream.forget(aBody);
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsDOMFile::Notify(const char* aCharset, nsDetectionConfident aConf)
-{
-  mCharset.Assign(aCharset);
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
 nsDOMFile::Initialize(nsISupports* aOwner,
                       JSContext* aCx,
                       JSObject* aObj,
                       PRUint32 aArgc,
                       jsval* aArgv)
 {
   nsresult rv;
 
@@ -669,52 +423,16 @@ nsDOMFile::Initialize(nsISupports* aOwne
   rv = file->Exists(&exists);
   NS_ENSURE_SUCCESS(rv, rv);
   NS_ENSURE_TRUE(exists, NS_ERROR_FILE_NOT_FOUND);
 
   mFile = file;
   return NS_OK;
 }
 
-nsresult
-nsDOMFile::ConvertStream(nsIInputStream *aStream,
-                         const char *aCharset,
-                         nsAString &aResult)
-{
-  aResult.Truncate();
-
-  nsCOMPtr<nsIConverterInputStream> converterStream =
-    do_CreateInstance("@mozilla.org/intl/converter-input-stream;1");
-  if (!converterStream) return NS_ERROR_FAILURE;
-
-  nsresult rv = converterStream->Init
-                  (aStream, aCharset,
-                   8192,
-                   nsIConverterInputStream::DEFAULT_REPLACEMENT_CHARACTER);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  nsCOMPtr<nsIUnicharInputStream> unicharStream =
-    do_QueryInterface(converterStream);
-  if (!unicharStream) return NS_ERROR_FAILURE;
-
-  PRUint32 numChars;
-  nsString result;
-  rv = unicharStream->ReadString(8192, result, &numChars);
-  while (NS_SUCCEEDED(rv) && numChars > 0) {
-    PRUint32 oldLength = aResult.Length();
-    aResult.Append(result);
-    if (aResult.Length() - oldLength != result.Length()) {
-      return NS_ERROR_OUT_OF_MEMORY;
-    }
-    rv = unicharStream->ReadString(8192, result, &numChars);
-  }
-
-  return rv;
-}
-
 // nsDOMMemoryFile Implementation
 NS_IMETHODIMP
 nsDOMMemoryFile::GetName(nsAString &aFileName)
 {
   NS_ASSERTION(mIsFullFile, "Should only be called on files");
   aFileName = mName;
   return NS_OK;
 }
--- a/content/base/src/nsGkAtomList.h
+++ b/content/base/src/nsGkAtomList.h
@@ -1378,17 +1378,16 @@ GK_ATOM(onrepeatEvent, "onrepeatEvent")
 GK_ATOM(repeatCount, "repeatCount")
 GK_ATOM(repeatDur, "repeatDur")
 GK_ATOM(repeatEvent, "repeatEvent")
 GK_ATOM(restart, "restart")
 GK_ATOM(to, "to")
 GK_ATOM(XML, "XML")
 #endif
 
-#ifdef MOZ_MATHML
 // internal MathML attributes: different from columnalign_, columnlines_,
 // fontstyle_, rowalign_ and rowlines_
 GK_ATOM(_moz_math_columnalign_, "_moz-math-columnalign")
 GK_ATOM(_moz_math_columnline_, "_moz-math-columnline")
 GK_ATOM(_moz_math_fontstyle_, "_moz-math-font-style")
 GK_ATOM(_moz_math_rowalign_, "_moz-math-rowalign")
 GK_ATOM(_moz_math_rowline_, "_moz-math-rowline")
 
@@ -1662,17 +1661,16 @@ GK_ATOM(vectorproduct_, "vectorproduct")
 GK_ATOM(vector_, "vector")
 GK_ATOM(verythickmathspace_, "verythickmathspace")
 GK_ATOM(verythinmathspace_, "verythinmathspace")
 GK_ATOM(veryverythickmathspace_, "veryverythickmathspace")
 GK_ATOM(veryverythinmathspace_, "veryverythinmathspace")
 GK_ATOM(voffset_, "voffset")
 GK_ATOM(xref_, "xref")
 GK_ATOM(math, "math") // the only one without an underscore
-#endif
 
 #ifndef DISABLE_XFORMS_HOOKS
 GK_ATOM(avg, "avg")
 GK_ATOM(booleanFromString, "boolean-from-string")
 GK_ATOM(countNonEmpty, "count-non-empty")
 GK_ATOM(daysFromDate, "days-from-date")
 GK_ATOM(init, "init")
 GK_ATOM(instance, "instance")
--- a/content/base/src/nsInProcessTabChildGlobal.cpp
+++ b/content/base/src/nsInProcessTabChildGlobal.cpp
@@ -290,17 +290,16 @@ nsInProcessTabChildGlobal::InitTabChildG
   NS_ENSURE_STATE(cx);
 
   mCx = cx;
 
   nsContentUtils::XPConnect()->SetSecurityManagerForJSContext(cx, nsContentUtils::GetSecurityManager(), 0);
   nsContentUtils::GetSecurityManager()->GetSystemPrincipal(getter_AddRefs(mPrincipal));
 
   JS_SetNativeStackQuota(cx, 128 * sizeof(size_t) * 1024);
-  JS_SetScriptStackQuota(cx, 25 * sizeof(size_t) * 1024 * 1024);
 
   JS_SetOptions(cx, JS_GetOptions(cx) | JSOPTION_JIT | JSOPTION_ANONFUNFIX | JSOPTION_PRIVATE_IS_NSISUPPORTS);
   JS_SetVersion(cx, JSVERSION_LATEST);
   JS_SetErrorReporter(cx, ContentScriptErrorReporter);
 
   xpc_LocalizeContext(cx);
 
   JSAutoRequest ar(cx);
--- a/content/base/src/nsNameSpaceManager.cpp
+++ b/content/base/src/nsNameSpaceManager.cpp
@@ -230,21 +230,19 @@ NS_NewElement(nsIContent** aResult, PRIn
   if (aElementType == kNameSpaceID_XHTML) {
     return NS_NewHTMLElement(aResult, aNodeInfo, aFromParser);
   }
 #ifdef MOZ_XUL
   if (aElementType == kNameSpaceID_XUL) {
     return NS_NewXULElement(aResult, aNodeInfo);
   }
 #endif
-#ifdef MOZ_MATHML
   if (aElementType == kNameSpaceID_MathML) {
     return NS_NewMathMLElement(aResult, aNodeInfo);
   }
-#endif
   if (aElementType == kNameSpaceID_SVG) {
     return NS_NewSVGElement(aResult, aNodeInfo, aFromParser);
   }
   if (aElementType == kNameSpaceID_XMLEvents) {
     return NS_NewXMLEventsElement(aResult, aNodeInfo);
   }
 #ifdef MOZ_XTF
   if (aElementType > kNameSpaceID_LastBuiltin) {
@@ -260,19 +258,17 @@ NS_NewElement(nsIContent** aResult, PRIn
 
 PRBool
 NameSpaceManagerImpl::HasElementCreator(PRInt32 aNameSpaceID)
 {
   return aNameSpaceID == kNameSpaceID_XHTML ||
 #ifdef MOZ_XUL
          aNameSpaceID == kNameSpaceID_XUL ||
 #endif
-#ifdef MOZ_MATHML
          aNameSpaceID == kNameSpaceID_MathML ||
-#endif
          aNameSpaceID == kNameSpaceID_SVG ||
          aNameSpaceID == kNameSpaceID_XMLEvents ||
          PR_FALSE;
 }
 
 nsresult NameSpaceManagerImpl::AddNameSpace(const nsAString& aURI,
                                             const PRInt32 aNameSpaceID)
 {
--- a/content/base/test/Makefile.in
+++ b/content/base/test/Makefile.in
@@ -153,17 +153,16 @@ include $(topsrcdir)/config/rules.mk
 		test_bug403868.xml \
 		test_bug405182.html \
 		test_bug403841.html \
 		test_bug409380.html \
 		test_bug410229.html \
 		test_bug413974.html \
 		test_bug415860.html \
 		test_bug414190.html \
-		test_bug414796.html \
 		test_bug527896.html \
 		test_bug416317-1.html \
 		test_bug416317-2.html \
 		test_XHRSendData.html \
 		file_XHRSendData.sjs \
 		file_XHRSendData_doc.xml \
 		file_XHRSendData_doc.xml^headers^ \
 		file_bug416317.xhtml \
--- a/content/base/test/browser_bug593387.js
+++ b/content/base/test/browser_bug593387.js
@@ -22,16 +22,18 @@ function test() {
 function testXFOFrameInChrome() {
   newBrowser.removeEventListener("load", testXFOFrameInChrome, true);
 
   // Insert an iframe that specifies "X-Frame-Options: DENY" and verify
   // that it loads, since the top context is chrome
   var frame = newBrowser.contentDocument.createElement("iframe");
   frame.src = "http://mochi.test:8888/tests/content/base/test/file_x-frame-options_page.sjs?testid=deny&xfo=deny";
   frame.addEventListener("load", function() {
+    frame.removeEventListener("load", arguments.callee, true);
+
     // Test that the frame loaded
     var test = this.contentDocument.getElementById("test");
     is(test.tagName, "H1", "wrong element type");
     is(test.textContent, "deny", "wrong textContent");
     
     // Run next test (try the same with a content top-level context)
     newBrowser.addEventListener("load", testXFOFrameInContent, true);
     newBrowser.contentWindow.location = "http://example.com/";  
@@ -43,16 +45,18 @@ function testXFOFrameInChrome() {
 function testXFOFrameInContent() {
   newBrowser.removeEventListener("load", testXFOFrameInContent, true);
 
   // Insert an iframe that specifies "X-Frame-Options: DENY" and verify that it
   // is blocked from loading since the top browsing context is another site
   var frame = newBrowser.contentDocument.createElement("iframe");
   frame.src = "http://mochi.test:8888/tests/content/base/test/file_x-frame-options_page.sjs?testid=deny&xfo=deny";
   frame.addEventListener("load", function() {
+    frame.removeEventListener("load", arguments.callee, true);
+
     // Test that the frame DID NOT load
     var test = this.contentDocument.getElementById("test");
     is(test, undefined, "should be about:blank");
 
     // Finalize the test
     gBrowser.removeCurrentTab();
     finish();
   }, true);
deleted file mode 100644
--- a/content/base/test/test_bug414796.html
+++ /dev/null
@@ -1,55 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=414796
--->
-  <title>Test for Bug 414796</title>
-  <script type="text/javascript" src="/MochiKit/packed.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=414796">Mozilla Bug 414796</a>
-<p id="display">
-  <input id="fileList" type="file"></input>
-</p>
-<div id="content" style="display: none">
-</div>
-
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
-
-// Write a test file > 8192 characters
-
-var testData = "asdfblahqwer";
-for (var i = 0; i < 10; i++) {
-  testData = testData + testData;
-}
-
-var dirSvc = Components.classes["@mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties);
-var testFile = dirSvc.get("ProfD", Components.interfaces.nsIFile);
-testFile.append("testfile");
-
-var outStream = Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance(Components.interfaces.nsIFileOutputStream);
-outStream.init(testFile, 0x02 | 0x08 | 0x20, // write, create, truncate
-               0666, 0);
-outStream.write(testData, testData.length);
-outStream.close();
-
-var fileList = document.getElementById('fileList');
-fileList.value = testFile.path;
-
-var domFileData = fileList.files[0].getAsText("iso-8859-1");
-ok(domFileData.length == testData.length);
-ok(domFileData == testData);
-
-testFile.remove(false);
-
-</script>
-</pre>
-</body> </html>
--- a/content/canvas/src/WebGLContext.h
+++ b/content/canvas/src/WebGLContext.h
@@ -944,17 +944,17 @@ protected:
 
     size_t mFacesCount, mMaxLevelWithCustomImages;
     nsTArray<ImageInfo> mImageInfos;
 
     PRBool mHaveGeneratedMipmap;
     FakeBlackStatus mFakeBlackStatus;
 
     void EnsureMaxLevelWithCustomImagesAtLeast(size_t aMaxLevelWithCustomImages) {
-        mMaxLevelWithCustomImages = PR_MAX(mMaxLevelWithCustomImages, aMaxLevelWithCustomImages);
+        mMaxLevelWithCustomImages = NS_MAX(mMaxLevelWithCustomImages, aMaxLevelWithCustomImages);
         mImageInfos.EnsureLengthAtLeast((mMaxLevelWithCustomImages + 1) * mFacesCount);
     }
 
     PRBool CheckFloatTextureFilterParams() const {
         // Without OES_texture_float_linear, only NEAREST and NEAREST_MIMPAMP_NEAREST are supported
         return (mMagFilter == LOCAL_GL_NEAREST) &&
             (mMinFilter == LOCAL_GL_NEAREST || mMinFilter == LOCAL_GL_NEAREST_MIPMAP_NEAREST);
     }
@@ -974,18 +974,18 @@ protected:
         ImageInfo expected = ImageInfoAt(0, face);
 
         // checks if custom level>0 images are all defined up to the highest level defined
         // and have the expected dimensions
         for (size_t level = 0; level <= mMaxLevelWithCustomImages; ++level) {
             const ImageInfo& actual = ImageInfoAt(level, face);
             if (actual != expected)
                 return PR_FALSE;
-            expected.mWidth = PR_MAX(1, expected.mWidth >> 1);
-            expected.mHeight = PR_MAX(1, expected.mHeight >> 1);
+            expected.mWidth = NS_MAX(1, expected.mWidth >> 1);
+            expected.mHeight = NS_MAX(1, expected.mHeight >> 1);
 
             // if the current level has size 1x1, we can stop here: the spec doesn't seem to forbid the existence
             // of extra useless levels.
             if (actual.mWidth == 1 && actual.mHeight == 1)
                 return PR_TRUE;
         }
 
         // if we're here, we've exhausted all levels without finding a 1x1 image
@@ -1086,17 +1086,17 @@ public:
             // if we were in GeneratedMipmap mode and are now switching to CustomMipmap mode,
             // we need to compute now all the mipmap image info.
 
             // since we were in GeneratedMipmap mode, we know that the level 0 images all have the same info,
             // and are power-of-two.
             ImageInfo imageInfo = ImageInfoAt(0, 0);
             NS_ASSERTION(imageInfo.IsPowerOfTwo(), "this texture is NPOT, so how could GenerateMipmap() ever accept it?");
 
-            WebGLsizei size = PR_MAX(imageInfo.mWidth, imageInfo.mHeight);
+            WebGLsizei size = NS_MAX(imageInfo.mWidth, imageInfo.mHeight);
 
             // so, the size is a power of two, let's find its log in base 2.
             size_t maxLevel = 0;
             for (WebGLsizei n = size; n > 1; n >>= 1)
                 ++maxLevel;
 
             EnsureMaxLevelWithCustomImagesAtLeast(maxLevel);
 
--- a/content/canvas/src/WebGLContextGL.cpp
+++ b/content/canvas/src/WebGLContextGL.cpp
@@ -739,23 +739,23 @@ WebGLContext::CopyTexSubImage2D_base(Web
             || x+width <= 0
             || y >= framebufferHeight
             || y+height <= 0)
         {
             // we are completely outside of range, can exit now with buffer filled with zeros
             return NS_OK;
         }
 
-        GLint   actual_x             = PR_MIN(framebufferWidth, PR_MAX(0, x));
-        GLint   actual_x_plus_width  = PR_MIN(framebufferWidth, PR_MAX(0, x + width));
+        GLint   actual_x             = NS_MIN(framebufferWidth, NS_MAX(0, x));
+        GLint   actual_x_plus_width  = NS_MIN(framebufferWidth, NS_MAX(0, x + width));
         GLsizei actual_width   = actual_x_plus_width  - actual_x;
         GLint   actual_xoffset = xoffset + actual_x - x;
 
-        GLint   actual_y             = PR_MIN(framebufferHeight, PR_MAX(0, y));
-        GLint   actual_y_plus_height = PR_MIN(framebufferHeight, PR_MAX(0, y + height));
+        GLint   actual_y             = NS_MIN(framebufferHeight, NS_MAX(0, y));
+        GLint   actual_y_plus_height = NS_MIN(framebufferHeight, NS_MAX(0, y + height));
         GLsizei actual_height  = actual_y_plus_height - actual_y;
         GLint   actual_yoffset = yoffset + actual_y - y;
 
         gl->fCopyTexSubImage2D(target, level, actual_xoffset, actual_yoffset, actual_x, actual_y, actual_width, actual_height);
     }
 
     return NS_OK;
 }
@@ -2982,22 +2982,22 @@ WebGLContext::ReadPixels_base(WebGLint x
             || y >= boundHeight
             || y+height <= 0)
         {
             // we are completely outside of range, can exit now with buffer filled with zeros
             return NS_OK;
         }
 
         // compute the parameters of the subrect we're actually going to call glReadPixels on
-        GLint   subrect_x      = PR_MAX(x, 0);
-        GLint   subrect_end_x  = PR_MIN(x+width, boundWidth);
+        GLint   subrect_x      = NS_MAX(x, 0);
+        GLint   subrect_end_x  = NS_MIN(x+width, boundWidth);
         GLsizei subrect_width  = subrect_end_x - subrect_x;
 
-        GLint   subrect_y      = PR_MAX(y, 0);
-        GLint   subrect_end_y  = PR_MIN(y+height, boundHeight);
+        GLint   subrect_y      = NS_MAX(y, 0);
+        GLint   subrect_end_y  = NS_MIN(y+height, boundHeight);
         GLsizei subrect_height = subrect_end_y - subrect_y;
 
         if (subrect_width < 0 || subrect_height < 0 ||
             subrect_width > width || subrect_height > height)
             return ErrorInvalidOperation("ReadPixels: integer overflow computing clipped rect size");
 
         // now we know that subrect_width is in the [0..width] interval, and same for heights.
 
@@ -3476,24 +3476,61 @@ WebGLContext::DOMElementToImageSurface(n
         flags |= nsLayoutUtils::SFE_NO_COLORSPACE_CONVERSION;
     if (!mPixelStorePremultiplyAlpha)
         flags |= nsLayoutUtils::SFE_NO_PREMULTIPLY_ALPHA;
 
     nsLayoutUtils::SurfaceFromElementResult res =
         nsLayoutUtils::SurfaceFromElement(imageOrCanvas, flags);
     if (!res.mSurface)
         return NS_ERROR_FAILURE;
-
-    CanvasUtils::DoDrawImageSecurityCheck(HTMLCanvasElement(), res.mPrincipal, res.mIsWriteOnly);
-
     if (res.mSurface->GetType() != gfxASurface::SurfaceTypeImage) {
         // SurfaceFromElement lied!
         return NS_ERROR_FAILURE;
     }
 
+    // Bug 656277 - Prevent loading WebGL textures from cross-domain images
+    //
+    // We disallow loading cross-domain images as WebGL textures. The reason for doing that
+    // is that timing attacks on WebGL shaders are able to retrieve approximations of the pixel values
+    // in WebGL textures, see bug 655987.
+    //
+    // To prevent a loophole where a Canvas2D would be used as a proxy to load cross-domain textures,
+    // we also disallow loading textures from write-only Canvas2D's.
+
+    // part 1: check that the DOM element is same-origin.
+    // if res.mPrincipal == null, no need for the origin check. See DoDrawImageSecurityCheck.
+    // this case happens in the mochitest for images served from mochi.test:8888
+    if (res.mPrincipal) {
+        PRBool subsumes;
+        nsresult rv = HTMLCanvasElement()->NodePrincipal()->Subsumes(res.mPrincipal, &subsumes);
+        if (NS_FAILED(rv) || !subsumes) {
+            LogMessageIfVerbose("It is forbidden to load a WebGL texture from a cross-domain element. "
+                                "See https://developer.mozilla.org/en/WebGL/Cross-Domain_Textures");
+            return NS_ERROR_DOM_SECURITY_ERR;
+        }
+    }
+
+    // part 2: if the DOM element is a canvas, check that it's not write-only. That would indicate a tainted canvas,
+    // i.e. a canvas that could contain cross-domain image data.
+    nsCOMPtr<nsIContent> maybeDOMCanvas = do_QueryInterface(imageOrCanvas);
+    if (maybeDOMCanvas && maybeDOMCanvas->IsHTML(nsGkAtoms::canvas)) {
+        nsHTMLCanvasElement *canvas = static_cast<nsHTMLCanvasElement*>(maybeDOMCanvas.get());
+        if (canvas->IsWriteOnly()) {
+            LogMessageIfVerbose("The canvas used as source for texImage2D here is tainted (write-only). It is forbidden "
+                                "to load a WebGL texture from a tainted canvas. A Canvas becomes tainted for example "
+                                "when a cross-domain image is drawn on it. "
+                                "See https://developer.mozilla.org/en/WebGL/Cross-Domain_Textures");
+            return NS_ERROR_DOM_SECURITY_ERR;
+        }
+    }
+
+    // End of security checks, now we should be safe regarding cross-domain images
+    // Notice that there is never a need to mark the WebGL canvas as write-only, since we reject write-only/cross-domain
+    // texture sources in the first place.
+
     surf = static_cast<gfxImageSurface*>(res.mSurface.get());
 
     res.mSurface.forget();
     *imageOut = surf;
 
     switch (surf->Format()) {
         case gfxASurface::ImageFormatARGB32:
             *format = WebGLTexelFormat::BGRA8; // careful, our ARGB means BGRA
--- a/content/canvas/src/WebGLContextValidate.cpp
+++ b/content/canvas/src/WebGLContextValidate.cpp
@@ -533,17 +533,17 @@ WebGLContext::InitAndValidateGL()
         GLint maxVertexOutputComponents,
               minFragmentInputComponents;
         gl->fGetIntegerv(LOCAL_GL_MAX_VERTEX_OUTPUT_COMPONENTS, &maxVertexOutputComponents);
         gl->fGetIntegerv(LOCAL_GL_MAX_FRAGMENT_INPUT_COMPONENTS, &minFragmentInputComponents);
 
         error = gl->fGetError();
         switch (error) {
             case LOCAL_GL_NO_ERROR:
-                mGLMaxVaryingVectors = PR_MIN(maxVertexOutputComponents, minFragmentInputComponents) / 4;
+                mGLMaxVaryingVectors = NS_MIN(maxVertexOutputComponents, minFragmentInputComponents) / 4;
                 break;
             case LOCAL_GL_INVALID_ENUM:
                 mGLMaxVaryingVectors = 16; // = 64/4, 64 is the min value for maxVertexOutputComponents in OpenGL 3.2 spec
                 break;
             default:
                 LogMessage("GL error 0x%x occurred during WebGL context initialization!", error);
                 return PR_FALSE;
         }
--- a/content/canvas/src/nsCanvasRenderingContext2D.cpp
+++ b/content/canvas/src/nsCanvasRenderingContext2D.cpp
@@ -3228,17 +3228,18 @@ nsCanvasRenderingContext2D::GetMiterLimi
 NS_IMETHODIMP
 nsCanvasRenderingContext2D::IsPointInPath(float x, float y, PRBool *retVal)
 {
     if (!FloatValidate(x,y)) {
         *retVal = PR_FALSE;
         return NS_OK;
     }
 
-    *retVal = mThebes->PointInFill(gfxPoint(x,y));
+    gfxPoint pt(x, y);
+    *retVal = mThebes->PointInFill(mThebes->DeviceToUser(pt));
     return NS_OK;
 }
 
 //
 // image
 //
 
 // drawImage(in HTMLImageElement image, in float dx, in float dy);
@@ -3452,30 +3453,27 @@ NS_IMETHODIMP
 nsCanvasRenderingContext2D::SetGlobalCompositeOperation(const nsAString& op)
 {
     gfxContext::GraphicsOperator thebes_op;
 
 #define CANVAS_OP_TO_THEBES_OP(cvsop,thebesop) \
     if (op.EqualsLiteral(cvsop))   \
         thebes_op = gfxContext::OPERATOR_##thebesop;
 
-    CANVAS_OP_TO_THEBES_OP("clear", CLEAR)
-    else CANVAS_OP_TO_THEBES_OP("copy", SOURCE)
+    CANVAS_OP_TO_THEBES_OP("copy", SOURCE)
     else CANVAS_OP_TO_THEBES_OP("destination-atop", DEST_ATOP)
     else CANVAS_OP_TO_THEBES_OP("destination-in", DEST_IN)
     else CANVAS_OP_TO_THEBES_OP("destination-out", DEST_OUT)
     else CANVAS_OP_TO_THEBES_OP("destination-over", DEST_OVER)
     else CANVAS_OP_TO_THEBES_OP("lighter", ADD)
     else CANVAS_OP_TO_THEBES_OP("source-atop", ATOP)
     else CANVAS_OP_TO_THEBES_OP("source-in", IN)
     else CANVAS_OP_TO_THEBES_OP("source-out", OUT)
     else CANVAS_OP_TO_THEBES_OP("source-over", OVER)
     else CANVAS_OP_TO_THEBES_OP("xor", XOR)
-    // not part of spec, kept here for compat
-    else CANVAS_OP_TO_THEBES_OP("over", OVER)
     // XXX ERRMSG we need to report an error to developers here! (bug 329026)
     else return NS_OK;
 
 #undef CANVAS_OP_TO_THEBES_OP
 
     mThebes->SetOperator(thebes_op);
     return NS_OK;
 }
@@ -3484,20 +3482,17 @@ NS_IMETHODIMP
 nsCanvasRenderingContext2D::GetGlobalCompositeOperation(nsAString& op)
 {
     gfxContext::GraphicsOperator thebes_op = mThebes->CurrentOperator();
 
 #define CANVAS_OP_TO_THEBES_OP(cvsop,thebesop) \
     if (thebes_op == gfxContext::OPERATOR_##thebesop) \
         op.AssignLiteral(cvsop);
 
-    // XXX "darker" isn't really correct
-    CANVAS_OP_TO_THEBES_OP("clear", CLEAR)
-    else CANVAS_OP_TO_THEBES_OP("copy", SOURCE)
-    else CANVAS_OP_TO_THEBES_OP("darker", SATURATE)  // XXX
+    CANVAS_OP_TO_THEBES_OP("copy", SOURCE)
     else CANVAS_OP_TO_THEBES_OP("destination-atop", DEST_ATOP)
     else CANVAS_OP_TO_THEBES_OP("destination-in", DEST_IN)
     else CANVAS_OP_TO_THEBES_OP("destination-out", DEST_OUT)
     else CANVAS_OP_TO_THEBES_OP("destination-over", DEST_OVER)
     else CANVAS_OP_TO_THEBES_OP("lighter", ADD)
     else CANVAS_OP_TO_THEBES_OP("source-atop", ATOP)
     else CANVAS_OP_TO_THEBES_OP("source-in", IN)
     else CANVAS_OP_TO_THEBES_OP("source-out", OUT)
--- a/content/canvas/test/test_canvas.html
+++ b/content/canvas/test/test_canvas.html
@@ -1481,17 +1481,17 @@ ok(!_thrown_outer, 'should not throw exc
 
 function test_2d_composite_operation_clear() {
 
 var canvas = document.getElementById('c55');
 var ctx = canvas.getContext('2d');
 
 ctx.globalCompositeOperation = 'xor';
 ctx.globalCompositeOperation = 'clear';
-todo(ctx.globalCompositeOperation == 'xor', "ctx.globalCompositeOperation == 'xor'");
+ok(ctx.globalCompositeOperation == 'xor', "ctx.globalCompositeOperation == 'xor'");
 
 
 }
 </script>
 
 <!-- [[[ test_2d.composite.operation.darker.html ]]] -->
 
 <p>Canvas test: 2d.composite.operation.darker</p>
@@ -1614,17 +1614,17 @@ ok(!_thrown_outer, 'should not throw exc
 
 function test_2d_composite_operation_over() {
 
 var canvas = document.getElementById('c61');
 var ctx = canvas.getContext('2d');
 
 ctx.globalCompositeOperation = 'xor';
 ctx.globalCompositeOperation = 'over';
-todo(ctx.globalCompositeOperation == 'xor', "ctx.globalCompositeOperation == 'xor'");
+ok(ctx.globalCompositeOperation == 'xor', "ctx.globalCompositeOperation == 'xor'");
 
 
 }
 </script>
 
 <!-- [[[ test_2d.composite.operation.unrecognised.html ]]] -->
 
 <p>Canvas test: 2d.composite.operation.unrecognised - bug 401788</p>
@@ -13271,20 +13271,20 @@ ok(ctx.isPointInPath(50, 10) === true, "
 function test_2d_path_isPointInPath_transform_1() {
 
 var canvas = document.getElementById('c409');
 var ctx = canvas.getContext('2d');
 
 ctx.translate(50, 0);
 ctx.rect(0, 0, 20, 20);
 ok(ctx.isPointInPath(-40, 10) === false, "ctx.isPointInPath(-40, 10) === false");
-todo(ctx.isPointInPath(10, 10) === false, "ctx.isPointInPath(10, 10) === false");
+ok(ctx.isPointInPath(10, 10) === false, "ctx.isPointInPath(10, 10) === false");
 ok(ctx.isPointInPath(49, 10) === false, "ctx.isPointInPath(49, 10) === false");
-todo(ctx.isPointInPath(51, 10) === true, "ctx.isPointInPath(51, 10) === true");
-todo(ctx.isPointInPath(69, 10) === true, "ctx.isPointInPath(69, 10) === true");
+ok(ctx.isPointInPath(51, 10) === true, "ctx.isPointInPath(51, 10) === true");
+ok(ctx.isPointInPath(69, 10) === true, "ctx.isPointInPath(69, 10) === true");
 ok(ctx.isPointInPath(71, 10) === false, "ctx.isPointInPath(71, 10) === false");
 
 
 }
 </script>
 
 <!-- [[[ test_2d.path.isPointInPath.transform.2.html ]]] -->
 
@@ -13296,20 +13296,20 @@ ok(ctx.isPointInPath(71, 10) === false, 
 function test_2d_path_isPointInPath_transform_2() {
 
 var canvas = document.getElementById('c410');
 var ctx = canvas.getContext('2d');
 
 ctx.rect(50, 0, 20, 20);
 ctx.translate(50, 0);
 ok(ctx.isPointInPath(-40, 10) === false, "ctx.isPointInPath(-40, 10) === false");
-todo(ctx.isPointInPath(10, 10) === false, "ctx.isPointInPath(10, 10) === false");
+ok(ctx.isPointInPath(10, 10) === false, "ctx.isPointInPath(10, 10) === false");
 ok(ctx.isPointInPath(49, 10) === false, "ctx.isPointInPath(49, 10) === false");
-todo(ctx.isPointInPath(51, 10) === true, "ctx.isPointInPath(51, 10) === true");
-todo(ctx.isPointInPath(69, 10) === true, "ctx.isPointInPath(69, 10) === true");
+ok(ctx.isPointInPath(51, 10) === true, "ctx.isPointInPath(51, 10) === true");
+ok(ctx.isPointInPath(69, 10) === true, "ctx.isPointInPath(69, 10) === true");
 ok(ctx.isPointInPath(71, 10) === false, "ctx.isPointInPath(71, 10) === false");
 
 
 }
 </script>
 
 <!-- [[[ test_2d.path.isPointInPath.transform.3.html ]]] -->
 
@@ -13323,18 +13323,18 @@ function test_2d_path_isPointInPath_tran
 var canvas = document.getElementById('c411');
 var ctx = canvas.getContext('2d');
 
 ctx.scale(-1, 1);
 ctx.rect(-70, 0, 20, 20);
 ok(ctx.isPointInPath(-40, 10) === false, "ctx.isPointInPath(-40, 10) === false");
 ok(ctx.isPointInPath(10, 10) === false, "ctx.isPointInPath(10, 10) === false");
 ok(ctx.isPointInPath(49, 10) === false, "ctx.isPointInPath(49, 10) === false");
-todo(ctx.isPointInPath(51, 10) === true, "ctx.isPointInPath(51, 10) === true");
-todo(ctx.isPointInPath(69, 10) === true, "ctx.isPointInPath(69, 10) === true");
+ok(ctx.isPointInPath(51, 10) === true, "ctx.isPointInPath(51, 10) === true");
+ok(ctx.isPointInPath(69, 10) === true, "ctx.isPointInPath(69, 10) === true");
 ok(ctx.isPointInPath(71, 10) === false, "ctx.isPointInPath(71, 10) === false");
 
 
 }
 </script>
 
 <!-- [[[ test_2d.path.isPointInPath.unclosed.html ]]] -->
 
--- a/content/canvas/test/test_mozGetAsFile.html
+++ b/content/canvas/test/test_mozGetAsFile.html
@@ -1,35 +1,48 @@
 <!DOCTYPE HTML>
 <title>Canvas test: mozGetAsFile</title>
 <script src="/MochiKit/MochiKit.js"></script>
 <script src="/tests/SimpleTest/SimpleTest.js"></script>
 <link rel="stylesheet" href="/tests/SimpleTest/test.css">
 <body>
 <canvas id="c" width="100" height="50"><p class="fallback">FAIL (fallback content)</p></canvas>
 <script>
+
+function compareAsync(file, canvas, type)
+{
+  SimpleTest.waitForExplicitFinish();
+
+  var reader = new FileReader();
+  reader.onload = 
+    function(e) {
+      is(e.target.result, canvas.toDataURL(type),
+ "<canvas>.mozGetAsFile().getAsDataURL() should equal <canvas>.toDataURL()");
+      SimpleTest.finish();
+    };
+  reader.readAsDataURL(file);
+}
+
 SimpleTest.waitForExplicitFinish();
 MochiKit.DOM.addLoadEvent(function () {
 
 var canvas = document.getElementById('c');
 var ctx = canvas.getContext('2d');
 
 ctx.drawImage(document.getElementById('yellow75.png'), 0, 0);
 
 var pngfile = canvas.mozGetAsFile("foo.png");
 is(pngfile.type, "image/png", "Default type for mozGetAsFile should be PNG");
-is(pngfile.getAsDataURL(), canvas.toDataURL(),
-   "<canvas>.mozGetAsFile().getAsDataURL() should equal <canvas>.toDataURL()");
+compareAsync(pngfile, canvas, "image/png");
 is(pngfile.name, "foo.png", "File name should be what we passed in");
 
 var jpegfile = canvas.mozGetAsFile("bar.jpg", "image/jpeg");
 is(jpegfile.type, "image/jpeg",
    "When a valid type is specified that should be returned");
-is(jpegfile.getAsDataURL(), canvas.toDataURL("image/jpeg"),
-   "<canvas>.mozGetAsFile().getAsDataURL() should equal <canvas>.toDataURL()");
+compareAsync(jpegfile, canvas, "image/jpeg");
 is(jpegfile.name, "bar.jpg", "File name should be what we passed in");
 
 SimpleTest.finish();
 
 });
 </script>
 <img src="image_yellow75.png" id="yellow75.png" class="resource">
 
--- a/content/canvas/test/webgl/conformance/00_test_list.txt
+++ b/content/canvas/test/webgl/conformance/00_test_list.txt
@@ -59,17 +59,17 @@ is-object.html
 methods.html
 more-than-65536-points.html
 null-object-behaviour.html
 null-uniform-location.html
 object-deletion-behaviour.html
 oes-standard-derivatives.html
 oes-texture-float.html
 oes-vertex-array-object.html
-origin-clean-conformance.html
+# origin-clean-conformance.html # is obsolete because of bug 656277
 point-size.html
 program-test.html
 read-pixels-pack-alignment.html
 read-pixels-test.html
 renderbuffer-initialization.html
 resource-sharing-test.html
 tex-image-and-sub-image-2d-with-array-buffer-view.html
 tex-image-and-sub-image-2d-with-image-data.html
--- a/content/canvas/test/webgl/conformance/more/functions/readPixelsBadArgs.html
+++ b/content/canvas/test/webgl/conformance/more/functions/readPixelsBadArgs.html
@@ -70,16 +70,18 @@ Tests.testReadPixels = function(gl) {
           new Uint8Array(4*4));});
   // we can't know if this is going to fail because of negative width
   // or because the buffer size doesn't match the dimensions.
   assertSomeGLError(gl, "bad type",
       function(){gl.readPixels(0,0,1,1, gl.ALPHA, gl.FLOAT,
           new Uint8Array(1*4));});
 }
 
+/* this part is obsolete because of bug 656277
+ *
 Tests.testReadPixelsSOPIMG = function(gl) {
     var img = document.getElementById("i");
     while (!img.complete) {}
     var tex = gl.createTexture();
     gl.bindTexture(gl.TEXTURE_2D, tex);
     gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img);
     gl.bindTexture(gl.TEXTURE_2D, null);
     // SOP failure
@@ -100,16 +102,17 @@ Tests.testReadPixelsSOPCanvas = function
     gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, c);
     gl.bindTexture(gl.TEXTURE_2D, null);
     // SOP failure
     assertThrowNoGLError(gl, "throw because canvas is not origin clean",
       function(){gl.readPixels(0,0,1,1, gl.RGBA, gl.UNSIGNED_BYTE,
           new Uint8Array(4));});
     gl.deleteTexture(tex);
 }
+*/
 
 Tests.endUnit = function(gl) {
 }
 
 </script>
 </head><body>
 <canvas id="gl" width="16" height="16"></canvas>
 <canvas id="c" width="128" height="128"></canvas>
--- a/content/canvas/test/webgl/conformance/more/functions/texImage2DHTML.html
+++ b/content/canvas/test/webgl/conformance/more/functions/texImage2DHTML.html
@@ -141,11 +141,11 @@ void main()
     vec4 c = texture2D(Texture, texCoord0.st);
     gl_FragColor = c;
 }
 </script>
 </head><body>
 <canvas id="gl" width="256" height="256"></canvas>
 <canvas id="c" width="256" height="256"></canvas>
 <img id="i" width="256" height="256"  src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAATVElEQVR4nO3d+VPUd57Hcf2b9k9Y+z44+qK7OZoGFVA5VfBGzah9cxpNzGEOoRua5lBEue/DK4fZ7MapmSm3Mlshu8xOdCpDJt3v/aEBAUHAOMG4z0fV53fqU/V6fd7fT/e32bEDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwOvBkar7l+3+GwBsk8xUrT0rTb8vx2Q45janlu7YsWPnsgXgTeYwak85U3Xv5ZiM3+XbUh/l2dICBc6080WZ1ur92baSHRQB8GayGdUWu1HzoSNFO+ZM1f2cbTLM51lT5woc5rkDObbZ/Vm2SEm23VvsyjhV5nJQBsCbxGZQVtmN6p4Mo/YPdqNGHKlayUrXJ9zWlESh0xIvzsmYL3HZ54pzMm6VuRyRMpfTW+pyUAbAm8BmVNVnGNTTdqP6vzOMGrGnaMSZqpNsk17ybKlS6DTL/ixbotRlj5flOubL3I65MpfjVrnbEalYKINSl335vQGA3wKbUW2xGdWRDKP66wyjWhYLwJGiFWeaTrJNBnFbU2SP3ST7s6xSmmuXcrczUe52xstzHfPlbsdcudt5qyzX3lKWlxkszXGeK8mxnyzJySjeQRkArzebQVllM6p7bUb149UF4EjVSmaaTrLS9eKypMgee7ocyLZJmdshFXmZUpHnXFEGB/OzJsrdjqEyt/NmWa49XJbt9Ja6Mk4Vu7hEBF5LNr2q3mZQz9gM6u9XFEBqsgCcaTrJXJgEci0pstdhkv3ZNinNTZbAofwsOZSfJQfzMqU8z5kodzsSZbmOeIXb+XW52zFa5nLcKnPZI2ULl4jFfKIAvB7MOrXFZlBHbAb11zaj+kmGUbNuAWSm65dKYHdGmhRlWqQ8zyFHCnLk+L5cOV6UK0cKXVK5J1sO5mdKhdspZavKoDTX0VPiciTLIHtFGVAIwK/NYlBW2fTqXptB/dhmSJ7+LyqArHS95JiTJVDgNEllQZZ4KgulrrpU6qtLJXBsv5wt3yMn9rvlaIFLDi8vg1xH4mB+5p+Wl0Fpjr2lJMcRLM6ynyvOzjhxIIt7A+BXY9Gr6q0L4/9SAaRoxL7w/L9WAWSbDJJrTZFid4Z4jxZJU/1xufHhOem+ek6il0/LB74qaTxTJoGj++Vs2R45vj9XjhTkyOHdC48JC2VwaHfmnyrczn+vcDsmynLtQyU5GTeLczLCpTk2T3GW7VhxVsae7d4f4I1l1qktVoM6YjOovrYa1D8sFoB9WQE415kA8u1pcvRAjnwUOiLDLQG5190o9242ylRHnQyG/XLz6nmJXqqWD3yV0nC6VPxH98nZst1yfF+uHC10SdXebDmUnyyDqoLs7w7lZ35b7nb8scxt/7dSl32kJCejqyQn40pJTkbZDiYC4NWzaJVVVr2q12ZQPbYa1H9fuwB0SwWQla6XLFOyAAoyTfLW4T3SfuWM3L3RIA/7L8vD/svyZe8l+ezW23Kvu1EmO2ploNkn3VfPSevb1fK+t1Iaz5RJ7cli8R0pktOl+XKsKFkGBxfKoHJv1l8P5mf+uSLP8fvyXMdMmdsRKXc5qotdGQXbvV/AG8WiV9Vb9aoZq141azOoxWbcXAHkWlOkJC9Dak8Xy61PL8iDnotLBbBUBH2X5Yvbl+RBz0W5e6NBJtprpL/ZJzc/Oi/XP3hLWi6ekvc8h6WuukS8Vc/KYPEC8WhhzpOqguzvKvdmfXV4d2b3wfzM9w/lZTENAK+CWaewWHWqiE2v+tqqV/2w2QLINhkkP2Nh/K89ImNtIfmi99Kz8Pcl15dL65J80XtJPr/1tty/2Sh3uxvkzvV6GY+FpO+aV65/8DuJXDwpVzyHpO7UQhmU5MvRIpdU7c2RQ7uz5MR+9x+OFbnuHi3MiVQVuKoP784u2u79A37TLFpllVWn6rXqVY+tetWPGxbAsgvAvU6TvHVot8SunJY7N+rly761g/9lb3J9sWx9fvuSfH77bXnQc1HudTfITFedjLWFpPeaR7o+eEvCjSflyoVDUlddKsHjB+TC4UI5VZwnVQU5ibcq9nx1ujS/58QB99XqYnf5DqYB4OVYdM/Gf6te9Y/k8//GBeCyGKXEnSE11Qek55Pzcv9m48rQrxP8L25fki9uvy2fr1qf3bqYnAxuNMh0Z52MRINy+1OPXP/wd9J+5Yw015+Qd84flJqTxXLhcIGcLM77+UhBzt8uVBa2nqvce/ZsxZ6y7d5L4Ddlcfy36FVfW/SqH6wGlawugMWvATvTlhWAySB5GalydH+OfFRzREajQfn81tvrh/6FwV9cF+WzWxflwa2Lcr/notzrbpSZ6/Uy1VUnkx21MtwSkJ5PLkjHe2elqf64XD53UEInDiQuHC6Yry7Omz1W5HrY+FbF4R1MA8DmWLTKKsuy8d9qUL+wAJZ/C3CPM13OHtwtbe+elunr9fLFusF/PvSf31o7+A96nq37PRflfk+j3L+Z/Fjx7o0Gme6qk4n2Ghlq8UvPx+el/coZuVZ3XC6fq/i57lTx32pOHngUOlUc/jR4lEtCYCMWnareolfNWPSqWatB9dOaBbDGl4BcFqMUu20SOnVAbn58Tu52N27qtP98g9A/WAz9QvAX173FEuhukLvdDcnJoLNWxmM1Mhjxy82Pzknn+2cSsXdPz4cbT8x+GKh8+FHwSO0OSgBYm1mnsJh1qohFr1wY/5XxZwWw/teAs9KTvwtwZH+2XA1VyXBrUB70XFz/tF9nzN9K8O91N8i9hfAvrjs3GuTOjXqZXnhEGG+vkdFoUAbD/p97Pj7/t56r57/pu+b5pOXd6qPbvdfAa8ei3VVl0al6LXrlY4tO+aNFr0pstgD2ONLlzMHdEn2nWqY66+SzlxzzHywb858L/TrBv3vjWfgX18z15JruqpOpzlqZaA8lxmKhv49Gg3/oD/s+3u69Bl47Fp2i3qJVzVh0ylmrTvmTVZ+8AFz5HsDzBZBjNkpxrk2Cpw5I90fn5M6Nhhee9lsOfvfmg3/n+rPwz1yvk5muOpleWJMdtfHJjprvJjtqKABgueT4r4iYdcqvzbpdP1j0yvjqArCv9SJQul7ctlSp2pctHwYrZaglIPdvNq5/2r/gYm9Twb+x9eBPd9XJVHISmJ/qrP1murOGRwBgOZN2V5VFp+y1aBfGf50ysVQAa3wHYLEAstL1stuRLqcr8qX18imZ7KiVBz0XXxj6jZ/vNxn86xsHP/kIUCdTnXXx6c7av0x11PRs914Drx2TTlFv0ipmzDrlrEWn/MmiV8lmCiDbbJADuTYJntwvN67+Tmau1ydDvmbot36x9yz49S8Z/NrFNT/dVfv7qc66k9u918BrxaxePf4r4hsVgHPh9wBzrSlSVZQtHwQqZTDil7vdjVs77bcY/JmtB1+mOmsTkx21T6a6ake2e6+B145Ju6vKpFP2mrTKx2bts/F/8VuALyqA3fY0OV2eLy2XTspEe43cf8Gz/TYEXyY7amWyoyY+1VHz/VRnXfN27zXw2lka/7XKWYtW+ZNFp5TNFEC2ySD7XVYJnNgnXR++JdNddZs+7X+d4NfKZEeNTHbUzE921Dya5PIPWClNrbCYtcnx36Td9YNZp4hbdKqNC2Bh/K8szJL3/YdlIOyTOzcatvwx3sY3+r8o+DLZEUpMtNc8mehg/AeeY1LvqjJplb0mjeKxWav40axVJlYXwFpvAmam6STfnibVZXkSefukjMVCcrd7EyP+eqf9loJfu2HwJzpqZKK9RsbbQ/HJ9tD3k501jP/AaiaNot6kSY7/Zq3iJ7NOKYsXgC8qgCyTQfblWMV/fJ90fnBWJjtrV4z3Wzntn7vRv/586Lca/GcrND/RHno02c74D6yQplZYTFpFxKRVLI3/Kwvg+ReB7CnJ3wFwWVLkcGGWvOc/LP3NXpm5Xv/LT/tNBn9yE8EfT4Y/MR4LPRlvDzH+A6uZNYpKk3ZXb/rC+G/SKhKbLYC8jDQ5VZYn4YsnZLQtKHdubC70mx3zf0nwx9tDMh4LyVgsFB+PBb8fb2f8B56TrlHUp2sV0yaNYmn830wBZKXrZV+2RXzH90nH+2dloqMmWQCv4LR/+eCHloK/EH4ZjwXnx2PBR2PtQcZ/YDmTRpmarlY0mTS7vkrTKP5q0ip+NuuUYtmgABypWnFZjHKoIFOueA9JX5NHprvqNh36zZ72vyT4C+FPjLYFn4zHgoz/wGomza7d6ZpdMZNG8Y1Jo3hi1i48/2+iAPIyUuVkqVuaGk/ISDQoM9df3Wm/Mvg1Ww7+WCwkY21BGW0Lxkfbgt+PxUKM/8BqaZpdu9PUiiaTRvGVSav4y9InABsUQGa6XoqyLeI9ViTt752R8fbQqsC/4tN+i8EfawvKaDQoI9HA/Ghb8JuxKOM/8ByT5l9T09SKQLpGMWTSKv7TrFU8NeuUieUFYFv1YyCOVK3kmJPj/7veg9J7zSNTnbWv6LR/BcFfWCPRQHwkGvjLSDTAm3/AetLVyjyTRvmOSauYNOsU35p1yn9sVABuW6qcLM2Vaw3HZbg1INNdr+a0X/sz/K0FfzQalNFoIHn6RwO/H2kL8uYf8CImza5Ck27Xe2atcsqiU8bXLYAUjWSm66QwyyzeY4USu3JaxmKhtUP/i0/7mhWhXxH8tvWCH5SRaEBGo4HESKv/yWhrgMs/YDPSdcois1bxvkWnfGrRK+NrFYA9RSvZZoMc3OuUdzwH5fa1CzLRUfNPPe3H1zjt1wv+4hpuDcRHooHvR6IBLv+AzTLrlEVmnfKhRad8al3z58C04ralyImSXLnWcEyGWv0y2VkrU13Ph/6lTvsNgj+6QfBHWgMy3BqQ4Vb//HBr4NFI1M/lH7AVFr0qYNGrHlr1qqc2gyq+/E1AZ5pOCrNM4jlaIG1XTstoW/Cfd9q/VPADMtzqTwy3+J8MM/4DL2XnihIwquI2o1rsKRrJNhmkYq9DLl+okFufnJfx9ppnoV/vc/utnvaxNcb8TQU/IMOtfhlq8ceHW/zfD0cDF7Z7I4Hfqp02vSpg06se2gzqpxlGTdyeopFca4ocL3HJp/VHZTDik4mOzY34L33ab+7EXwz+wvLND7cEbo20BjK3exOB37KdNqM6YDOoH2YY1U+dabp4QaZJLhzZK9F3q2UkGpCJDU/70Ks77TcMvl+GWnyJwYjvyVBL4J3t3jzgTbDTZlQHMoyah9lm/dOKPc74pfPl0vPxORmLhX6d035TwV9YEV98sMU/NRDm8g94VXbaU7UBl8X48ESJ6+kn9Ud+Hgh7EuPtoVdz2rdtJvQvDv5gxLewvH8ciHg7hloClu3eNOBNstNtSw34jxc9bH2nenaoxTc33h6aH4uF4uPtwcR48n/u/RNO+80G3ydDEd//DIR99wbCvsbt3izgTbTzaqgy0PPxufBINBAbbw89Go+FZsdjobnx9tDcaCw4P9oWjI/FgomxWCAx+gpO++G1xvxVwR+M+GQw7P1xMOx7PBj29fZHvFXbvVHAm2rn4prsrKkd6wiFR9tDsfH2mthILPRorC04O9YWmhuNheZG2wLzI9FgfLQtkBiNBhLPhf4XnPaLayDik4GwTwbC3v8daPY+HIj4Pupv9jL+A7+CncvXeHtN7WgsGB6NhWKjsVBsJBp8NBoNzo5EA3MLa364NRAfafUnhpPr5U77lcGXgbD37wNhz5/7m70jA2HPmW3eE+D/rZWF0BasHW4LhkeigdhILBQbbg08Gm4NzA63+OeGW/xzQ63++aEWf3yoxZdIrmWhb3k+9INLoV8KvvQ3e+MDzd4f+ps9/9Ef9rYNRHyObd4DAAtWFMJoW7B2uDUYHooGYkPRQGyoxf9oqMU3OxTxzQ1FfHNDLb75oYgvPhjxJpZWeO3gJ8PvSfQ3eX8aCHtn+5u9M33NXP4Br7MVhTDcGqgdbvWHB1v9scFWf2ww4n80GPHNDoa9c4MR39xg2Ds3EPbOD4S98YGwJzEQ9iT6m73S3+yVvmbPfH+zZ76vyfO0v9n7p75mb29/M5d/wG/Jc4Uw1OIP90f8scGIP9Yf8ccGwr5HA2Hv7ECzd26g2TvXlwx9vK/Z821/s+e/+po83/Y3eT7ra/Y0cfkH/LbtXL2GWny1A2FfuC/sjfWHvbH+Zs+jvrD3Zm+TZ6i3yTPW1+yZ7GvyXO9r9vi3908H8M+wohB6m7xlt695Tw6EfecGw15ff5Pnnb5mT6D32oUD2/x3AvgV7dyxY8fOgSavu7/Jk9V3zave7j8IAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICV/g9tPJEQu1XvmQAAAABJRU5ErkJggg==">
-<img id="i2" src="http://example.com/tests/content/canvas/test/webgl/resources/thunderbird-logo-64x64.png">
+<img id="i2" src="http://mochi.test:8888/tests/content/canvas/test/webgl/resources/thunderbird-logo-64x64.png">
 
 </body></html>
--- a/content/canvas/test/webgl/conformance/more/functions/texSubImage2DHTML.html
+++ b/content/canvas/test/webgl/conformance/more/functions/texSubImage2DHTML.html
@@ -151,11 +151,11 @@ void main()
     vec4 c = texture2D(Texture, texCoord0.st);
     gl_FragColor = c;
 }
 </script>
 </head><body>
 <canvas id="gl" width="256" height="256"></canvas>
 <canvas id="c" width="256" height="256"></canvas>
 <img id="i" width="256" height="256"  src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAATVElEQVR4nO3d+VPUd57Hcf2b9k9Y+z44+qK7OZoGFVA5VfBGzah9cxpNzGEOoRua5lBEue/DK4fZ7MapmSm3Mlshu8xOdCpDJt3v/aEBAUHAOMG4z0fV53fqU/V6fd7fT/e32bEDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwOvBkar7l+3+GwBsk8xUrT0rTb8vx2Q45janlu7YsWPnsgXgTeYwak85U3Xv5ZiM3+XbUh/l2dICBc6080WZ1ur92baSHRQB8GayGdUWu1HzoSNFO+ZM1f2cbTLM51lT5woc5rkDObbZ/Vm2SEm23VvsyjhV5nJQBsCbxGZQVtmN6p4Mo/YPdqNGHKlayUrXJ9zWlESh0xIvzsmYL3HZ54pzMm6VuRyRMpfTW+pyUAbAm8BmVNVnGNTTdqP6vzOMGrGnaMSZqpNsk17ybKlS6DTL/ixbotRlj5flOubL3I65MpfjVrnbEalYKINSl335vQGA3wKbUW2xGdWRDKP66wyjWhYLwJGiFWeaTrJNBnFbU2SP3ST7s6xSmmuXcrczUe52xstzHfPlbsdcudt5qyzX3lKWlxkszXGeK8mxnyzJySjeQRkArzebQVllM6p7bUb149UF4EjVSmaaTrLS9eKypMgee7ocyLZJmdshFXmZUpHnXFEGB/OzJsrdjqEyt/NmWa49XJbt9Ja6Mk4Vu7hEBF5LNr2q3mZQz9gM6u9XFEBqsgCcaTrJXJgEci0pstdhkv3ZNinNTZbAofwsOZSfJQfzMqU8z5kodzsSZbmOeIXb+XW52zFa5nLcKnPZI2ULl4jFfKIAvB7MOrXFZlBHbAb11zaj+kmGUbNuAWSm65dKYHdGmhRlWqQ8zyFHCnLk+L5cOV6UK0cKXVK5J1sO5mdKhdspZavKoDTX0VPiciTLIHtFGVAIwK/NYlBW2fTqXptB/dhmSJ7+LyqArHS95JiTJVDgNEllQZZ4KgulrrpU6qtLJXBsv5wt3yMn9rvlaIFLDi8vg1xH4mB+5p+Wl0Fpjr2lJMcRLM6ynyvOzjhxIIt7A+BXY9Gr6q0L4/9SAaRoxL7w/L9WAWSbDJJrTZFid4Z4jxZJU/1xufHhOem+ek6il0/LB74qaTxTJoGj++Vs2R45vj9XjhTkyOHdC48JC2VwaHfmnyrczn+vcDsmynLtQyU5GTeLczLCpTk2T3GW7VhxVsae7d4f4I1l1qktVoM6YjOovrYa1D8sFoB9WQE415kA8u1pcvRAjnwUOiLDLQG5190o9242ylRHnQyG/XLz6nmJXqqWD3yV0nC6VPxH98nZst1yfF+uHC10SdXebDmUnyyDqoLs7w7lZ35b7nb8scxt/7dSl32kJCejqyQn40pJTkbZDiYC4NWzaJVVVr2q12ZQPbYa1H9fuwB0SwWQla6XLFOyAAoyTfLW4T3SfuWM3L3RIA/7L8vD/svyZe8l+ezW23Kvu1EmO2ploNkn3VfPSevb1fK+t1Iaz5RJ7cli8R0pktOl+XKsKFkGBxfKoHJv1l8P5mf+uSLP8fvyXMdMmdsRKXc5qotdGQXbvV/AG8WiV9Vb9aoZq141azOoxWbcXAHkWlOkJC9Dak8Xy61PL8iDnotLBbBUBH2X5Yvbl+RBz0W5e6NBJtprpL/ZJzc/Oi/XP3hLWi6ekvc8h6WuukS8Vc/KYPEC8WhhzpOqguzvKvdmfXV4d2b3wfzM9w/lZTENAK+CWaewWHWqiE2v+tqqV/2w2QLINhkkP2Nh/K89ImNtIfmi99Kz8Pcl15dL65J80XtJPr/1tty/2Sh3uxvkzvV6GY+FpO+aV65/8DuJXDwpVzyHpO7UQhmU5MvRIpdU7c2RQ7uz5MR+9x+OFbnuHi3MiVQVuKoP784u2u79A37TLFpllVWn6rXqVY+tetWPGxbAsgvAvU6TvHVot8SunJY7N+rly761g/9lb3J9sWx9fvuSfH77bXnQc1HudTfITFedjLWFpPeaR7o+eEvCjSflyoVDUlddKsHjB+TC4UI5VZwnVQU5ibcq9nx1ujS/58QB99XqYnf5DqYB4OVYdM/Gf6te9Y/k8//GBeCyGKXEnSE11Qek55Pzcv9m48rQrxP8L25fki9uvy2fr1qf3bqYnAxuNMh0Z52MRINy+1OPXP/wd9J+5Yw015+Qd84flJqTxXLhcIGcLM77+UhBzt8uVBa2nqvce/ZsxZ6y7d5L4Ddlcfy36FVfW/SqH6wGlawugMWvATvTlhWAySB5GalydH+OfFRzREajQfn81tvrh/6FwV9cF+WzWxflwa2Lcr/notzrbpSZ6/Uy1VUnkx21MtwSkJ5PLkjHe2elqf64XD53UEInDiQuHC6Yry7Omz1W5HrY+FbF4R1MA8DmWLTKKsuy8d9qUL+wAJZ/C3CPM13OHtwtbe+elunr9fLFusF/PvSf31o7+A96nq37PRflfk+j3L+Z/Fjx7o0Gme6qk4n2Ghlq8UvPx+el/coZuVZ3XC6fq/i57lTx32pOHngUOlUc/jR4lEtCYCMWnareolfNWPSqWatB9dOaBbDGl4BcFqMUu20SOnVAbn58Tu52N27qtP98g9A/WAz9QvAX173FEuhukLvdDcnJoLNWxmM1Mhjxy82Pzknn+2cSsXdPz4cbT8x+GKh8+FHwSO0OSgBYm1mnsJh1qohFr1wY/5XxZwWw/teAs9KTvwtwZH+2XA1VyXBrUB70XFz/tF9nzN9K8O91N8i9hfAvrjs3GuTOjXqZXnhEGG+vkdFoUAbD/p97Pj7/t56r57/pu+b5pOXd6qPbvdfAa8ei3VVl0al6LXrlY4tO+aNFr0pstgD2ONLlzMHdEn2nWqY66+SzlxzzHywb858L/TrBv3vjWfgX18z15JruqpOpzlqZaA8lxmKhv49Gg3/oD/s+3u69Bl47Fp2i3qJVzVh0ylmrTvmTVZ+8AFz5HsDzBZBjNkpxrk2Cpw5I90fn5M6Nhhee9lsOfvfmg3/n+rPwz1yvk5muOpleWJMdtfHJjprvJjtqKABgueT4r4iYdcqvzbpdP1j0yvjqArCv9SJQul7ctlSp2pctHwYrZaglIPdvNq5/2r/gYm9Twb+x9eBPd9XJVHISmJ/qrP1murOGRwBgOZN2V5VFp+y1aBfGf50ysVQAa3wHYLEAstL1stuRLqcr8qX18imZ7KiVBz0XXxj6jZ/vNxn86xsHP/kIUCdTnXXx6c7av0x11PRs914Drx2TTlFv0ipmzDrlrEWn/MmiV8lmCiDbbJADuTYJntwvN67+Tmau1ydDvmbot36x9yz49S8Z/NrFNT/dVfv7qc66k9u918BrxaxePf4r4hsVgHPh9wBzrSlSVZQtHwQqZTDil7vdjVs77bcY/JmtB1+mOmsTkx21T6a6ake2e6+B145Ju6vKpFP2mrTKx2bts/F/8VuALyqA3fY0OV2eLy2XTspEe43cf8Gz/TYEXyY7amWyoyY+1VHz/VRnXfN27zXw2lka/7XKWYtW+ZNFp5TNFEC2ySD7XVYJnNgnXR++JdNddZs+7X+d4NfKZEeNTHbUzE921Dya5PIPWClNrbCYtcnx36Td9YNZp4hbdKqNC2Bh/K8szJL3/YdlIOyTOzcatvwx3sY3+r8o+DLZEUpMtNc8mehg/AeeY1LvqjJplb0mjeKxWav40axVJlYXwFpvAmam6STfnibVZXkSefukjMVCcrd7EyP+eqf9loJfu2HwJzpqZKK9RsbbQ/HJ9tD3k501jP/AaiaNot6kSY7/Zq3iJ7NOKYsXgC8qgCyTQfblWMV/fJ90fnBWJjtrV4z3Wzntn7vRv/586Lca/GcrND/RHno02c74D6yQplZYTFpFxKRVLI3/Kwvg+ReB7CnJ3wFwWVLkcGGWvOc/LP3NXpm5Xv/LT/tNBn9yE8EfT4Y/MR4LPRlvDzH+A6uZNYpKk3ZXb/rC+G/SKhKbLYC8jDQ5VZYn4YsnZLQtKHdubC70mx3zf0nwx9tDMh4LyVgsFB+PBb8fb2f8B56TrlHUp2sV0yaNYmn830wBZKXrZV+2RXzH90nH+2dloqMmWQCv4LR/+eCHloK/EH4ZjwXnx2PBR2PtQcZ/YDmTRpmarlY0mTS7vkrTKP5q0ip+NuuUYtmgABypWnFZjHKoIFOueA9JX5NHprvqNh36zZ72vyT4C+FPjLYFn4zHgoz/wGomza7d6ZpdMZNG8Y1Jo3hi1i48/2+iAPIyUuVkqVuaGk/ISDQoM9df3Wm/Mvg1Ww7+WCwkY21BGW0Lxkfbgt+PxUKM/8BqaZpdu9PUiiaTRvGVSav4y9InABsUQGa6XoqyLeI9ViTt752R8fbQqsC/4tN+i8EfawvKaDQoI9HA/Ghb8JuxKOM/8ByT5l9T09SKQLpGMWTSKv7TrFU8NeuUieUFYFv1YyCOVK3kmJPj/7veg9J7zSNTnbWv6LR/BcFfWCPRQHwkGvjLSDTAm3/AetLVyjyTRvmOSauYNOsU35p1yn9sVABuW6qcLM2Vaw3HZbg1INNdr+a0X/sz/K0FfzQalNFoIHn6RwO/H2kL8uYf8CImza5Ck27Xe2atcsqiU8bXLYAUjWSm66QwyyzeY4USu3JaxmKhtUP/i0/7mhWhXxH8tvWCH5SRaEBGo4HESKv/yWhrgMs/YDPSdcois1bxvkWnfGrRK+NrFYA9RSvZZoMc3OuUdzwH5fa1CzLRUfNPPe3H1zjt1wv+4hpuDcRHooHvR6IBLv+AzTLrlEVmnfKhRad8al3z58C04ralyImSXLnWcEyGWv0y2VkrU13Ph/6lTvsNgj+6QfBHWgMy3BqQ4Vb//HBr4NFI1M/lH7AVFr0qYNGrHlr1qqc2gyq+/E1AZ5pOCrNM4jlaIG1XTstoW/Cfd9q/VPADMtzqTwy3+J8MM/4DL2XnihIwquI2o1rsKRrJNhmkYq9DLl+okFufnJfx9ppnoV/vc/utnvaxNcb8TQU/IMOtfhlq8ceHW/zfD0cDF7Z7I4Hfqp02vSpg06se2gzqpxlGTdyeopFca4ocL3HJp/VHZTDik4mOzY34L33ab+7EXwz+wvLND7cEbo20BjK3exOB37KdNqM6YDOoH2YY1U+dabp4QaZJLhzZK9F3q2UkGpCJDU/70Ks77TcMvl+GWnyJwYjvyVBL4J3t3jzgTbDTZlQHMoyah9lm/dOKPc74pfPl0vPxORmLhX6d035TwV9YEV98sMU/NRDm8g94VXbaU7UBl8X48ESJ6+kn9Ud+Hgh7EuPtoVdz2rdtJvQvDv5gxLewvH8ciHg7hloClu3eNOBNstNtSw34jxc9bH2nenaoxTc33h6aH4uF4uPtwcR48n/u/RNO+80G3ydDEd//DIR99wbCvsbt3izgTbTzaqgy0PPxufBINBAbbw89Go+FZsdjobnx9tDcaCw4P9oWjI/FgomxWCAx+gpO++G1xvxVwR+M+GQw7P1xMOx7PBj29fZHvFXbvVHAm2rn4prsrKkd6wiFR9tDsfH2mthILPRorC04O9YWmhuNheZG2wLzI9FgfLQtkBiNBhLPhf4XnPaLayDik4GwTwbC3v8daPY+HIj4Pupv9jL+A7+CncvXeHtN7WgsGB6NhWKjsVBsJBp8NBoNzo5EA3MLa364NRAfafUnhpPr5U77lcGXgbD37wNhz5/7m70jA2HPmW3eE+D/rZWF0BasHW4LhkeigdhILBQbbg08Gm4NzA63+OeGW/xzQ63++aEWf3yoxZdIrmWhb3k+9INLoV8KvvQ3e+MDzd4f+ps9/9Ef9rYNRHyObd4DAAtWFMJoW7B2uDUYHooGYkPRQGyoxf9oqMU3OxTxzQ1FfHNDLb75oYgvPhjxJpZWeO3gJ8PvSfQ3eX8aCHtn+5u9M33NXP4Br7MVhTDcGqgdbvWHB1v9scFWf2ww4n80GPHNDoa9c4MR39xg2Ds3EPbOD4S98YGwJzEQ9iT6m73S3+yVvmbPfH+zZ76vyfO0v9n7p75mb29/M5d/wG/Jc4Uw1OIP90f8scGIP9Yf8ccGwr5HA2Hv7ECzd26g2TvXlwx9vK/Z821/s+e/+po83/Y3eT7ra/Y0cfkH/LbtXL2GWny1A2FfuC/sjfWHvbH+Zs+jvrD3Zm+TZ6i3yTPW1+yZ7GvyXO9r9vi3908H8M+wohB6m7xlt695Tw6EfecGw15ff5Pnnb5mT6D32oUD2/x3AvgV7dyxY8fOgSavu7/Jk9V3zave7j8IAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICV/g9tPJEQu1XvmQAAAABJRU5ErkJggg==">
-<img id="i2" src="http://example.com/tests/content/canvas/test/webgl/resources/thunderbird-logo-64x64.png">
+<img id="i2" src="http://mochi.test:8888/tests/content/canvas/test/webgl/resources/thunderbird-logo-64x64.png">
 
 </body></html>
--- a/content/events/public/nsEventStates.h
+++ b/content/events/public/nsEventStates.h
@@ -237,19 +237,17 @@ private:
 #define NS_EVENT_STATE_USERDISABLED  NS_DEFINE_EVENT_STATE_MACRO(20)
 // Content suppressed by the user (ad blocking, etc).
 #define NS_EVENT_STATE_SUPPRESSED    NS_DEFINE_EVENT_STATE_MACRO(21)
 // Content is still loading such that there is nothing to show the
 // user (eg an image which hasn't started coming in yet).
 #define NS_EVENT_STATE_LOADING       NS_DEFINE_EVENT_STATE_MACRO(22)
 // Content is of a type that gecko can't handle.
 #define NS_EVENT_STATE_TYPE_UNSUPPORTED NS_DEFINE_EVENT_STATE_MACRO(23)
-#ifdef MOZ_MATHML
 #define NS_EVENT_STATE_INCREMENT_SCRIPT_LEVEL NS_DEFINE_EVENT_STATE_MACRO(24)
-#endif
 // Handler for the content has been blocked.
 #define NS_EVENT_STATE_HANDLER_BLOCKED NS_DEFINE_EVENT_STATE_MACRO(25)
 // Handler for the content has been disabled.
 #define NS_EVENT_STATE_HANDLER_DISABLED NS_DEFINE_EVENT_STATE_MACRO(26)
 // Content is in the indeterminate state.
 #define NS_EVENT_STATE_INDETERMINATE NS_DEFINE_EVENT_STATE_MACRO(27)
 // Handler for the content has crashed
 #define NS_EVENT_STATE_HANDLER_CRASHED NS_DEFINE_EVENT_STATE_MACRO(28)
--- a/content/events/src/nsEventStateManager.cpp
+++ b/content/events/src/nsEventStateManager.cpp
@@ -765,17 +765,17 @@ nsMouseWheelTransaction::LimitToOnePageS
   nscoord lineScroll = aIsHorizontal ? lineAmount.width : lineAmount.height;
 
   if (lineScroll == 0)
     return aScrollLines;
 
   nsSize pageAmount = sf->GetPageScrollAmount();
   nscoord pageScroll = aIsHorizontal ? pageAmount.width : pageAmount.height;
 
-  if (PR_ABS(aScrollLines) * lineScroll < pageScroll)
+  if (NS_ABS(aScrollLines) * lineScroll < pageScroll)
     return aScrollLines;
 
   nscoord maxLines = (pageScroll / lineScroll);
   if (maxLines >= 1)
     return ((aScrollLines < 0) ? -1 : 1) * maxLines;
 
   *aScrollQuantity = nsIScrollableFrame::PAGES;
   return (aScrollLines < 0) ? -1 : 1;
@@ -858,16 +858,19 @@ nsEventStateManager::Init()
   nsCOMPtr<nsIObserverService> observerService =
     mozilla::services::GetObserverService();
   if (!observerService)
     return NS_ERROR_FAILURE;
 
   observerService->AddObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, PR_TRUE);
 
   if (sESMInstanceCount == 1) {
+    sKeyCausesActivation =
+      Preferences::GetBool("accessibility.accesskeycausesactivation",
+                           sKeyCausesActivation);
     sLeftClickOnly =
       Preferences::GetBool("nglayout.events.dispatchLeftClickOnly",
                            sLeftClickOnly);
     sChromeAccessModifier =
       GetAccessModifierMaskFromPref(nsIDocShellTreeItem::typeChrome);
     sContentAccessModifier =
       GetAccessModifierMaskFromPref(nsIDocShellTreeItem::typeContent);
   }
@@ -1267,32 +1270,32 @@ nsEventStateManager::PreHandleEvent(nsPr
         nscoord pixelHeight = aPresContext->AppUnitsToIntCSSPixels(
           GetScrollableLineHeight(aTargetFrame));
 
         if (msEvent->scrollFlags & nsMouseScrollEvent::kIsVertical) {
           gPixelScrollDeltaX += msEvent->delta;
           if (!gPixelScrollDeltaX || !pixelHeight)
             break;
 
-          if (PR_ABS(gPixelScrollDeltaX) >= pixelHeight) {
+          if (NS_ABS(gPixelScrollDeltaX) >= pixelHeight) {
             PRInt32 numLines = (PRInt32)ceil((float)gPixelScrollDeltaX/(float)pixelHeight);
 
             gPixelScrollDeltaX -= numLines*pixelHeight;
 
             nsWeakFrame weakFrame(aTargetFrame);
             SendLineScrollEvent(aTargetFrame, msEvent, aPresContext,
               aStatus, numLines);
             NS_ENSURE_STATE(weakFrame.IsAlive());
           }
         } else if (msEvent->scrollFlags & nsMouseScrollEvent::kIsHorizontal) {
           gPixelScrollDeltaY += msEvent->delta;
           if (!gPixelScrollDeltaY || !pixelHeight)
             break;
 
-          if (PR_ABS(gPixelScrollDeltaY) >= pixelHeight) {
+          if (NS_ABS(gPixelScrollDeltaY) >= pixelHeight) {
             PRInt32 numLines = (PRInt32)ceil((float)gPixelScrollDeltaY/(float)pixelHeight);
 
             gPixelScrollDeltaY -= numLines*pixelHeight;
 
             nsWeakFrame weakFrame(aTargetFrame);
             SendLineScrollEvent(aTargetFrame, msEvent, aPresContext,
               aStatus, numLines);
             NS_ENSURE_STATE(weakFrame.IsAlive());
@@ -1985,18 +1988,18 @@ nsEventStateManager::GenerateDragGesture
       if (!pixelThresholdX)
         pixelThresholdX = 5;
       if (!pixelThresholdY)
         pixelThresholdY = 5;
     }
 
     // fire drag gesture if mouse has moved enough
     nsIntPoint pt = aEvent->refPoint + aEvent->widget->WidgetToScreenOffset();
-    if (PR_ABS(pt.x - mGestureDownPoint.x) > pixelThresholdX ||
-        PR_ABS(pt.y - mGestureDownPoint.y) > pixelThresholdY) {
+    if (NS_ABS(pt.x - mGestureDownPoint.x) > pixelThresholdX ||
+        NS_ABS(pt.y - mGestureDownPoint.y) > pixelThresholdY) {
       if (mClickHoldContextMenu) {
         // stop the click-hold before we fire off the drag gesture, in case
         // it takes a long time
         KillClickHoldTimer();
       }
 
       nsRefPtr<nsDOMDataTransfer> dataTransfer = new nsDOMDataTransfer();
       if (!dataTransfer)
--- a/content/html/content/src/nsGenericHTMLElement.cpp
+++ b/content/html/content/src/nsGenericHTMLElement.cpp
@@ -17,16 +17,17 @@
  *
  * The Initial Developer of the Original Code is
  * Netscape Communications Corporation.
  * Portions created by the Initial Developer are Copyright (C) 1998
  * the Initial Developer. All Rights Reserved.
  *
  * Contributor(s):
  *   Mats Palmgren <mats.palmgren@bredband.net>
+ *   Ms2ger <ms2ger@gmail.com>
  *
  * Alternatively, the contents of this file may be used under the terms of
  * either of the GNU General Public License Version 2 or later (the "GPL"),
  * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  * in which case the provisions of the GPL or the LGPL are applicable instead
  * of those above. If you wish to allow use of your version of this file only
  * under the terms of either the GPL or the LGPL, and not to allow others to
  * use your version of this file under the terms of the MPL, indicate your
@@ -439,37 +440,17 @@ nsGenericHTMLElement::SetLang(const nsAS
 }
 
 static const nsAttrValue::EnumTable kDirTable[] = {
   { "ltr", NS_STYLE_DIRECTION_LTR },
   { "rtl", NS_STYLE_DIRECTION_RTL },
   { 0 }
 };
 
-nsresult
-nsGenericHTMLElement::GetDir(nsAString& aDir)
-{
-  const nsAttrValue* attr = mAttrsAndChildren.GetAttr(nsGkAtoms::dir);
-
-  if (attr && attr->Type() == nsAttrValue::eEnum) {
-    attr->ToString(aDir);
-  }
-  else {
-    aDir.Truncate();
-  }
-
-  return NS_OK;
-}
-
-nsresult
-nsGenericHTMLElement::SetDir(const nsAString& aDir)
-{
-  SetAttr(kNameSpaceID_None, nsGkAtoms::dir, aDir, PR_TRUE);
-  return NS_OK;
-}
+NS_IMPL_ENUM_ATTR_DEFAULT_VALUE(nsGenericHTMLElement, Dir, dir, NULL)
 
 nsresult
 nsGenericHTMLElement::GetClassName(nsAString& aClassName)
 {
   GetAttr(kNameSpaceID_None, nsGkAtoms::_class, aClassName);
   return NS_OK;
 }
 
@@ -2326,17 +2307,17 @@ nsGenericHTMLElement::GetEnumAttr(nsIAto
                                   nsAString& aResult)
 {
   const nsAttrValue* attrVal = mAttrsAndChildren.GetAttr(aAttr);
 
   aResult.Truncate();
 
   if (attrVal && attrVal->Type() == nsAttrValue::eEnum) {
     attrVal->GetEnumString(aResult, PR_TRUE);
-  } else {
+  } else if (aDefault) {
     AppendASCIItoUTF16(nsDependentCString(aDefault), aResult);
   }
 
   return NS_OK;
 }
 
 nsresult
 nsGenericHTMLElement::GetContentEditable(nsAString& aContentEditable)
--- a/content/html/content/src/nsGenericHTMLElement.h
+++ b/content/html/content/src/nsGenericHTMLElement.h
@@ -111,18 +111,18 @@ public:
   // methods, implementations are expected to forward calls to these
   // methods.
   nsresult GetId(nsAString& aId);
   nsresult SetId(const nsAString& aId);
   nsresult GetTitle(nsAString& aTitle);
   nsresult SetTitle(const nsAString& aTitle);
   nsresult GetLang(nsAString& aLang);
   nsresult SetLang(const nsAString& aLang);
-  nsresult GetDir(nsAString& aDir);
-  nsresult SetDir(const nsAString& aDir);
+  NS_IMETHOD GetDir(nsAString& aDir);
+  NS_IMETHOD SetDir(const nsAString& aDir);
   nsresult GetClassName(nsAString& aClassName);
   nsresult SetClassName(const nsAString& aClassName);
 
   // nsIDOMNSHTMLElement methods. Note that these are non-virtual
   // methods, implementations are expected to forward calls to these
   // methods.
   nsresult GetOffsetTop(PRInt32* aOffsetTop);
   nsresult GetOffsetLeft(PRInt32* aOffsetLeft);
--- a/content/html/content/src/nsHTMLBodyElement.cpp
+++ b/content/html/content/src/nsHTMLBodyElement.cpp
@@ -16,16 +16,17 @@
  *
  * The Initial Developer of the Original Code is
  * Netscape Communications Corporation.
  * Portions created by the Initial Developer are Copyright (C) 1998
  * the Initial Developer. All Rights Reserved.
  *
  * Contributor(s):
  *   Daniel Glazman <glazman@netscape.com>
+ *   Ms2ger <ms2ger@gmail.com>
  *
  * Alternatively, the contents of this file may be used under the terms of
  * either of the GNU General Public License Version 2 or later (the "GPL"),
  * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  * in which case the provisions of the GPL or the LGPL are applicable instead
  * of those above. If you wish to allow use of your version of this file only
  * under the terms of either the GPL or the LGPL, and not to allow others to
  * use your version of this file under the terms of the MPL, indicate your
@@ -309,18 +310,17 @@ NS_INTERFACE_TABLE_HEAD(nsHTMLBodyElemen
   NS_HTML_CONTENT_INTERFACE_TABLE1(nsHTMLBodyElement, nsIDOMHTMLBodyElement)
   NS_HTML_CONTENT_INTERFACE_TABLE_TO_MAP_SEGUE(nsHTMLBodyElement,
                                                nsGenericHTMLElement)
 NS_HTML_CONTENT_INTERFACE_TABLE_TAIL_CLASSINFO(HTMLBodyElement)
 
 NS_IMPL_ELEMENT_CLONE(nsHTMLBodyElement)
 
 
-NS_IMPL_URI_ATTR(nsHTMLBodyElement, Background, background)
-
+NS_IMPL_STRING_ATTR(nsHTMLBodyElement, Background, background)
 NS_IMPL_STRING_ATTR(nsHTMLBodyElement, VLink, vlink)
 NS_IMPL_STRING_ATTR(nsHTMLBodyElement, ALink, alink)
 NS_IMPL_STRING_ATTR(nsHTMLBodyElement, Link, link)
 NS_IMPL_STRING_ATTR(nsHTMLBodyElement, Text, text)
 NS_IMPL_STRING_ATTR(nsHTMLBodyElement, BgColor, bgcolor)
 
 PRBool
 nsHTMLBodyElement::ParseAttribute(PRInt32 aNamespaceID,
--- a/content/html/content/src/nsHTMLInputElement.cpp
+++ b/content/html/content/src/nsHTMLInputElement.cpp
@@ -3047,29 +3047,23 @@ nsHTMLInputElement::SaveState()
   nsresult rv = NS_OK;
 
   nsRefPtr<nsHTMLInputElementState> inputState = nsnull;
 
   switch (mType) {
     case NS_FORM_INPUT_CHECKBOX:
     case NS_FORM_INPUT_RADIO:
       {
-        PRBool checked = GetChecked();
-        PRBool defaultChecked = PR_FALSE;
-        GetDefaultChecked(&defaultChecked);
-        // Only save if checked != defaultChecked (bug 62713)
-        // (always save if it's a radio button so that the checked
-        // state of all radio buttons is restored)
-        if (mType == NS_FORM_INPUT_RADIO || checked != defaultChecked) {
+        if (GetCheckedChanged()) {
           inputState = new nsHTMLInputElementState();
           if (!inputState) {
             return NS_ERROR_OUT_OF_MEMORY;
           }
 
-          inputState->SetChecked(checked);
+          inputState->SetChecked(GetChecked());
         }
         break;
       }
 
     // Never save passwords in session history
     case NS_FORM_INPUT_PASSWORD:
       break;
     case NS_FORM_INPUT_EMAIL:
--- a/content/html/content/test/Makefile.in
+++ b/content/html/content/test/Makefile.in
@@ -46,16 +46,19 @@ include $(DEPTH)/config/autoconf.mk
 ifdef ENABLE_TESTS
 # This extra subdirectory is needed due to the nature of this test.
 # With the bug, the test loads the base URL of the bug649134/file_*.sjs
 # files, and the mochitest server responds with the contents of index.html if
 # it exists in that case, which we use to detect failure.
 # We can't have index.html in this directory because it would prevent
 # running the tests here.
 DIRS		+= bug649134
+
+# For form-related test suite.
+DIRS		+= forms
 endif
 
 include $(topsrcdir)/config/rules.mk
 
 _TEST_FILES = \
 		test_hidden.html \
 		test_bug589.html \
 		test_bug691.html \
@@ -275,13 +278,14 @@ include $(topsrcdir)/config/rules.mk
 		test_bug643051.html \
 		test_bug583514.html \
 		test_bug514437.html \
 		test_bug560112.html \
 		test_bug649134.html \
 		test_bug658746.html \
 		test_bug659596.html \
 		test_bug659743.xml \
+		test_bug660663.html \
 		test_restore_from_parser_fragment.html \
 		$(NULL)
 
 libs:: $(_TEST_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/tests/$(relativesrcdir)
new file mode 100644
--- /dev/null
+++ b/content/html/content/test/forms/Makefile.in
@@ -0,0 +1,53 @@
+# ***** BEGIN LICENSE BLOCK *****
+# Version: MPL 1.1/GPL 2.0/LGPL 2.1
+#
+# The contents of this file are subject to the Mozilla Public License Version
+# 1.1 (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.mozilla.org/MPL/
+#
+# Software distributed under the License is distributed on an "AS IS" basis,
+# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+# for the specific language governing rights and limitations under the
+# License.
+#
+# The Original Code is Mozilla code.
+#
+# The Initial Developer of the Original Code is Mozilla Foundation.
+# Portions created by the Initial Developer are Copyright (C) 2011
+# the Initial Developer. All Rights Reserved.
+#
+# Contributor(s):
+#   Mounir Lamouri <mounir.lamouri@mozilla.com> (original author)
+#
+# Alternatively, the contents of this file may be used under the terms of
+# either of the GNU General Public License Version 2 or later (the "GPL"),
+# or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+# in which case the provisions of the GPL or the LGPL are applicable instead
+# of those above. If you wish to allow use of your version of this file only
+# under the terms of either the GPL or the LGPL, and not to allow others to
+# use your version of this file under the terms of the MPL, indicate your
+# decision by deleting the provisions above and replace them with the notice
+# and other provisions required by the GPL or the LGPL. If you do not delete
+# the provisions above, a recipient may use your version of this file under
+# the terms of any one of the MPL, the GPL or the LGPL.
+#
+# ***** END LICENSE BLOCK *****
+
+DEPTH          = ../../../../..
+topsrcdir      = @top_srcdir@
+srcdir         = @srcdir@
+VPATH          = @srcdir@
+relativesrcdir = content/html/content/test/forms
+
+include $(DEPTH)/config/autoconf.mk
+include $(topsrcdir)/config/rules.mk
+
+_TEST_FILES = \
+		save_restore_radio_groups.sjs \
+		test_save_restore_radio_groups.html \
+		$(NULL)
+
+libs:: $(_TEST_FILES)
+	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/tests/$(relativesrcdir)
+
new file mode 100644
--- /dev/null
+++ b/content/html/content/test/forms/save_restore_radio_groups.sjs
@@ -0,0 +1,44 @@
+var pages = [
+  "<!DOCTYPE html>" +
+  "<html><body>" +
+  "<form>" +
+  "<input name='a' type='radio' checked><input name='a' type='radio'><input name='a' type='radio'>" +
+  "</form>" +
+  "</body></html>",
+  "<!DOCTYPE html>" +
+  "<html><body>" +
+  "<form>" +
+  "<input name='a' type='radio'><input name='a' type='radio' checked><input name='a' type='radio'>" +
+  "</form>" +
+  "</body></html>",
+  ];
+
+/**
+ * This SJS is going to send the same page the two first times it will be called
+ * and another page the two following times. After that, the response will have
+ * no content.
+ * The use case is to have two iframes using this SJS and both being reloaded
+ * once.
+ */
+
+function handleRequest(request, response)
+{
+  var counter = +getState("counter"); // convert to number; +"" === 0
+
+  response.setStatusLine(request.httpVersion, 200, "Ok");
+  response.setHeader("Content-Type", "text/html");
+  response.setHeader("Cache-Control", "no-cache");
+
+  switch (counter) {
+    case 0:
+    case 1:
+      response.write(pages[0]);
+      break;
+    case 2:
+    case 3:
+      response.write(pages[1]);
+      break;
+  }
+  setState("counter", "" + ++counter);
+}
+
new file mode 100644
--- /dev/null
+++ b/content/html/content/test/forms/test_save_restore_radio_groups.html
@@ -0,0 +1,74 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=350022
+-->
+<head>
+  <title>Test for Bug 350022</title>
+  <script type="application/javascript" src="/MochiKit/packed.js"></script>
+  <script type="application/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=350022">Mozilla Bug 350022</a>
+<p id="display"></p>
+<div id="content"><!-- style="display: none">-->
+  <iframe src="save_restore_radio_groups.sjs"></iframe>
+  <iframe src="save_restore_radio_groups.sjs"></iframe>
+</div>
+<pre id="test">
+<script type="application/javascript">
+
+/** Test for Bug 350022 **/
+
+function checkRadioGroup(aFrame, aResults)
+{
+  var radios = frames[aFrame].document.getElementsByTagName('input');
+
+  is(radios.length, aResults.length,
+     "Radio group should have " + aResults.length + "elements");
+
+  for (var i=0; i<aResults.length; ++i) {
+    is(radios[i].checked, aResults[i],
+       "Radio checked state should be " + aResults[i]);
+  }
+}
+
+SimpleTest.waitForExplicitFinish();
+addLoadEvent(function() {
+  /**
+   * We have two iframes each containing one radio button group.
+   * We are going to change the selected radio button in one group.
+   * Then, both iframes will be reloaded and the new groups will have another
+   * radio checked by default.
+   * For the first group (which had a selection change), nothing should change.
+   * For the second, the selected radio button should change.
+   */
+  checkRadioGroup(0, [true, false, false]);
+  checkRadioGroup(1, [true, false, false]);
+
+  frames[0].document.getElementsByTagName('input')[2].checked = true;
+  checkRadioGroup(0, [false, false, true]);
+
+  framesElts = document.getElementsByTagName('iframe');
+  framesElts[0].addEventListener("load", function() {
+    framesElts[0].removeEventListener("load", arguments.callee, false);
+    checkRadioGroup(0, [false, false, true]);
+
+    framesElts[1].addEventListener("load", function() {
+      framesElts[1].removeEventListener("load", arguments.callee, false);
+
+      checkRadioGroup(1, [false, true, false]);
+      SimpleTest.finish();
+    }, false);
+
+    frames[1].location.reload();
+  }, false);
+
+  frames[0].location.reload();
+});
+
+</script>
+</pre>
+</body>
+</html>
--- a/content/html/content/test/reflect.js
+++ b/content/html/content/test/reflect.js
@@ -88,8 +88,52 @@ function reflectUnsignedInt(aElement, aA
   is(aElement.getAttribute(aAttr), 0, "@" + aAttr + " should be equals to 0");
   if (aNonNull) {
     is(aElement[aAttr], aDefault,
        "." + aAttr + " should be equals to " + aDefault);
   } else {
     is(aElement[aAttr], 0, "." + aAttr + " should be equals to 0");
   }
 }
+
+/**
+ * @param aElement            Element     node to test on
+ * @param aAttr               String      name of the attribute
+ * @param aSupportedValues    Array       values we supported
+ * @param aUnsupportedValues  Array       values we don't support
+ */
+function reflectLimitedEnumerated(aElement, aAttr, aSupportedValues,
+                                  aUnsupportedValues)
+{
+  aSupportedValues.forEach(function (v) {
+    aElement.setAttribute(aAttr, v);
+    is(aElement[aAttr], v);
+    is(aElement.getAttribute(aAttr), v);
+    aElement.removeAttribute(aAttr);
+
+    aElement.setAttribute(aAttr, v.toUpperCase());
+    is(aElement[aAttr], v);
+    is(aElement.getAttribute(aAttr), v.toUpperCase());
+    aElement.removeAttribute(aAttr);
+
+    aElement[aAttr] = v;
+    is(aElement[aAttr], v);
+    is(aElement.getAttribute(aAttr), v);
+    aElement.removeAttribute(aAttr);
+
+    aElement[aAttr] = v.toUpperCase();
+    is(aElement[aAttr], v);
+    is(aElement.getAttribute(aAttr), v.toUpperCase());
+    aElement.removeAttribute(aAttr);
+  });
+  ["cheesecake"].concat(aUnsupportedValues).forEach(function (v) {
+    aElement.setAttribute(aAttr, v);
+    is(aElement[aAttr], "");
+    is(aElement.getAttribute(aAttr), v);
+    aElement.removeAttribute(aAttr);
+
+    aElement[aAttr] = v;
+    is(aElement[aAttr], "");
+    is(aElement.getAttribute(aAttr), v);
+    aElement.removeAttribute(aAttr);
+  });
+}
+
new file mode 100644
--- /dev/null
+++ b/content/html/content/test/test_bug660663.html
@@ -0,0 +1,29 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=660663
+-->
+<head>
+  <title>Test for Bug 660663</title>
+  <script type="application/javascript" src="/MochiKit/packed.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script src="reflect.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=660663">Mozilla Bug 660663</a>
+<p id="display"></p>
+<div id="content" style="display: none">
+  
+</div>
+<pre id="test">
+<script type="application/javascript">
+/** Test for Bug 660663 **/
+reflectLimitedEnumerated(document.createElement("div"),
+                         "dir",
+                         ["ltr", "rtl"],
+                         ["auto"]);
+</script>
+</pre>
+</body>
+</html>
--- a/content/html/document/src/nsHTMLDocument.cpp
+++ b/content/html/document/src/nsHTMLDocument.cpp
@@ -916,17 +916,17 @@ nsHTMLDocument::StartDocumentLoad(const 
   if (muCV && !muCVIsParent)
     muCV->SetPrevDocCharacterSet(charset);
 
   if (cachingChan) {
     NS_ASSERTION(charset == parserCharset,
                  "How did those end up different here?  wyciwyg channels are "
                  "not nsICachingChannel");
     rv = cachingChan->SetCacheTokenCachedCharset(charset);
-    NS_ASSERTION(NS_SUCCEEDED(rv),"cannot SetMetaDataElement");
+    NS_WARN_IF_FALSE(NS_SUCCEEDED(rv), "cannot SetMetaDataElement");
   }
 
   // Set the parser as the stream listener for the document loader...
   if (mParser) {
     rv = mParser->GetStreamListener(aDocListener);
     if (NS_FAILED(rv)) {
       return rv;
     }
@@ -986,17 +986,17 @@ nsHTMLDocument::StopDocumentLoad()
     if (mWriteState == eDocumentOpened) {
       NS_ASSERTION(IsHTML(), "document.open()ed doc is not HTML?");
 
       // Marking the document as closed, since pending scripts will be
       // stopped by nsDocument::StopDocumentLoad() below
       mWriteState = eDocumentClosed;
 
       // Remove the wyciwyg channel request from the document load group
-      // that we added in OpenCommon().
+      // that we added in Open().
       NS_ASSERTION(mWyciwygChannel, "nsHTMLDocument::StopDocumentLoad(): "
                    "Trying to remove nonexistent wyciwyg channel!");
       RemoveWyciwygChannel();
       NS_ASSERTION(!mWyciwygChannel, "nsHTMLDocument::StopDocumentLoad(): "
                    "nsIWyciwygChannel could not be removed!");
     }
     nsDocument::StopDocumentLoad();
     UnblockOnload(PR_FALSE);
@@ -1511,45 +1511,62 @@ nsHTMLDocument::SetCookie(const nsAStrin
 
     NS_LossyConvertUTF16toASCII cookie(aCookie);
     service->SetCookieString(codebaseURI, prompt, cookie.get(), mChannel);
   }
 
   return NS_OK;
 }
 
-nsresult
-nsHTMLDocument::OpenCommon(JSContext* cx, const nsAString& aContentType,
-                           PRBool aReplace)
+NS_IMETHODIMP
+nsHTMLDocument::Open(const nsAString& aContentTypeOrUrl,
+                     const nsAString& aReplaceOrName,
+                     const nsAString& aFeatures,
+                     JSContext* cx, PRUint8 aOptionalArgCount,
+                     nsISupports** aReturn)
 {
+  NS_ASSERTION(nsContentUtils::CanCallerAccess(static_cast<nsIDOMHTMLDocument*>(this)),
+               "XOW should have caught this!");
+
+  // When called with 3 or more arguments, document.open() calls window.open().
+  if (aOptionalArgCount > 2) {
+    nsCOMPtr<nsIDOMWindowInternal> window = GetWindowInternal();
+    if (!window) {
+      return NS_OK;
+    }
+    nsCOMPtr<nsIDOMWindow> newWindow;
+    nsresult rv = window->Open(aContentTypeOrUrl, aReplaceOrName, aFeatures,
+                               getter_AddRefs(newWindow));
+    *aReturn = newWindow.forget().get();
+    return rv;
+  }
+
   if (!IsHTML() || mDisableDocWrite) {
     // No calling document.open() on XHTML
-
     return NS_ERROR_DOM_INVALID_STATE_ERR;
   }
 
-  PRBool loadAsHtml5 = nsHtml5Module::sEnabled;
-
-  nsresult rv = NS_OK;
+  nsCAutoString contentType;
+  contentType.AssignLiteral("text/html");
+  if (aOptionalArgCount > 0) {
+    nsAutoString type;
+    ToLowerCase(aContentTypeOrUrl, type);
+    nsCAutoString actualType, dummy;
+    NS_ParseContentType(NS_ConvertUTF16toUTF8(type), actualType, dummy);
+    if (!actualType.EqualsLiteral("text/html") &&
+        !type.EqualsLiteral("replace")) {
+      contentType.AssignLiteral("text/plain");
+    }
+  }
 
   // If we already have a parser we ignore the document.open call.
   if (mParser) {
-
     return NS_OK;
   }
 
-  NS_ASSERTION(nsContentUtils::CanCallerAccess(static_cast<nsIDOMHTMLDocument*>(this)),
-               "XOW should have caught this!");
-
-  if (!aContentType.EqualsLiteral("text/html") &&
-      !aContentType.EqualsLiteral("text/plain")) {
-    NS_WARNING("Unsupported type; fix the caller");
-    return NS_ERROR_DOM_NOT_SUPPORTED_ERR;
-  }
-
   // check whether we're in the middle of unload.  If so, ignore this call.
   nsCOMPtr<nsIDocShell> shell = do_QueryReferent(mDocumentContainer);
   if (!shell) {
     // We won't be able to create a parser anyway.
     return NS_OK;
   }
 
   PRBool inUnload;
@@ -1597,32 +1614,30 @@ nsHTMLDocument::OpenCommon(JSContext* cx
     nsCAutoString callerSpec;
     nsCAutoString thisSpec;
     if (callerDocURI) {
       callerDocURI->GetSpec(callerSpec);
     }
     if (thisURI) {
       thisURI->GetSpec(thisSpec);
     }
-    printf("nsHTMLDocument::OpenCommon callerDoc %s this %s\n", callerSpec.get(), thisSpec.get());
+    printf("nsHTMLDocument::Open callerDoc %s this %s\n", callerSpec.get(), thisSpec.get());
 #endif
 
     return NS_ERROR_DOM_SECURITY_ERR;
   }
 
   // Stop current loads targeted at the window this document is in.
   if (mScriptGlobalObject) {
     nsCOMPtr<nsIContentViewer> cv;
     shell->GetContentViewer(getter_AddRefs(cv));
 
     if (cv) {
       PRBool okToUnload;
-      rv = cv->PermitUnload(PR_FALSE, &okToUnload);
-
-      if (NS_SUCCEEDED(rv) && !okToUnload) {
+      if (NS_SUCCEEDED(cv->PermitUnload(PR_FALSE, &okToUnload)) && !okToUnload) {
         // We don't want to unload, so stop here, but don't throw an
         // exception.
         return NS_OK;
       }
     }
 
     nsCOMPtr<nsIWebNavigation> webnav(do_QueryInterface(shell));
     webnav->Stop(nsIWebNavigation::STOP_NETWORK);
@@ -1634,17 +1649,17 @@ nsHTMLDocument::OpenCommon(JSContext* cx
     EnsureOnloadBlocker();
   }
 
   // The open occurred after the document finished loading.
   // So we reset the document and create a new one.
   nsCOMPtr<nsIChannel> channel;
   nsCOMPtr<nsILoadGroup> group = do_QueryReferent(mDocumentLoadGroup);
 
-  rv = NS_NewChannel(getter_AddRefs(channel), uri, nsnull, group);
+  nsresult rv = NS_NewChannel(getter_AddRefs(channel), uri, nsnull, group);
 
   if (NS_FAILED(rv)) {
     return rv;
   }
 
   // We can't depend on channels implementing property bags, so do our
   // base URI manually after reset.
 
@@ -1695,25 +1710,26 @@ nsHTMLDocument::OpenCommon(JSContext* cx
   if (baseURI) {
     mDocumentBaseURI = baseURI;
   }
 
   // Store the security info of the caller now that we're done
   // resetting the document.
   mSecurityInfo = securityInfo;
 
+  PRBool loadAsHtml5 = nsHtml5Module::sEnabled;
   if (loadAsHtml5) {
     mParser = nsHtml5Module::NewHtml5Parser();
     rv = NS_OK;
   } else {
     mParser = do_CreateInstance(kCParserCID, &rv);  
   }
 
   // This will be propagated to the parser when someone actually calls write()
-  SetContentTypeInternal(NS_ConvertUTF16toUTF8(aContentType));
+  SetContentTypeInternal(contentType);
 
   mWriteState = eDocumentOpened;
 
   if (NS_SUCCEEDED(rv)) {
     if (loadAsHtml5) {
       nsHtml5Module::Initialize(mParser, this, uri, shell, channel);
     } else {
       nsCOMPtr<nsIHTMLContentSink> sink;
@@ -1734,79 +1750,42 @@ nsHTMLDocument::OpenCommon(JSContext* cx
   // Prepare the docshell and the document viewer for the impending
   // out of band document.write()
   shell->PrepareForNewContentModel();
 
   // Now check whether we were opened with a "replace" argument.  If
   // so, we need to tell the docshell to not create a new history
   // entry for this load. Otherwise, make sure that we're doing a normal load,
   // not whatever type of load was previously done on this docshell.
-  shell->SetLoadType(aReplace ? LOAD_NORMAL_REPLACE : LOAD_NORMAL);
+  shell->SetLoadType(
+    (aOptionalArgCount > 1 && aReplaceOrName.EqualsLiteral("replace"))
+    ? LOAD_NORMAL_REPLACE : LOAD_NORMAL);
 
   nsCOMPtr<nsIContentViewer> cv;
   shell->GetContentViewer(getter_AddRefs(cv));
   nsCOMPtr<nsIDocumentViewer> docViewer = do_QueryInterface(cv);
   if (docViewer) {
     docViewer->LoadStart(static_cast<nsIHTMLDocument *>(this));
   }
 
   // Add a wyciwyg channel request into the document load group
-  NS_ASSERTION(!mWyciwygChannel, "nsHTMLDocument::OpenCommon(): wyciwyg "
+  NS_ASSERTION(!mWyciwygChannel, "nsHTMLDocument::Open(): wyciwyg "
                "channel already exists!");
 
   // In case the editor is listening and will see the new channel
   // being added, make sure mWriteLevel is non-zero so that the editor
   // knows that document.open/write/close() is being called on this
   // document.
   ++mWriteLevel;
 
   CreateAndAddWyciwygChannel();
 
   --mWriteLevel;
 
-  return rv;
-}
-
-NS_IMETHODIMP
-nsHTMLDocument::Open(const nsAString& aContentTypeOrUrl,
-                     const nsAString& aReplaceOrName,
-                     const nsAString& aFeatures,
-                     JSContext* cx, PRUint8 aOptionalArgCount,
-                     nsISupports** aReturn)
-{
-  // When called with 3 or more arguments, document.open() calls window.open().
-  if (aOptionalArgCount > 2) {
-    nsCOMPtr<nsIDOMWindowInternal> window = GetWindowInternal();
-    if (!window) {
-      return NS_OK;
-    }
-    nsCOMPtr<nsIDOMWindow> newWindow;
-    nsresult rv = window->Open(aContentTypeOrUrl, aReplaceOrName, aFeatures,
-                               getter_AddRefs(newWindow));
-    *aReturn = newWindow.forget().get();
-    return rv;
-  }
-
-  nsAutoString contentType;
-  contentType.AssignLiteral("text/html");
-  if (aOptionalArgCount > 0) {
-    nsAutoString type;
-    ToLowerCase(aContentTypeOrUrl, type);
-    nsCAutoString actualType, dummy;
-    NS_ParseContentType(NS_ConvertUTF16toUTF8(type), actualType, dummy);
-    if (!actualType.EqualsLiteral("text/html") &&
-        !type.EqualsLiteral("replace")) {
-      contentType.AssignLiteral("text/plain");
-    }
-  }
-
-  nsresult rv = OpenCommon(cx, contentType,
-    aOptionalArgCount > 1 && aReplaceOrName.EqualsLiteral("replace"));
   NS_ENSURE_SUCCESS(rv, rv);
-
   return CallQueryInterface(this, aReturn);
 }
 
 NS_IMETHODIMP
 nsHTMLDocument::Clear()
 {
   // This method has been deprecated
   return NS_OK;
@@ -2362,22 +2341,16 @@ nsHTMLDocument::ResolveName(const nsAStr
     }
   }
 
   return NS_OK;
 }
 
 //----------------------------
 
-/* virtual */ nsIContent*
-nsHTMLDocument::GetBodyContentExternal()
-{
-  return GetBodyElement();
-}
-
 // forms related stuff
 
 NS_IMETHODIMP
 nsHTMLDocument::GetForms(nsIDOMHTMLCollection** aForms)
 {
   nsContentList *forms = nsHTMLDocument::GetForms();
   if (!forms)
     return NS_ERROR_OUT_OF_MEMORY;
--- a/content/html/document/src/nsHTMLDocument.h
+++ b/content/html/document/src/nsHTMLDocument.h
@@ -169,18 +169,16 @@ public:
     return mEditingState;
   }
 
   virtual void DisableCookieAccess()
   {
     mDisableCookieAccess = PR_TRUE;
   }
 
-  virtual nsIContent* GetBodyContentExternal();
-
   class nsAutoEditingState {
   public:
     nsAutoEditingState(nsHTMLDocument* aDoc, EditingState aState)
       : mDoc(aDoc), mSavedState(aDoc->mEditingState)
     {
       aDoc->mEditingState = aState;
     }
     ~nsAutoEditingState() {
@@ -230,18 +228,16 @@ protected:
   static void* UseExistingNameString(nsINode* aRootNode, const nsString* aName);
 
   static void DocumentWriteTerminationFunc(nsISupports *aRef);
 
   void GetDomainURI(nsIURI **uri);
 
   nsresult WriteCommon(JSContext *cx, const nsAString& aText,
                        PRBool aNewlineTerminate);
-  nsresult OpenCommon(JSContext *cx, const nsAString& aContentType,
-                      PRBool aReplace);
 
   nsresult CreateAndAddWyciwygChannel(void);
   nsresult RemoveWyciwygChannel(void);
 
   /**
    * Like IsEditingOn(), but will flush as needed first.
    */
   PRBool IsEditingOnAfterFlush();
--- a/content/html/document/src/nsIHTMLDocument.h
+++ b/content/html/document/src/nsIHTMLDocument.h
@@ -44,18 +44,18 @@
 class nsIDOMHTMLFormElement;
 class nsIContent;
 class nsIScriptElement;
 class nsIEditor;
 class nsContentList;
 class nsWrapperCache;
 
 #define NS_IHTMLDOCUMENT_IID \
-{ 0x30001b0c, 0xdb25, 0x4318, \
-  { 0x85, 0xb8, 0x48, 0xb4, 0xea, 0x54, 0x8f, 0x23 } }
+{ 0x51a360fa, 0xd659, 0x4d85, \
+  { 0xa5, 0xc5, 0x4a, 0xbb, 0x0d, 0x97, 0x0f, 0x7a } }
 
 
 /**
  * HTML document extensions to nsIDocument.
  */
 class nsIHTMLDocument : public nsISupports
 {
 public:
@@ -160,22 +160,16 @@ public:
   virtual nsresult SetEditingState(EditingState aState) = 0;
 
   /**
    * Disables getting and setting cookies
    */
   virtual void DisableCookieAccess() = 0;
 
   /**
-   * Get the first <body> child of the root <html>, but don't do
-   * anything <frameset>-related (like nsIDOMHTMLDocument::GetBody).
-   */
-  virtual nsIContent* GetBodyContentExternal() = 0;
-
-  /**
    * Called when this nsIHTMLDocument's editor is destroyed.
    */
   virtual void TearingDownEditor(nsIEditor *aEditor) = 0;
 
   virtual void SetIsXHTML(PRBool aXHTML) = 0;
 
   virtual void SetDocWriteDisabled(PRBool aDisabled) = 0;
 };
--- a/content/media/nsBuiltinDecoderReader.cpp
+++ b/content/media/nsBuiltinDecoderReader.cpp
@@ -249,17 +249,17 @@ VideoData* nsBuiltinDecoderReader::FindS
   if (HasAudio()) {
     SoundData* soundData = DecodeToFirstData(&nsBuiltinDecoderReader::DecodeAudioData,
                                              mAudioQueue);
     if (soundData) {
       audioStartTime = soundData->mTime;
     }
   }
 
-  PRInt64 startTime = PR_MIN(videoStartTime, audioStartTime);
+  PRInt64 startTime = NS_MIN(videoStartTime, audioStartTime);
   if (startTime != PR_INT64_MAX) {
     aOutStartTime = startTime;
   }
 
   return videoData;
 }
 
 template<class Data>
--- a/content/media/nsMediaCache.cpp
+++ b/content/media/nsMediaCache.cpp
@@ -813,24 +813,24 @@ nsMediaCache::AppendMostReusableBlock(Bl
 PRInt32
 nsMediaCache::FindReusableBlock(TimeStamp aNow,
                                 nsMediaCacheStream* aForStream,
                                 PRInt32 aForStreamBlock,
                                 PRInt32 aMaxSearchBlockIndex)
 {
   mReentrantMonitor.AssertCurrentThreadIn();
 
-  PRUint32 length = PR_MIN(PRUint32(aMaxSearchBlockIndex), mIndex.Length());
+  PRUint32 length = NS_MIN(PRUint32(aMaxSearchBlockIndex), mIndex.Length());
 
   if (aForStream && aForStreamBlock > 0 &&
       PRUint32(aForStreamBlock) <= aForStream->mBlocks.Length()) {
     PRInt32 prevCacheBlock = aForStream->mBlocks[aForStreamBlock - 1];
     if (prevCacheBlock >= 0) {
       PRUint32 freeBlockScanEnd =
-        PR_MIN(length, prevCacheBlock + FREE_BLOCK_SCAN_LIMIT);
+        NS_MIN(length, prevCacheBlock + FREE_BLOCK_SCAN_LIMIT);
       for (PRUint32 i = prevCacheBlock; i < freeBlockScanEnd; ++i) {
         if (IsBlockFree(i))
           return i;
       }
     }
   }
 
   if (!mFreeBlocks.IsEmpty()) {
@@ -1041,17 +1041,17 @@ nsMediaCache::PredictNextUse(TimeStamp a
     case READAHEAD_BLOCK: {
       PRInt64 bytesAhead =
         static_cast<PRInt64>(bo->mStreamBlock)*BLOCK_SIZE - bo->mStream->mStreamOffset;
       NS_ASSERTION(bytesAhead >= 0,
                    "Readahead block before the current stream position?");
       PRInt64 millisecondsAhead =
         bytesAhead*1000/bo->mStream->mPlaybackBytesPerSecond;
       prediction = TimeDuration::FromMilliseconds(
-          PR_MIN(millisecondsAhead, PR_INT32_MAX));
+          NS_MIN<PRInt64>(millisecondsAhead, PR_INT32_MAX));
       break;
     }
     default:
       NS_ERROR("Invalid class for predicting next use");
       return TimeDuration(0);
     }
     if (i == 0 || prediction < result) {
       result = prediction;
@@ -1069,17 +1069,17 @@ nsMediaCache::PredictNextUseForIncomingD
   if (bytesAhead <= -BLOCK_SIZE) {
     // Hmm, no idea when data behind us will be used. Guess 24 hours.
     return TimeDuration::FromSeconds(24*60*60);
   }
   if (bytesAhead <= 0)
     return TimeDuration(0);
   PRInt64 millisecondsAhead = bytesAhead*1000/aStream->mPlaybackBytesPerSecond;
   return TimeDuration::FromMilliseconds(
-      PR_MIN(millisecondsAhead, PR_INT32_MAX));
+      NS_MIN<PRInt64>(millisecondsAhead, PR_INT32_MAX));
 }
 
 enum StreamAction { NONE, SEEK, RESUME, SUSPEND };
 
 void
 nsMediaCache::Update()
 {
   NS_ASSERTION(NS_IsMainThread(), "Only call on main thread");
@@ -1119,17 +1119,17 @@ nsMediaCache::Update()
     for (PRInt32 blockIndex = mIndex.Length() - 1; blockIndex >= maxBlocks;
          --blockIndex) {
       if (IsBlockFree(blockIndex)) {
         // Don't count overflowing free blocks in our free block count
         --freeBlockCount;
         continue;
       }
       TimeDuration predictedUse = PredictNextUse(now, blockIndex);
-      latestPredictedUseForOverflow = PR_MAX(latestPredictedUseForOverflow, predictedUse);
+      latestPredictedUseForOverflow = NS_MAX(latestPredictedUseForOverflow, predictedUse);
     }
 
     // Now try to move overflowing blocks to the main part of the cache.
     for (PRInt32 blockIndex = mIndex.Length() - 1; blockIndex >= maxBlocks;
          --blockIndex) {
       if (IsBlockFree(blockIndex))
         continue;
 
@@ -1644,17 +1644,17 @@ nsMediaCache::NoteSeek(nsMediaCacheStrea
   mReentrantMonitor.AssertCurrentThreadIn();
 
   if (aOldOffset < aStream->mStreamOffset) {
     // We seeked forward. Convert blocks from readahead to played.
     // Any readahead block that intersects the seeked-over range must
     // be converted.
     PRInt32 blockIndex = aOldOffset/BLOCK_SIZE;
     PRInt32 endIndex =
-      PR_MIN((aStream->mStreamOffset + BLOCK_SIZE - 1)/BLOCK_SIZE,
+      NS_MIN<PRInt64>((aStream->mStreamOffset + BLOCK_SIZE - 1)/BLOCK_SIZE,
              aStream->mBlocks.Length());
     TimeStamp now = TimeStamp::Now();
     while (blockIndex < endIndex) {
       PRInt32 cacheBlockIndex = aStream->mBlocks[blockIndex];
       if (cacheBlockIndex >= 0) {
         // Marking the block used may not be exactly what we want but
         // it's simple
         NoteBlockUsage(aStream, cacheBlockIndex, nsMediaCacheStream::MODE_PLAYBACK,
@@ -1664,17 +1664,17 @@ nsMediaCache::NoteSeek(nsMediaCacheStrea
     }
   } else {
     // We seeked backward. Convert from played to readahead.
     // Any played block that is entirely after the start of the seeked-over
     // range must be converted.
     PRInt32 blockIndex =
       (aStream->mStreamOffset + BLOCK_SIZE - 1)/BLOCK_SIZE;
     PRInt32 endIndex =
-      PR_MIN((aOldOffset + BLOCK_SIZE - 1)/BLOCK_SIZE,
+      NS_MIN<PRInt64>((aOldOffset + BLOCK_SIZE - 1)/BLOCK_SIZE,
              aStream->mBlocks.Length());
     while (blockIndex < endIndex) {
       PRInt32 cacheBlockIndex = aStream->mBlocks[endIndex - 1];
       if (cacheBlockIndex >= 0) {
         BlockOwner* bo = GetBlockOwner(cacheBlockIndex, aStream);
         NS_ASSERTION(bo, "Stream doesn't own its blocks?");
         if (bo->mClass == PLAYED_BLOCK) {
           aStream->mPlayedBlocks.RemoveBlock(cacheBlockIndex);
@@ -1708,17 +1708,17 @@ nsMediaCacheStream::NotifyDataStarted(PR
 
   ReentrantMonitorAutoEnter mon(gMediaCache->GetReentrantMonitor());
   NS_WARN_IF_FALSE(aOffset == mChannelOffset,
                    "Server is giving us unexpected offset");
   mChannelOffset = aOffset;
   if (mStreamLength >= 0) {
     // If we started reading at a certain offset, then for sure
     // the stream is at least that long.
-    mStreamLength = PR_MAX(mStreamLength, mChannelOffset);
+    mStreamLength = NS_MAX(mStreamLength, mChannelOffset);
   }
 }
 
 void
 nsMediaCacheStream::UpdatePrincipal(nsIPrincipal* aPrincipal)
 {
   if (!mPrincipal) {
     NS_ASSERTION(!mUsingNullPrincipal, "Are we using a null principal or not?");
@@ -1763,17 +1763,17 @@ nsMediaCacheStream::NotifyDataReceived(P
 
   LOG(PR_LOG_DEBUG, ("Stream %p DataReceived at %lld count=%lld",
       this, (long long)mChannelOffset, (long long)aSize));
 
   // We process the data one block (or part of a block) at a time
   while (size > 0) {
     PRUint32 blockIndex = mChannelOffset/BLOCK_SIZE;
     PRInt32 blockOffset = PRInt32(mChannelOffset - blockIndex*BLOCK_SIZE);
-    PRInt32 chunkSize = PRInt32(PR_MIN(BLOCK_SIZE - blockOffset, size));
+    PRInt32 chunkSize = NS_MIN<PRInt64>(BLOCK_SIZE - blockOffset, size);
 
     // This gets set to something non-null if we have a whole block
     // of data to write to the cache
     const char* blockDataToStore = nsnull;
     ReadMode mode = MODE_PLAYBACK;
     if (blockOffset == 0 && chunkSize == BLOCK_SIZE) {
       // We received a whole block, so avoid a useless copy through
       // mPartialBlockBuffer
@@ -1804,17 +1804,17 @@ nsMediaCacheStream::NotifyDataReceived(P
     size -= chunkSize;
     data += chunkSize;
   }
 
   nsMediaCache::ResourceStreamIterator iter(mResourceID);
   while (nsMediaCacheStream* stream = iter.Next()) {
     if (stream->mStreamLength >= 0) {
       // The stream is at least as long as what we've read
-      stream->mStreamLength = PR_MAX(stream->mStreamLength, mChannelOffset);
+      stream->mStreamLength = NS_MAX(stream->mStreamLength, mChannelOffset);
     }
     stream->UpdatePrincipal(aPrincipal);
     stream->mClient->CacheClientNotifyDataReceived();
   }
 
   // Notify in case there's a waiting reader
   // XXX it would be fairly easy to optimize things a lot more to
   // avoid waking up reader threads unnecessarily
@@ -1970,19 +1970,19 @@ nsMediaCacheStream::GetCachedDataEndInte
   if (blockIndex == mChannelOffset/BLOCK_SIZE) {
     // The block containing mChannelOffset may be partially read but not
     // yet committed to the main cache
     result = mChannelOffset;
   }
   if (mStreamLength >= 0) {
     // The last block in the cache may only be partially valid, so limit
     // the cached range to the stream length
-    result = PR_MIN(result, mStreamLength);
+    result = NS_MIN(result, mStreamLength);
   }
-  return PR_MAX(result, aOffset);
+  return NS_MAX(result, aOffset);
 }
 
 PRInt64
 nsMediaCacheStream::GetNextCachedDataInternal(PRInt64 aOffset)
 {
   gMediaCache->GetReentrantMonitor().AssertCurrentThreadIn();
   if (aOffset == mStreamLength)
     return -1;
@@ -2101,36 +2101,36 @@ nsMediaCacheStream::Read(char* aBuffer, 
     return NS_ERROR_FAILURE;
 
   PRUint32 count = 0;
   // Read one block (or part of a block) at a time
   while (count < aCount) {
     PRUint32 streamBlock = PRUint32(mStreamOffset/BLOCK_SIZE);
     PRUint32 offsetInStreamBlock =
       PRUint32(mStreamOffset - streamBlock*BLOCK_SIZE);
-    PRInt32 size = PR_MIN(aCount - count, BLOCK_SIZE - offsetInStreamBlock);
+    PRInt32 size = NS_MIN(aCount - count, BLOCK_SIZE - offsetInStreamBlock);
 
     if (mStreamLength >= 0) {
       // Don't try to read beyond the end of the stream
       PRInt64 bytesRemaining = mStreamLength - mStreamOffset;
       if (bytesRemaining <= 0) {
         // Get out of here and return NS_OK
         break;
       }
-      size = PR_MIN(size, PRInt32(bytesRemaining));
+      size = NS_MIN(size, PRInt32(bytesRemaining));
     }
 
     PRInt32 bytes;
     PRUint32 channelBlock = PRUint32(mChannelOffset/BLOCK_SIZE);
     PRInt32 cacheBlock = streamBlock < mBlocks.Length() ? mBlocks[streamBlock] : -1;
     if (channelBlock == streamBlock && mStreamOffset < mChannelOffset) {
       // We can just use the data in mPartialBlockBuffer. In fact we should
       // use it rather than waiting for the block to fill and land in
       // the cache.
-      bytes = PR_MIN(size, mChannelOffset - mStreamOffset);
+      bytes = NS_MIN<PRInt64>(size, mChannelOffset - mStreamOffset);
       memcpy(aBuffer + count,
         reinterpret_cast<char*>(mPartialBlockBuffer) + offsetInStreamBlock, bytes);
       if (mCurrentMode == MODE_METADATA) {
         mMetadataInPartialBlockBuffer = PR_TRUE;
       }
       gMediaCache->NoteBlockUsage(this, cacheBlock, mCurrentMode, TimeStamp::Now());
     } else {
       if (cacheBlock < 0) {
@@ -2187,35 +2187,35 @@ nsMediaCacheStream::ReadFromCache(char* 
 
   // Read one block (or part of a block) at a time
   PRUint32 count = 0;
   PRInt64 streamOffset = aOffset;
   while (count < aCount) {
     PRUint32 streamBlock = PRUint32(streamOffset/BLOCK_SIZE);
     PRUint32 offsetInStreamBlock =
       PRUint32(streamOffset - streamBlock*BLOCK_SIZE);
-    PRInt32 size = PR_MIN(aCount - count, BLOCK_SIZE - offsetInStreamBlock);
+    PRInt32 size = NS_MIN<PRInt64>(aCount - count, BLOCK_SIZE - offsetInStreamBlock);
 
     if (mStreamLength >= 0) {
       // Don't try to read beyond the end of the stream
       PRInt64 bytesRemaining = mStreamLength - streamOffset;
       if (bytesRemaining <= 0) {
         return NS_ERROR_FAILURE;
       }
-      size = PR_MIN(size, PRInt32(bytesRemaining));
+      size = NS_MIN(size, PRInt32(bytesRemaining));
     }
 
     PRInt32 bytes;
     PRUint32 channelBlock = PRUint32(mChannelOffset/BLOCK_SIZE);
     PRInt32 cacheBlock = streamBlock < mBlocks.Length() ? mBlocks[streamBlock] : -1;
     if (channelBlock == streamBlock && streamOffset < mChannelOffset) {
       // We can just use the data in mPartialBlockBuffer. In fact we should
       // use it rather than waiting for the block to fill and land in
       // the cache.
-      bytes = PR_MIN(size, mChannelOffset - streamOffset);
+      bytes = NS_MIN<PRInt64>(size, mChannelOffset - streamOffset);
       memcpy(aBuffer + count,
         reinterpret_cast<char*>(mPartialBlockBuffer) + offsetInStreamBlock, bytes);
     } else {
       if (cacheBlock < 0) {
         // We expect all blocks to be cached! Fail!
         return NS_ERROR_FAILURE;
       }
       PRInt64 offset = cacheBlock*BLOCK_SIZE + offsetInStreamBlock;
--- a/content/media/nsMediaStream.cpp
+++ b/content/media/nsMediaStream.cpp
@@ -933,17 +933,17 @@ public:
     *aIsReliable = PR_TRUE;
     return 100*1024*1024; // arbitray, use 100MB/s
   }
   virtual PRInt64 GetLength() { return mSize; }
   virtual PRInt64 GetNextCachedData(PRInt64 aOffset)
   {
     return (aOffset < mSize) ? aOffset : -1;
   }
-  virtual PRInt64 GetCachedDataEnd(PRInt64 aOffset) { return PR_MAX(aOffset, mSize); }
+  virtual PRInt64 GetCachedDataEnd(PRInt64 aOffset) { return NS_MAX(aOffset, mSize); }
   virtual PRBool  IsDataCachedToEndOfStream(PRInt64 aOffset) { return PR_TRUE; }
   virtual PRBool  IsSuspendedByCache() { return PR_FALSE; }
   virtual PRBool  IsSuspended() { return PR_FALSE; }
 
   nsresult GetCachedRanges(nsTArray<nsByteRange>& aRanges);
 
 private:
   // The file size, or -1 if not known. Immutable after Open().
--- a/content/smil/nsSMILAnimationController.cpp
+++ b/content/smil/nsSMILAnimationController.cpp
@@ -574,34 +574,34 @@ nsSMILAnimationController::DoMilestoneSa
     // Due to negative offsets, early ends and the like, a timed element might
     // register a milestone that is actually in the past. That's fine, but it's
     // still only going to get *sampled* with whatever time we're up to and no
     // earlier.
     //
     // Because we're only performing this clamping at the last moment, the
     // animations will still all get sampled in the correct order and
     // dependencies will be appropriately resolved.
-    sampleTime = PR_MAX(nextMilestone.mTime, sampleTime);
+    sampleTime = NS_MAX(nextMilestone.mTime, sampleTime);
 
     for (PRUint32 i = 0; i < length; ++i) {
       nsISMILAnimationElement* elem = params.mElements[i].get();
       NS_ABORT_IF_FALSE(elem, "NULL animation element in list");
       nsSMILTimeContainer* container = elem->GetTimeContainer();
       if (!container)
         // The container may be nsnull if the element has been detached from its
         // parent since registering a milestone.
         continue;
 
       nsSMILTimeValue containerTimeValue =
         container->ParentToContainerTime(sampleTime);
       if (!containerTimeValue.IsResolved())
         continue;
 
       // Clamp the converted container time to non-negative values.
-      nsSMILTime containerTime = PR_MAX(0, containerTimeValue.GetMillis());
+      nsSMILTime containerTime = NS_MAX<nsSMILTime>(0, containerTimeValue.GetMillis());
 
       if (nextMilestone.mIsEnd) {
         elem->TimedElement().SampleEndAt(containerTime);
       } else {
         elem->TimedElement().SampleAt(containerTime);
       }
     }
   }
--- a/content/smil/nsSMILTimeContainer.cpp
+++ b/content/smil/nsSMILTimeContainer.cpp
@@ -144,17 +144,17 @@ nsSMILTimeContainer::GetCurrentTime() co
   return mCurrentTime;
 }
 
 void
 nsSMILTimeContainer::SetCurrentTime(nsSMILTime aSeekTo)
 {
   // SVG 1.1 doesn't specify what to do for negative times so we adopt SVGT1.2's
   // behaviour of clamping negative times to 0.
-  aSeekTo = PR_MAX(0, aSeekTo);
+  aSeekTo = NS_MAX<nsSMILTime>(0, aSeekTo);
 
   // The following behaviour is consistent with:
   // http://www.w3.org/2003/01/REC-SVG11-20030114-errata
   //  #getCurrentTime_setCurrentTime_undefined_before_document_timeline_begin
   // which says that if SetCurrentTime is called before the document timeline
   // has begun we should still adjust the offset.
   nsSMILTime parentTime = GetParentTime();
   mParentOffset = parentTime - aSeekTo;
--- a/content/svg/content/src/nsSVGFeatures.cpp
+++ b/content/svg/content/src/nsSVGFeatures.cpp
@@ -101,19 +101,17 @@ nsSVGFeatures::HaveFeatures(nsISupports*
   return PR_TRUE;
 }
 
 /*static*/ PRBool
 nsSVGFeatures::HaveExtension(const nsAString& aExtension)
 {
 #define SVG_SUPPORTED_EXTENSION(str) if (aExtension.EqualsLiteral(str)) return PR_TRUE;
   SVG_SUPPORTED_EXTENSION("http://www.w3.org/1999/xhtml")
-#ifdef MOZ_MATHML
   SVG_SUPPORTED_EXTENSION("http://www.w3.org/1998/Math/MathML")
-#endif
 #undef SVG_SUPPORTED_EXTENSION
 
   return PR_FALSE;
 }
 
 /*static*/ PRBool
 nsSVGFeatures::HaveExtensions(const nsSubstring& aExtensions)
 {
--- a/content/xml/document/src/nsXMLContentSink.cpp
+++ b/content/xml/document/src/nsXMLContentSink.cpp
@@ -1652,15 +1652,13 @@ nsXMLContentSink::UpdateChildCounts()
 
 PRBool
 nsXMLContentSink::IsMonolithicContainer(nsINodeInfo* aNodeInfo)
 {
   return ((aNodeInfo->NamespaceID() == kNameSpaceID_XHTML &&
           (aNodeInfo->NameAtom() == nsGkAtoms::tr ||
            aNodeInfo->NameAtom() == nsGkAtoms::select ||
            aNodeInfo->NameAtom() == nsGkAtoms::object ||
-           aNodeInfo->NameAtom() == nsGkAtoms::applet))
-#ifdef MOZ_MATHML
-       || (aNodeInfo->NamespaceID() == kNameSpaceID_MathML &&
+           aNodeInfo->NameAtom() == nsGkAtoms::applet)) ||
+          (aNodeInfo->NamespaceID() == kNameSpaceID_MathML &&
           (aNodeInfo->NameAtom() == nsGkAtoms::math))
-#endif
           );
 }
--- a/content/xslt/src/base/txDouble.cpp
+++ b/content/xslt/src/base/txDouble.cpp
@@ -256,17 +256,17 @@ void Double::toString(double aValue, nsA
     if (intDigits < 1) {
         *dest = '0'; ++dest;
         *dest = '.'; ++dest;
         for (i = 0; i > intDigits; --i) {
             *dest = '0'; ++dest;
         }
     }
     // mantissa
-    int firstlen = PR_MIN(intDigits, endp - buf);
+    int firstlen = NS_MIN<size_t>(intDigits, endp - buf);
     for (i = 0; i < firstlen; i++) {
         *dest = buf[i]; ++dest;
     }
     if (i < endp - buf) {
         if (i > 0) {
             *dest = '.'; ++dest;
         }
         for (; i < endp - buf; i++) {
--- a/content/xslt/src/base/txStringUtils.cpp
+++ b/content/xslt/src/base/txStringUtils.cpp
@@ -116,17 +116,17 @@ public:
   typedef PRUnichar value_type;
 
   CopyToLowerCase(nsAString::iterator& aDestIter) : mIter(aDestIter)
   {
   }
 
   void write(const PRUnichar* aSource, PRUint32 aSourceLength)
   {
-    PRUint32 len = PR_MIN(PRUint32(mIter.size_forward()), aSourceLength);
+    PRUint32 len = NS_MIN(PRUint32(mIter.size_forward()), aSourceLength);
     PRUnichar* cp = mIter.get();
     const PRUnichar* end = aSource + len;
     while (aSource != end) {
       PRUnichar ch = *aSource;
       if ((ch >= 'A') && (ch <= 'Z'))
         *cp = ch + ('a' - 'A');
       else
         *cp = ch;
--- a/content/xslt/src/xpath/txMozillaXPathTreeWalker.cpp
+++ b/content/xslt/src/xpath/txMozillaXPathTreeWalker.cpp
@@ -707,17 +707,17 @@ txXPathNodeUtils::comparePosition(const 
         otherNode = otherNode->GetNodeParent();
     }
 
     // Walk back down along the parent-chains until we find where they split.
     PRInt32 total = parents.Length() - 1;
     PRInt32 otherTotal = otherParents.Length() - 1;
     NS_ASSERTION(total != otherTotal, "Can't have same number of parents");
 
-    PRInt32 lastIndex = PR_MIN(total, otherTotal);
+    PRInt32 lastIndex = NS_MIN(total, otherTotal);
     PRInt32 i;
     parent = nsnull;
     for (i = 0; i <= lastIndex; ++i) {
         node = parents.ElementAt(total - i);
         otherNode = otherParents.ElementAt(otherTotal - i);
         if (node != otherNode) {
             if (!parent) {
                 // The two nodes are in different orphan subtrees.
--- a/content/xslt/src/xpath/txNodeSet.cpp
+++ b/content/xslt/src/xpath/txNodeSet.cpp
@@ -547,17 +547,17 @@ PRBool txNodeSet::ensureGrowSize(PRInt32
         mStart = dest;
         mEnd = dest + oldSize;
             
         return PR_TRUE;
     }
 
     // This isn't 100% safe. But until someone manages to make a 1gig nodeset
     // it should be ok.
-    PRInt32 newLength = PR_MAX(oldLength, kTxNodeSetMinSize);
+    PRInt32 newLength = NS_MAX(oldLength, kTxNodeSetMinSize);
 
     while (newLength < ensureSize) {
         newLength *= kTxNodeSetGrowFactor;
     }
 
     txXPathNode* newArr = static_cast<txXPathNode*>
                                      (nsMemory::Alloc(newLength *
                                                          sizeof(txXPathNode)));
--- a/content/xslt/src/xslt/txMozillaXMLOutput.cpp
+++ b/content/xslt/src/xslt/txMozillaXMLOutput.cpp
@@ -679,17 +679,17 @@ txMozillaXMLOutput::createTxWrapper()
         }
 #endif
 
         if (childContent->Tag() == nsGkAtoms::documentTypeNodeName) {
 #ifdef DEBUG
             // The new documentElement should go after the document type.
             // This is needed for cases when there is no existing
             // documentElement in the document.
-            rootLocation = PR_MAX(rootLocation, j + 1);
+            rootLocation = NS_MAX(rootLocation, j + 1);
 #endif
             ++j;
         }
         else {
             rv = mDocument->RemoveChildAt(j, PR_TRUE);
             NS_ENSURE_SUCCESS(rv, rv);
 
             rv = wrapper->AppendChildTo(childContent, PR_TRUE);
--- a/content/xul/content/src/nsXULElement.cpp
+++ b/content/xul/content/src/nsXULElement.cpp
@@ -1034,17 +1034,17 @@ nsXULElement::RemoveChildAt(PRUint32 aIn
     
     if (newCurrentIndex == -2)
         controlElement->SetCurrentItem(nsnull);
     else if (newCurrentIndex > -1) {
         // Make sure the index is still valid
         PRInt32 treeRows;
         listBox->GetRowCount(&treeRows);
         if (treeRows > 0) {
-            newCurrentIndex = PR_MIN((treeRows - 1), newCurrentIndex);
+            newCurrentIndex = NS_MIN((treeRows - 1), newCurrentIndex);
             nsCOMPtr<nsIDOMElement> newCurrentItem;
             listBox->GetItemAtIndex(newCurrentIndex, getter_AddRefs(newCurrentItem));
             nsCOMPtr<nsIDOMXULSelectControlItemElement> xulCurItem = do_QueryInterface(newCurrentItem);
             if (xulCurItem)
                 controlElement->SetCurrentItem(xulCurItem);
         } else {
             controlElement->SetCurrentItem(nsnull);
         }
--- a/db/morkreader/nsMorkReader.cpp
+++ b/db/morkreader/nsMorkReader.cpp
@@ -310,17 +310,17 @@ nsMorkReader::ParseMap(const nsCSubstrin
 
           tokenStart = idx;
           while (idx < len && line[idx] != ')') {
             if (line[idx] == '\\') {
               ++idx; // skip escaped ')' characters
             }
             ++idx;
           }
-          PRUint32 tokenEnd = PR_MIN(idx, len);
+          PRUint32 tokenEnd = NS_MIN(idx, len);
           ++idx;
 
           nsCString value;
           MorkUnescape(Substring(line, tokenStart, tokenEnd - tokenStart),
                        value);
           aMap->Put(key, value);
           key.Truncate(0);
           break;
@@ -458,17 +458,17 @@ nsMorkReader::ParseTable(const nsCSubstr
           tokenStart = idx;
           while (idx < len && line[idx] != '^' && line[idx] != '=') {
             if (line[idx] == '\\') {
               ++idx; // skip escaped characters
             }
             ++idx;
           }
 
-          tokenEnd = PR_MIN(idx, len);
+          tokenEnd = NS_MIN(idx, len);
 
           nsCAutoString column;
           const nsCSubstring &colValue =
             Substring(line, tokenStart, tokenEnd - tokenStart);
           if (columnIsAtom) {
             column.Assign(colValue);
           } else {
             MorkUnescape(colValue, column);
@@ -491,17 +491,17 @@ nsMorkReader::ParseTable(const nsCSubstr
           PRBool valueIsAtom = (line[idx - 1] == '^');
           tokenStart = idx - 1;  // include the '=' or '^' marker in the value
           while (idx < len && line[idx] != ')') {
             if (line[idx] == '\\') {
               ++idx; // skip escaped characters
             }
             ++idx;
           }
-          tokenEnd = PR_MIN(idx, len);
+          tokenEnd = NS_MIN(idx, len);
           ++idx;
 
           const nsCSubstring &value =
             Substring(line, tokenStart, tokenEnd - tokenStart);
           if (valueIsAtom) {
             (*currentRow)[columnIndex] = value;
           } else {
             nsCAutoString value2;
--- a/docshell/base/nsDocShell.cpp
+++ b/docshell/base/nsDocShell.cpp
@@ -3940,16 +3940,20 @@ nsDocShell::DisplayLoadError(nsresult aE
         {
             error.AssignLiteral("remoteXUL");
             break;
         }
         case NS_ERROR_UNSAFE_CONTENT_TYPE:
             // Channel refused to load from an unrecognized content type.
             error.AssignLiteral("unsafeContentType");
             break;
+        case NS_ERROR_CORRUPTED_CONTENT:
+            // Broken Content Detected. e.g. Content-MD5 check failure.
+            error.AssignLiteral("corruptedContentError");
+            break;
         }
     }
 
     // Test if the error should be displayed
     if (error.IsEmpty()) {
         return NS_OK;
     }
 
@@ -6119,16 +6123,17 @@ nsDocShell::EndPageLoad(nsIWebProgress *
     //      encoding error.
     //   2. Send the URI to a keyword server (if enabled)
     //   3. If the error was DNS failure, then add www and .com to the URI
     //      (if appropriate).
     //   4. Throw an error dialog box...
     //
     if (url && NS_FAILED(aStatus)) {
         if (aStatus == NS_ERROR_FILE_NOT_FOUND ||
+            aStatus == NS_ERROR_CORRUPTED_CONTENT ||
             aStatus == NS_ERROR_INVALID_CONTENT_ENCODING) {
             DisplayLoadError(aStatus, url, nsnull, aChannel);
             return NS_OK;
         }
 
         if (sURIFixup) {
             //
             // Try and make an alternative URI from the old one
@@ -8280,22 +8285,24 @@ nsDocShell::InternalLoad(nsIURI * aURI,
 
     if (aLoadType == LOAD_NORMAL ||
         aLoadType == LOAD_STOP_CONTENT ||
         LOAD_TYPE_HAS_FLAGS(aLoadType, LOAD_FLAGS_REPLACE_HISTORY) ||
         aLoadType == LOAD_HISTORY ||
         aLoadType == LOAD_LINK) {
 
         // Split mCurrentURI and aURI on the '#' character.  Make sure we read
-        // the return values of SplitURIAtHash; it might fail because
-        // mCurrentURI is null, for instance, and we don't want to allow a
-        // short-circuited navigation in that case.
+        // the return values of SplitURIAtHash; if it fails, we don't want to
+        // allow a short-circuited navigation.
         nsCAutoString curBeforeHash, curHash, newBeforeHash, newHash;
         nsresult splitRv1, splitRv2;
-        splitRv1 = nsContentUtils::SplitURIAtHash(mCurrentURI, curBeforeHash, curHash);
+        splitRv1 = mCurrentURI ?
+            nsContentUtils::SplitURIAtHash(mCurrentURI,
+                                           curBeforeHash, curHash) :
+            NS_ERROR_FAILURE;
         splitRv2 = nsContentUtils::SplitURIAtHash(aURI, newBeforeHash, newHash);
 
         PRBool sameExceptHashes = NS_SUCCEEDED(splitRv1) &&
                                   NS_SUCCEEDED(splitRv2) &&
                                   curBeforeHash.Equals(newBeforeHash);
 
         PRBool sameDocIdent = PR_FALSE;
         if (mOSHE && aSHEntry) {
@@ -10671,17 +10678,19 @@ nsDocShell::ConfirmRepost(PRBool * aRepo
   }
   if (NS_FAILED(rv)) return rv;
 
   rv = appBundle->GetStringFromName(NS_LITERAL_STRING("resendButton.label").get(),
                                     getter_Copies(button0Title));
   if (NS_FAILED(rv)) return rv;
 
   PRInt32 buttonPressed;
-  PRBool checkState;
+  // The actual value here is irrelevant, but we can't pass an invalid
+  // PRBool through XPConnect.
+  PRBool checkState = PR_FALSE;
   rv = prompter->
          ConfirmEx(nsnull, msgString.get(),
                    (nsIPrompt::BUTTON_POS_0 * nsIPrompt::BUTTON_TITLE_IS_STRING) +
                    (nsIPrompt::BUTTON_POS_1 * nsIPrompt::BUTTON_TITLE_CANCEL),
                    button0Title.get(), nsnull, nsnull, nsnull, &checkState, &buttonPressed);
   if (NS_FAILED(rv)) return rv;
 
   *aRepost = (buttonPressed == 0);
--- a/docshell/resources/content/netError.xhtml
+++ b/docshell/resources/content/netError.xhtml
@@ -324,16 +324,17 @@
         <h1 id="et_proxyConnectFailure">&proxyConnectFailure.title;</h1>
         <h1 id="et_contentEncodingError">&contentEncodingError.title;</h1>
         <h1 id="et_unsafeContentType">&unsafeContentType.title;</h1>
         <h1 id="et_nssFailure2">&nssFailure2.title;</h1>
         <h1 id="et_nssBadCert">&nssBadCert.title;</h1>
         <h1 id="et_malwareBlocked">&malwareBlocked.title;</h1>
         <h1 id="et_cspFrameAncestorBlocked">&cspFrameAncestorBlocked.title;</h1>
         <h1 id="et_remoteXUL">&remoteXUL.title;</h1>
+        <h1 id="et_corruptedContentError">&corruptedContentError.title;</h1>
       </div>
       <div id="errorDescriptionsContainer">
         <div id="ed_generic">&generic.longDesc;</div>
         <div id="ed_dnsNotFound">&dnsNotFound.longDesc;</div>
         <div id="ed_fileNotFound">&fileNotFound.longDesc;</div>
         <div id="ed_malformedURI">&malformedURI.longDesc;</div>
         <div id="ed_protocolNotFound">&protocolNotFound.longDesc;</div>
         <div id="ed_connectionFailure">&connectionFailure.longDesc;</div>
@@ -348,16 +349,17 @@
         <div id="ed_proxyConnectFailure">&proxyConnectFailure.longDesc;</div>
         <div id="ed_contentEncodingError">&contentEncodingError.longDesc;</div>
         <div id="ed_unsafeContentType">&unsafeContentType.longDesc;</div>
         <div id="ed_nssFailure2">&nssFailure2.longDesc;</div>
         <div id="ed_nssBadCert">&nssBadCert.longDesc2;</div>
         <div id="ed_malwareBlocked">&malwareBlocked.longDesc;</div>
         <div id="ed_cspFrameAncestorBlocked">&cspFrameAncestorBlocked.longDesc;</div>
         <div id="ed_remoteXUL">&remoteXUL.longDesc;</div>
+        <div id="ed_corruptedContentError">&corruptedContentError.longDesc;</div>
       </div>
     </div>
 
     <!-- PAGE CONTAINER (for styling purposes only) -->
     <div id="errorPageContainer">
     
       <!-- Error Title -->
       <div id="errorTitle">
--- a/docshell/shistory/src/nsSHistory.cpp
+++ b/docshell/shistory/src/nsSHistory.cpp
@@ -998,17 +998,17 @@ nsSHistory::EvictGlobalContentViewer()
           uri->GetSpec(spec);
           printf("Considering for eviction: %s\n", spec.get());
         }
 #endif
         
         // This SHEntry has a ContentViewer, so check how far away it is from
         // the currently used SHEntry within this SHistory object
         if (viewer) {
-          PRInt32 distance = PR_ABS(shist->mIndex - i);
+          PRInt32 distance = NS_ABS(shist->mIndex - i);
           
 #ifdef DEBUG_PAGE_CACHE
           printf("Has a cached content viewer: %s\n", spec.get());
           printf("mIndex: %d i: %d\n", shist->mIndex, i);
 #endif
           totalContentViewers++;
 
           // If this entry is further away from focus than any previously found
@@ -1208,17 +1208,17 @@ PRBool IsSameTree(nsISHEntry* aEntry1, n
   }
 
   nsCOMPtr<nsISHContainer> container1 = do_QueryInterface(aEntry1);
   nsCOMPtr<nsISHContainer> container2 = do_QueryInterface(aEntry2);
   PRInt32 count1, count2;
   container1->GetChildCount(&count1);
   container2->GetChildCount(&count2);
   // We allow null entries in the end of the child list.
-  PRInt32 count = PR_MAX(count1, count2);
+  PRInt32 count = NS_MAX(count1, count2);
   for (PRInt32 i = 0; i < count; ++i) {
     nsCOMPtr<nsISHEntry> child1, child2;
     container1->GetChildAt(i, getter_AddRefs(child1));
     container2->GetChildAt(i, getter_AddRefs(child2));
     if (!IsSameTree(child1, child2)) {
       return PR_FALSE;
     }
   }
--- a/docshell/test/browser/browser_bug554155.js
+++ b/docshell/test/browser/browser_bug554155.js
@@ -1,14 +1,16 @@
 function test() {
   waitForExplicitFinish();
 
   let tab = gBrowser.addTab("http://example.com");
 
-  tab.linkedBrowser.addEventListener('load', function() {
+  tab.linkedBrowser.addEventListener("load", function() {
+    tab.linkedBrowser.removeEventListener("load", arguments.callee, true);
+
     let numLocationChanges = 0;
 
     let listener = {
       onLocationChange: function() {
         numLocationChanges++;
       }
     };
 
--- a/docshell/test/navigation/browser_bug343515.js
+++ b/docshell/test/navigation/browser_bug343515.js
@@ -9,32 +9,24 @@ var ctx = {};
 // Helper function to check if a window is active
 function isActive(aWindow) {
   var docshell = aWindow.QueryInterface(Ci.nsIInterfaceRequestor)
                         .getInterface(Ci.nsIWebNavigation)
                         .QueryInterface(Ci.nsIDocShell);
   return docshell.isActive;
 }
 
-// Returns a closure that will remove itself as a listener from
-// aElem and then call aCallback. aCallback is executed asynchronously,
-// which is handy because load events fire before mIsDocumentLoaded is actually
-// set to true. :(
-function autoRemovedListener(aElem, aType, aCallback) {
+function oneShotListener(aElem, aType, aCallback) {
+  aElem.addEventListener(aType, function () {
+    aElem.removeEventListener(aType, arguments.callee, true);
 
-  var elem = aElem;
-  var type = aType;
-  var callback = aCallback;
-
-  function remover() {
-    elem.removeEventListener(type, remover, true);
-    executeSoon(callback);
-  }
-
-  return remover;
+    // aCallback is executed asynchronously, which is handy because load
+    // events fire before mIsDocumentLoaded is actually set to true. :(
+    executeSoon(aCallback);
+  }, true);
 }
 
 // Returns a closure that iteratively (BFS) waits for all
 // of the descendant frames of aInitialWindow to finish loading,
 // then calls aFinalCallback.
 function frameLoadWaiter(aInitialWindow, aFinalCallback) {
 
   // The window we're currently waiting on
@@ -53,17 +45,17 @@ function frameLoadWaiter(aInitialWindow,
       waitQueue.push(curr.frames[i]);
 
     // Handle the next window in the queue
     if (waitQueue.length >= 1) {
       curr = waitQueue.shift();
       if (curr.document.readyState == "complete")
         frameLoadCallback();
       else
-        curr.addEventListener("load", autoRemovedListener(curr, "load", frameLoadCallback), true);
+        oneShotListener(curr, "load", frameLoadCallback);
       return;
     }
 
     // Otherwise, we're all done. Call the final callback
     finalCallback();
   }
 
   return frameLoadCallback;
@@ -88,19 +80,17 @@ function step1() {
 
   // Our current tab should be active
   ok(isActive(ctx.tab0Window), "Tab 0 should be active at test start");
 
   // Open a New Tab
   ctx.tab1 = gBrowser.addTab(testPath + "bug343515_pg1.html");
   ctx.tab1Browser = gBrowser.getBrowserForTab(ctx.tab1);
   ctx.tab1Window = ctx.tab1Browser.contentWindow;
-  ctx.tab1Browser.addEventListener("load",
-                                   autoRemovedListener(ctx.tab1Browser, "load", step2),
-                                   true);
+  oneShotListener(ctx.tab1Browser, "load", step2);
 }
 
 function step2() {
 
   // Our current tab should still be active
   ok(isActive(ctx.tab0Window), "Tab 0 should still be active");
   ok(!isActive(ctx.tab1Window), "Tab 1 should not be active");
 
@@ -110,40 +100,34 @@ function step2() {
   // Tab 1 should now be active
   ok(!isActive(ctx.tab0Window), "Tab 0 should be inactive");
   ok(isActive(ctx.tab1Window), "Tab 1 should be active");
 
   // Open another tab
   ctx.tab2 = gBrowser.addTab(testPath + "bug343515_pg2.html");
   ctx.tab2Browser = gBrowser.getBrowserForTab(ctx.tab2);
   ctx.tab2Window = ctx.tab2Browser.contentWindow;
-  ctx.tab2Browser.addEventListener("load",
-                                   autoRemovedListener(ctx.tab2Browser, "load",
-                                                       frameLoadWaiter(ctx.tab2Window, step3)),
-                                   true);
+  oneShotListener(ctx.tab2Browser, "load", frameLoadWaiter(ctx.tab2Window, step3));
 }
 
 function step3() {
 
   // Tab 0 should be inactive, Tab 1 should be active
   ok(!isActive(ctx.tab0Window), "Tab 0 should be inactive");
   ok(isActive(ctx.tab1Window), "Tab 1 should be active");
 
   // Tab 2's window _and_ its iframes should be inactive
   ok(!isActive(ctx.tab2Window), "Tab 2 should be inactive");
   is(ctx.tab2Window.frames.length, 2, "Tab 2 should have 2 iframes");
   ok(!isActive(ctx.tab2Window.frames[0]), "Tab2 iframe 0 should be inactive");
   ok(!isActive(ctx.tab2Window.frames[1]), "Tab2 iframe 1 should be inactive");
 
   // Navigate tab 2 to a different page
   ctx.tab2Window.location = testPath + "bug343515_pg3.html";
-  ctx.tab2Browser.addEventListener("load",
-                                  autoRemovedListener(ctx.tab2Browser, "load",
-                                                      frameLoadWaiter(ctx.tab2Window, step4)),
-                                  true);
+  oneShotListener(ctx.tab2Browser, "load", frameLoadWaiter(ctx.tab2Window, step4));
 }
 
 function step4() {
 
   // Tab 0 should be inactive, Tab 1 should be active
   ok(!isActive(ctx.tab0Window), "Tab 0 should be inactive");
   ok(isActive(ctx.tab1Window), "Tab 1 should be active");
 
@@ -162,20 +146,17 @@ function step4() {
   ok(!isActive(ctx.tab0Window), "Tab 0 should be inactive");
   ok(!isActive(ctx.tab1Window), "Tab 1 should be inactive");
   ok(isActive(ctx.tab2Window), "Tab 2 should be active");
   ok(isActive(ctx.tab2Window.frames[0]), "Tab2 iframe 0 should be active");
   ok(isActive(ctx.tab2Window.frames[0].frames[0]), "Tab2 iframe 0 subiframe 0 should be active");
   ok(isActive(ctx.tab2Window.frames[1]), "Tab2 iframe 1 should be active");
 
   // Go back
-  ctx.tab2Browser.addEventListener("pageshow",
-                                   autoRemovedListener(ctx.tab2Browser, "pageshow",
-                                                       frameLoadWaiter(ctx.tab2Window, step5)),
-                                   true);
+  oneShotListener(ctx.tab2Browser, "pageshow", frameLoadWaiter(ctx.tab2Window, step5));
   ctx.tab2Browser.goBack();
 
 }
 
 function step5() {
 
   // Check everything
   ok(!isActive(ctx.tab0Window), "Tab 0 should be inactive");
@@ -184,39 +165,33 @@ function step5() {
   ok(isActive(ctx.tab2Window.frames[0]), "Tab2 iframe 0 should be active");
   ok(isActive(ctx.tab2Window.frames[1]), "Tab2 iframe 1 should be active");
 
   // Switch to tab 1
   gBrowser.selectedTab = ctx.tab1;
 
   // Navigate to page 3
   ctx.tab1Window.location = testPath + "bug343515_pg3.html";
-  ctx.tab1Browser.addEventListener("load",
-                                   autoRemovedListener(ctx.tab1Browser, "load",
-                                                       frameLoadWaiter(ctx.tab1Window, step6)),
-                                   true);
+  oneShotListener(ctx.tab1Browser, "load", frameLoadWaiter(ctx.tab1Window, step6));
 }
 
 function step6() {
 
   // Check everything
   ok(!isActive(ctx.tab0Window), "Tab 0 should be inactive");
   ok(isActive(ctx.tab1Window), "Tab 1 should be active");
   ok(isActive(ctx.tab1Window.frames[0]), "Tab1 iframe 0 should be active");
   ok(isActive(ctx.tab1Window.frames[0].frames[0]), "Tab1 iframe 0 subiframe 0 should be active");
   ok(isActive(ctx.tab1Window.frames[1]), "Tab1 iframe 1 should be active");
   ok(!isActive(ctx.tab2Window), "Tab 2 should be inactive");
   ok(!isActive(ctx.tab2Window.frames[0]), "Tab2 iframe 0 should be inactive");
   ok(!isActive(ctx.tab2Window.frames[1]), "Tab2 iframe 1 should be inactive");
 
   // Go forward on tab 2
-  ctx.tab2Browser.addEventListener("pageshow",
-                                   autoRemovedListener(ctx.tab2Browser, "pageshow",
-                                                       frameLoadWaiter(ctx.tab2Window, step7)),
-                                   true);
+  oneShotListener(ctx.tab2Browser, "pageshow", frameLoadWaiter(ctx.tab2Window, step7));
   var tab2docshell = ctx.tab2Window.QueryInterface(Ci.nsIInterfaceRequestor)
                                    .getInterface(Ci.nsIWebNavigation);
   tab2docshell.goForward();
 }
 
 function step7() {
 
   ctx.tab2Window = ctx.tab2Browser.contentWindow;
--- a/dom/base/nsDOMClassInfo.cpp
+++ b/dom/base/nsDOMClassInfo.cpp
@@ -223,17 +223,16 @@
 #include "nsIDOMDocumentType.h"
 #include "nsIDOMDOMImplementation.h"
 #include "nsIDOMDocumentFragment.h"
 #include "nsDOMAttribute.h"
 #include "nsIDOMText.h"
 #include "nsIDOMComment.h"
 #include "nsIDOMCDATASection.h"
 #include "nsIDOMProcessingInstruction.h"
-#include "nsIDOMNotation.h"
 #include "nsIDOMNSEvent.h"
 #include "nsIDOMDataContainerEvent.h"
 #include "nsIDOMKeyEvent.h"
 #include "nsIDOMMouseEvent.h"
 #include "nsIDOMMouseScrollEvent.h"
 #include "nsIDOMDragEvent.h"
 #include "nsIDOMCommandEvent.h"
 #include "nsIDOMPopupBlockedEvent.h"
@@ -602,18 +601,16 @@ DOMCI_DATA(SmartCardEvent, void)
 DOMCI_DATA(ContentFrameMessageManager, void)
 
 DOMCI_DATA(DOMPrototype, void)
 DOMCI_DATA(DOMConstructor, void)
 
 DOMCI_DATA(Worker, void)
 DOMCI_DATA(ChromeWorker, void)
 
-DOMCI_DATA(Notation, void)
-
 #define NS_DEFINE_CLASSINFO_DATA_WITH_NAME(_class, _name, _helper,            \
                                            _flags)                            \
   { #_name,                                                                   \
     nsnull,                                                                   \
     { _helper::doCreate },                                                    \
     nsnull,                                                                   \
     nsnull,                                                                   \
     nsnull,                                                                   \
@@ -727,17 +724,16 @@ static nsDOMClassInfoData sClassInfoData
                            NODE_SCRIPTABLE_FLAGS)
   NS_DEFINE_CLASSINFO_DATA(Text, nsNodeSH,
                            NODE_SCRIPTABLE_FLAGS)
   NS_DEFINE_CLASSINFO_DATA(Comment, nsNodeSH,
                            NODE_SCRIPTABLE_FLAGS)
   NS_DEFINE_CLASSINFO_DATA(CDATASection, nsNodeSH, NODE_SCRIPTABLE_FLAGS)
   NS_DEFINE_CLASSINFO_DATA(ProcessingInstruction, nsNodeSH,
                            NODE_SCRIPTABLE_FLAGS)
-  NS_DEFINE_CLASSINFO_DATA(Notation, nsNodeSH, NODE_SCRIPTABLE_FLAGS)
   NS_DEFINE_CLASSINFO_DATA(NodeList, nsNodeListSH, ARRAY_SCRIPTABLE_FLAGS)
   NS_DEFINE_CLASSINFO_DATA(NamedNodeMap, nsNamedNodeMapSH,
                            ARRAY_SCRIPTABLE_FLAGS)
 
   // Misc Core related classes
 
   // Event
   NS_DEFINE_CLASSINFO_DATA(Event, nsDOMGenericSH,
@@ -1418,20 +1414,18 @@ static nsDOMClassInfoData sClassInfoData
   NS_DEFINE_CLASSINFO_DATA(NotifyAudioAvailableEvent, nsDOMGenericSH,
                            DOM_DEFAULT_SCRIPTABLE_FLAGS)
 
   NS_DEFINE_CLASSINFO_DATA(SimpleGestureEvent, nsDOMGenericSH,
                            DOM_DEFAULT_SCRIPTABLE_FLAGS)
 
   NS_DEFINE_CLASSINFO_DATA(MozTouchEvent, nsDOMGenericSH,
                            DOM_DEFAULT_SCRIPTABLE_FLAGS)
-#ifdef MOZ_MATHML
   NS_DEFINE_CLASSINFO_DATA_WITH_NAME(MathMLElement, Element, nsElementSH,
                                      ELEMENT_SCRIPTABLE_FLAGS)
-#endif
 
   NS_DEFINE_CLASSINFO_DATA(Worker, nsDOMGenericSH,
                            DOM_DEFAULT_SCRIPTABLE_FLAGS)
   NS_DEFINE_CHROME_ONLY_CLASSINFO_DATA(ChromeWorker, nsDOMGenericSH,
                                        DOM_DEFAULT_SCRIPTABLE_FLAGS)
 
   NS_DEFINE_CLASSINFO_DATA(WebGLRenderingContext, nsWebGLViewportHandlerSH,
                            DOM_DEFAULT_SCRIPTABLE_FLAGS)
@@ -2555,20 +2549,16 @@ nsDOMClassInfo::Init()
 
   DOM_CLASSINFO_MAP_BEGIN(ProcessingInstruction, nsIDOMProcessingInstruction)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMProcessingInstruction)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMNSEventTarget)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMEventTarget)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOM3Node)
   DOM_CLASSINFO_MAP_END
 
-  DOM_CLASSINFO_MAP_BEGIN(Notation, nsIDOMNotation)
-    DOM_CLASSINFO_MAP_ENTRY(nsIDOMNotation)
-  DOM_CLASSINFO_MAP_END
-
   DOM_CLASSINFO_MAP_BEGIN(NodeList, nsIDOMNodeList)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMNodeList)
   DOM_CLASSINFO_MAP_END
 
   DOM_CLASSINFO_MAP_BEGIN(NamedNodeMap, nsIDOMNamedNodeMap)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMNamedNodeMap)
   DOM_CLASSINFO_MAP_END
 
@@ -4134,26 +4124,24 @@ nsDOMClassInfo::Init()
 
   DOM_CLASSINFO_MAP_BEGIN(MozTouchEvent, nsIDOMMozTouchEvent)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMMozTouchEvent)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMMouseEvent)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMNSMouseEvent)
     DOM_CLASSINFO_UI_EVENT_MAP_ENTRIES
   DOM_CLASSINFO_MAP_END
 
-#ifdef MOZ_MATHML
   DOM_CLASSINFO_MAP_BEGIN_NO_CLASS_IF(MathMLElement, nsIDOMElement)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMElement)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMNSElement)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMNSEventTarget)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMEventTarget)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOM3Node)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMNodeSelector)
   DOM_CLASSINFO_MAP_END
-#endif
 
   DOM_CLASSINFO_MAP_BEGIN(Worker, nsIWorker)
     DOM_CLASSINFO_MAP_ENTRY(nsIWorker)
     DOM_CLASSINFO_MAP_ENTRY(nsIAbstractWorker)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMNSEventTarget)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMEventTarget)
   DOM_CLASSINFO_MAP_END
 
--- a/dom/base/nsDOMClassInfoClasses.h
+++ b/dom/base/nsDOMClassInfoClasses.h
@@ -58,17 +58,16 @@ DOMCI_CLASS(DOMTokenList)
 DOMCI_CLASS(DOMSettableTokenList)
 DOMCI_CLASS(DocumentFragment)
 DOMCI_CLASS(Element)
 DOMCI_CLASS(Attr)
 DOMCI_CLASS(Text)
 DOMCI_CLASS(Comment)
 DOMCI_CLASS(CDATASection)
 DOMCI_CLASS(ProcessingInstruction)
-DOMCI_CLASS(Notation)
 DOMCI_CLASS(NodeList)
 DOMCI_CLASS(NamedNodeMap)
 
 // Event classes
 DOMCI_CLASS(Event)
 DOMCI_CLASS(MutationEvent)
 DOMCI_CLASS(UIEvent)
 DOMCI_CLASS(MouseEvent)
@@ -450,19 +449,17 @@ DOMCI_CLASS(DataTransfer)
 DOMCI_CLASS(NotifyPaintEvent)
 
 DOMCI_CLASS(NotifyAudioAvailableEvent)
 
 DOMCI_CLASS(SimpleGestureEvent)
 
 DOMCI_CLASS(MozTouchEvent)
 
-#ifdef MOZ_MATHML
 DOMCI_CLASS(MathMLElement)
-#endif
 
 DOMCI_CLASS(Worker)
 DOMCI_CLASS(ChromeWorker)
 
 // WebGL
 DOMCI_CLASS(WebGLRenderingContext)
 DOMCI_CLASS(WebGLBuffer)
 DOMCI_CLASS(WebGLTexture)
--- a/dom/base/nsGlobalWindow.cpp
+++ b/dom/base/nsGlobalWindow.cpp
@@ -185,17 +185,17 @@
 #include "nsIXULAppInfo.h"
 #include "nsNetUtil.h"
 #include "nsFocusManager.h"
 #include "nsIXULWindow.h"
 #include "nsEventStateManager.h"
 #ifdef MOZ_XUL
 #include "nsXULPopupManager.h"
 #include "nsIDOMXULControlElement.h"
-#include "nsIFrame.h"
+#include "nsMenuPopupFrame.h"
 #endif
 
 #include "xpcprivate.h"
 
 #ifdef NS_PRINTING
 #include "nsIPrintSettings.h"
 #include "nsIPrintSettingsService.h"
 #include "nsIWebBrowserPrint.h"
@@ -10209,19 +10209,38 @@ nsGlobalChromeWindow::GetAttentionWithCy
   if (widget) {
     rv = widget->GetAttention(aCycleCount);
   }
 
   return rv;
 }
 
 NS_IMETHODIMP
-nsGlobalChromeWindow::BeginWindowMove(nsIDOMEvent *aMouseDownEvent)
-{
-  nsCOMPtr<nsIWidget> widget = GetMainWidget();
+nsGlobalChromeWindow::BeginWindowMove(nsIDOMEvent *aMouseDownEvent, nsIDOMElement* aPanel)
+{
+  nsCOMPtr<nsIWidget> widget;
+
+  // if a panel was supplied, use its widget instead.
+#ifdef MOZ_XUL
+  if (aPanel) {
+    nsCOMPtr<nsIContent> panel = do_QueryInterface(aPanel);
+    NS_ENSURE_TRUE(panel, NS_ERROR_FAILURE);
+
+    nsIFrame* frame = panel->GetPrimaryFrame();
+    NS_ENSURE_TRUE(frame && frame->GetType() == nsGkAtoms::menuPopupFrame, NS_OK);
+
+    (static_cast<nsMenuPopupFrame*>(frame))->GetWidget(getter_AddRefs(widget));
+  }
+  else {
+#endif
+    widget = GetMainWidget();
+#ifdef MOZ_XUL
+  }
+#endif
+
   if (!widget) {
     return NS_OK;
   }
 
   nsCOMPtr<nsIPrivateDOMEvent> privEvent = do_QueryInterface(aMouseDownEvent);
   NS_ENSURE_TRUE(privEvent, NS_ERROR_FAILURE);
   nsEvent *internalEvent = privEvent->GetInternalNSEvent();
   NS_ENSURE_TRUE(internalEvent &&
--- a/dom/base/nsJSEnvironment.cpp
+++ b/dom/base/nsJSEnvironment.cpp
@@ -1004,17 +1004,17 @@ nsJSContext::JSOptionChangedCallback(con
   ::JS_SetOptions(context->mContext, newDefaultJSOptions & JSRUNOPTION_MASK);
 
   // Save the new defaults for the next page load (InitContext).
   context->mDefaultJSOptions = newDefaultJSOptions;
 
 #ifdef JS_GC_ZEAL
   PRInt32 zeal = Preferences::GetInt(js_zeal_option_str, -1);
   if (zeal >= 0)
-    ::JS_SetGCZeal(context->mContext, (PRUint8)zeal);
+    ::JS_SetGCZeal(context->mContext, (PRUint8)zeal, JS_DEFAULT_ZEAL_FREQ, JS_FALSE);
 #endif
 
   return 0;
 }
 
 nsJSContext::nsJSContext(JSRuntime *aRuntime)
   : mGCOnDestruction(PR_TRUE),
     mExecuteDepth(0)
--- a/dom/indexedDB/IDBFactory.cpp
+++ b/dom/indexedDB/IDBFactory.cpp
@@ -622,17 +622,17 @@ IDBFactory::SetCurrentDatabase(IDBDataba
 
   return true;
 }
 
 // static
 PRUint32
 IDBFactory::GetIndexedDBQuota()
 {
-  return PRUint32(PR_MAX(gIndexedDBQuota, 0));
+  return PRUint32(NS_MAX(gIndexedDBQuota, 0));
 }
 
 // static
 void
 IDBFactory::NoteUsedByProcessType(GeckoProcessType aProcessType)
 {
   if (gAllowedProcessType == GeckoProcessType_Invalid) {
     gAllowedProcessType = aProcessType;
@@ -978,19 +978,19 @@ OpenDatabaseHelper::DoDatabaseWork(mozIS
   rv = IDBFactory::LoadDatabaseInformation(connection, mDatabaseId, mVersion,
                                            mObjectStores);
   NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
 
   for (PRUint32 i = 0; i < mObjectStores.Length(); i++) {
     nsAutoPtr<ObjectStoreInfo>& objectStoreInfo = mObjectStores[i];
     for (PRUint32 j = 0; j < objectStoreInfo->indexes.Length(); j++) {
       IndexInfo& indexInfo = objectStoreInfo->indexes[j];
-      mLastIndexId = PR_MAX(indexInfo.id, mLastIndexId);
+      mLastIndexId = NS_MAX(indexInfo.id, mLastIndexId);
     }
-    mLastObjectStoreId = PR_MAX(objectStoreInfo->id, mLastObjectStoreId);
+    mLastObjectStoreId = NS_MAX(objectStoreInfo->id, mLastObjectStoreId);
   }
 
   return NS_OK;
 }
 
 nsresult
 OpenDatabaseHelper::GetSuccessResult(JSContext* aCx,
                                      jsval *aVal)
--- a/dom/interfaces/base/domstubs.idl
+++ b/dom/interfaces/base/domstubs.idl
@@ -50,17 +50,16 @@ interface nsIDOMDOMImplementation;
 interface nsIDOMDocument;
 interface nsIDOMDocumentFragment;
 interface nsIDOMDocumentType;
 interface nsIDOMElement;
 interface nsIDOMNSElement;
 interface nsIDOMNamedNodeMap;
 interface nsIDOMNode;
 interface nsIDOMNodeList;
-interface nsIDOMNotation;
 interface nsIDOMProcessingInstruction;
 interface nsIDOMText;
 interface nsIDOMDOMStringList;
 interface nsIDOMDOMTokenList;
 interface nsIDOMNameList;
 interface nsIDOMClientRect;
 interface nsIDOMClientRectList;
 
--- a/dom/interfaces/base/nsIDOMChromeWindow.idl
+++ b/dom/interfaces/base/nsIDOMChromeWindow.idl
@@ -38,17 +38,17 @@
 
 #include "domstubs.idl"
 
 interface nsIBrowserDOMWindow;
 interface nsIDOMElement;
 interface nsIDOMEvent;
 interface nsIChromeFrameMessageManager;
 
-[scriptable, uuid(ec38cbaf-372f-4874-bc7a-dbf1f0b3d755)]
+[scriptable, uuid(7cfbc355-cbf9-4408-8e4c-a3c603ff1428)]
 interface nsIDOMChromeWindow : nsISupports
 {
   const unsigned short STATE_MAXIMIZED = 1;
   const unsigned short STATE_MINIMIZED = 2;
   const unsigned short STATE_NORMAL = 3;
   const unsigned short STATE_FULLSCREEN = 4;
 
   readonly attribute unsigned short              windowState;
@@ -79,13 +79,15 @@ interface nsIDOMChromeWindow : nsISuppor
   readonly attribute nsIChromeFrameMessageManager messageManager;
 
   /**
    * On some operating systems, we must allow the window manager to
    * handle window dragging. This function tells the window manager to
    * start dragging the window. This function will fail unless called
    * while the left mouse button is held down, callers must check this.
    *
+   * The optional panel argument should be set when moving a panel.
+   *
    * Returns NS_ERROR_NOT_IMPLEMENTED (and thus throws in JS) if the OS
    * doesn't support this.
    */
-  void beginWindowMove(in nsIDOMEvent mouseDownEvent);
+  void beginWindowMove(in nsIDOMEvent mouseDownEvent, [optional] in nsIDOMElement panel);
 };
--- a/dom/interfaces/core/Makefile.in
+++ b/dom/interfaces/core/Makefile.in
@@ -55,23 +55,21 @@ SDK_XPIDLSRCS =                         
 	nsIDOMDOMImplementation.idl		\
 	nsIDOMDocument.idl			\
 	nsIDOMDocumentFragment.idl		\
 	nsIDOMDocumentType.idl			\
 	nsIDOMElement.idl			\
 	nsIDOMNamedNodeMap.idl			\
 	nsIDOMNode.idl				\
 	nsIDOMNodeList.idl			\
-	nsIDOMNotation.idl			\
 	nsIDOMProcessingInstruction.idl		\
 	nsIDOMText.idl				\
 	$(NULL)
 XPIDLSRCS =                                     \
 	nsIDOM3Node.idl				\
-	nsIDOM3TypeInfo.idl			\
 	nsIDOM3Attr.idl				\
 	nsIDOMDOMStringList.idl			\
 	nsIDOMNameList.idl			\
 	nsIDOMXMLDocument.idl			\
 	nsIDOMUserDataHandler.idl		\
 	nsIDOMNSEditableElement.idl		\
 	nsIDOMNSElement.idl			\
 	nsIDOMNodeSelector.idl			\
--- a/dom/interfaces/core/nsIDOM3Attr.idl
+++ b/dom/interfaces/core/nsIDOM3Attr.idl
@@ -30,18 +30,15 @@
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "domstubs.idl"
-#include "nsIDOM3TypeInfo.idl"
 
-[scriptable, uuid(274ef301-065c-450d-a75b-e7673d257293)]
+[scriptable, uuid(dc3ac0ee-9afb-4d1e-a49c-f5042e5bcf65)]
 interface nsIDOM3Attr : nsISupports
 {
     // Introduced in DOM Level 3:
-    readonly attribute nsIDOM3TypeInfo        schemaTypeInfo;
-    // Introduced in DOM Level 3:
     readonly attribute boolean                isId;
 };
deleted file mode 100644
--- a/dom/interfaces/core/nsIDOM3TypeInfo.idl
+++ /dev/null
@@ -1,55 +0,0 @@
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is mozilla.org code.
- *
- * The Initial Developer of the Original Code is
- * Alexander J. Vincent <ajvincent@gmail.com>.
- * Portions created by the Initial Developer are Copyright (C) 2006
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either of the GNU General Public License Version 2 or later (the "GPL"),
- * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-#include "domstubs.idl"
-
-// Introduced in DOM Level 3:
-[scriptable, uuid(2a1088c7-499a-49a7-9d3b-1970d21532ab)]
-interface nsIDOM3TypeInfo : nsISupports
-{
-    readonly attribute DOMString       typeName;
-    readonly attribute DOMString       typeNamespace;
-
-    // DerivationMethods
-    const unsigned long       DERIVATION_RESTRICTION         = 0x00000001;
-    const unsigned long       DERIVATION_EXTENSION           = 0x00000002;
-    const unsigned long       DERIVATION_UNION               = 0x00000004;
-    const unsigned long       DERIVATION_LIST                = 0x00000008;
-
-    boolean            isDerivedFrom(in DOMString typeNamespaceArg, 
-                                     in DOMString typeNameArg, 
-                                     in unsigned long derivationMethod);
-};
deleted file mode 100644
--- a/dom/interfaces/core/nsIDOMNotation.idl
+++ /dev/null
@@ -1,56 +0,0 @@
-/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is mozilla.org code.
- *
- * The Initial Developer of the Original Code is
- * Netscape Communications Corporation.
- * Portions created by the Initial Developer are Copyright (C) 2000
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *   Vidur Apparao <vidur@netscape.com> (original author)
- *   Johnny Stenback <jst@netscape.com>
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either of the GNU General Public License Version 2 or later (the "GPL"),
- * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-#include "nsIDOMNode.idl"
-
-/**
- * The nsIDOMNotation interface represents a notation declared in the DTD.
- * A notation  either declares, by name, the format of an unparsed entity, 
- * or is used for formal declaration of processing instruction targets.
- *
- * For more information on this interface please see 
- * http://www.w3.org/TR/DOM-Level-2-Core/
- */
-
-[scriptable, uuid(43658ade-a157-447a-8dcd-aa7fc824ef0a)]
-interface nsIDOMNotation : nsIDOMNode
-{
-  readonly attribute DOMString            publicId;
-  readonly attribute DOMString            systemId;
-};
--- a/dom/ipc/ContentParent.cpp
+++ b/dom/ipc/ContentParent.cpp
@@ -685,23 +685,23 @@ void
 ContentParent::SetChildMemoryReporters(const InfallibleTArray<MemoryReport>& report)
 {
     nsCOMPtr<nsIMemoryReporterManager> mgr = do_GetService("@mozilla.org/memory-reporter-manager;1");
     for (PRInt32 i = 0; i < mMemoryReporters.Count(); i++)
         mgr->UnregisterReporter(mMemoryReporters[i]);
 
     for (PRUint32 i = 0; i < report.Length(); i++) {
 
-        nsCString prefix = report[i].prefix();
-        nsCString path   = report[i].path();
-        PRInt32   kind   = report[i].kind();
-        nsCString desc   = report[i].desc();
+        nsCString process  = report[i].process();
+        nsCString path     = report[i].path();
+        PRInt32   kind     = report[i].kind();
+        nsCString desc     = report[i].desc();
         PRInt64 memoryUsed = report[i].memoryUsed();
         
-        nsRefPtr<nsMemoryReporter> r = new nsMemoryReporter(prefix,
+        nsRefPtr<nsMemoryReporter> r = new nsMemoryReporter(process,
                                                             path,
                                                             kind,
                                                             desc,
                                                             memoryUsed);
       mMemoryReporters.AppendObject(r);
       mgr->RegisterReporter(r);
     }
 
--- a/dom/ipc/PMemoryReportRequest.ipdl
+++ b/dom/ipc/PMemoryReportRequest.ipdl
@@ -37,17 +37,17 @@
  * ***** END LICENSE BLOCK ***** */
 
 include protocol PContent;
 
 namespace mozilla {
 namespace dom {
 
 struct MemoryReport {
-  nsCString prefix;
+  nsCString process;
   nsCString path;
   PRInt32 kind;
   nsCString desc;
   PRInt64 memoryUsed;
 };
 
 protocol PMemoryReportRequest {
   manager PContent;
--- a/dom/ipc/TabChild.cpp
+++ b/dom/ipc/TabChild.cpp
@@ -839,17 +839,16 @@ TabChild::InitTabChildGlobal()
   NS_ENSURE_TRUE(cx, false);
 
   mCx = cx;
 
   nsContentUtils::XPConnect()->SetSecurityManagerForJSContext(cx, nsContentUtils::GetSecurityManager(), 0);
   nsContentUtils::GetSecurityManager()->GetSystemPrincipal(getter_AddRefs(mPrincipal));
 
   JS_SetNativeStackQuota(cx, 128 * sizeof(size_t) * 1024);
-  JS_SetScriptStackQuota(cx, 25 * sizeof(size_t) * 1024 * 1024);
 
   JS_SetOptions(cx, JS_GetOptions(cx) | JSOPTION_JIT | JSOPTION_ANONFUNFIX | JSOPTION_PRIVATE_IS_NSISUPPORTS);
   JS_SetVersion(cx, JSVERSION_LATEST);
   JS_SetErrorReporter(cx, ContentScriptErrorReporter);
 
   xpc_LocalizeContext(cx);
 
   JSAutoRequest ar(cx);
--- a/dom/ipc/TabParent.cpp
+++ b/dom/ipc/TabParent.cpp
@@ -395,17 +395,17 @@ TabParent::HandleQueryContentEvent(nsQue
   aEvent.mSucceeded = PR_FALSE;
   aEvent.mWasAsync = PR_FALSE;
   aEvent.mReply.mFocusedWidget = nsCOMPtr<nsIWidget>(GetWidget()).get();
 
   switch (aEvent.message)
   {
   case NS_QUERY_SELECTED_TEXT:
     {
-      aEvent.mReply.mOffset = PR_MIN(mIMESelectionAnchor, mIMESelectionFocus);
+      aEvent.mReply.mOffset = NS_MIN(mIMESelectionAnchor, mIMESelectionFocus);
       if (mIMESelectionAnchor == mIMESelectionFocus) {
         aEvent.mReply.mString.Truncate(0);
       } else {
         if (mIMESelectionAnchor > mIMECacheText.Length() ||
             mIMESelectionFocus > mIMECacheText.Length()) {
           break;
         }
         PRUint32 selLen = mIMESelectionAnchor > mIMESelectionFocus ?
@@ -441,17 +441,17 @@ TabParent::HandleQueryContentEvent(nsQue
   }
   return true;
 }
 
 bool
 TabParent::SendCompositionEvent(nsCompositionEvent& event)
 {
   mIMEComposing = event.message == NS_COMPOSITION_START;
-  mIMECompositionStart = PR_MIN(mIMESelectionAnchor, mIMESelectionFocus);
+  mIMECompositionStart = NS_MIN(mIMESelectionAnchor, mIMESelectionFocus);
   if (mIMECompositionEnding)
     return true;
   event.seqno = ++mIMESeqno;
   return PBrowserParent::SendCompositionEvent(event);
 }
 
 /**
  * During ResetInputState or CancelComposition, widget usually sends a
@@ -466,17 +466,17 @@ TabParent::SendTextEvent(nsTextEvent& ev
   if (mIMECompositionEnding) {
     mIMECompositionText = event.theText;
     return true;
   }
 
   // We must be able to simulate the selection because
   // we might not receive selection updates in time
   if (!mIMEComposing) {
-    mIMECompositionStart = PR_MIN(mIMESelectionAnchor, mIMESelectionFocus);
+    mIMECompositionStart = NS_MIN(mIMESelectionAnchor, mIMESelectionFocus);
   }
   mIMESelectionAnchor = mIMESelectionFocus =
       mIMECompositionStart + event.theText.Length();
 
   event.seqno = ++mIMESeqno;
   return PBrowserParent::SendTextEvent(event);
 }
 
--- a/dom/locales/en-US/chrome/appstrings.properties
+++ b/dom/locales/en-US/chrome/appstrings.properties
@@ -57,9 +57,10 @@ externalProtocolTitle=External Protocol 
 externalProtocolPrompt=An external application must be launched to handle %1$S: links.\n\n\nRequested link:\n\n%2$S\n\nApplication: %3$S\n\n\nIf you were not expecting this request it may be an attempt to exploit a weakness in that other program. Cancel this request unless you are sure it is not malicious.\n
 #LOCALIZATION NOTE (externalProtocolUnknown): The following string is shown if the application name can't be determined
 externalProtocolUnknown=<Unknown>
 externalProtocolChkMsg=Remember my choice for all links of this type.
 externalProtocolLaunchBtn=Launch application
 malwareBlocked=The site at %S has been reported as an attack site and has been blocked based on your security preferences.
 phishingBlocked=The web site at %S has been reported as a web forgery designed to trick users into sharing personal or financial information.
 cspFrameAncestorBlocked=This page has a content security policy that prevents it from being embedded in this way.
+corruptedContentError=The page you are trying to view cannot be shown because an error in the data transmission was detected.
 remoteXUL=This page uses an unsupported technology that is no longer available by default.
--- a/dom/locales/en-US/chrome/netError.dtd
+++ b/dom/locales/en-US/chrome/netError.dtd
@@ -79,16 +79,19 @@
 <!ENTITY phishingBlocked.longDesc "
 <p>Entering any personal information on this page may result in identity theft or other fraud.</p>
 <p>These types of web forgeries are used in scams known as phishing attacks, in which fraudulent web pages and emails are used to imitate sources you may trust.</p>
 ">
 
 <!ENTITY cspFrameAncestorBlocked.title "Blocked by Content Security Policy">
 <!ENTITY cspFrameAncestorBlocked.longDesc "<p>The browser prevented this page from loading in this way because the page has a content security policy that disallows it.</p>">
 
+<!ENTITY corruptedContentError.title "Corrupted Content Error">
+<!ENTITY corruptedContentError.longDesc "<p>The page you are trying to view cannot be shown because an error in the data transmission was detected.</p><ul><li>Please contact the website owners to inform them of this problem.</li></ul>">
+
 <!ENTITY remoteXUL.title "Remote XUL">
 <!ENTITY remoteXUL.longDesc "<p><ul><li>Please contact the website owners to inform them of this problem.</li></ul></p>">
 
 <!-- Include app-specific error messages - do not change this in localization!
      Some applications might override netErrorApp.dtd with their specific version,
      this inclusion needs to be intact for that approach to work correctly.
      Please, try to keep this at the end of the file. -->
 <!ENTITY % netErrorAppDTD SYSTEM "chrome://global/locale/netErrorApp.dtd">
--- a/dom/plugins/base/PluginPRLibrary.cpp
+++ b/dom/plugins/base/PluginPRLibrary.cpp
@@ -253,27 +253,16 @@ PluginPRLibrary::GetImage(NPP instance, 
 }
 
 nsresult
 PluginPRLibrary::GetImageSize(NPP instance, nsIntSize* aSize)
 {
   return NS_ERROR_NOT_IMPLEMENTED;
 }
 
-#if defined(XP_MACOSX)
-nsresult
-PluginPRLibrary::IsRemoteDrawingCoreAnimation(NPP instance, PRBool *aDrawing)
-{
-  nsNPAPIPluginInstance* inst = (nsNPAPIPluginInstance*)instance->ndata;
-  NS_ENSURE_TRUE(inst, NS_ERROR_NULL_POINTER);
-  *aDrawing = PR_FALSE; 
-  return NS_OK;
-}
-#endif
-
 nsresult
 PluginPRLibrary::SetBackgroundUnknown(NPP instance)
 {
   nsNPAPIPluginInstance* inst = (nsNPAPIPluginInstance*)instance->ndata;
   NS_ENSURE_TRUE(inst, NS_ERROR_NULL_POINTER);
   NS_ERROR("Unexpected use of async APIs for in-process plugin.");
   return NS_ERROR_NOT_IMPLEMENTED;
 }
--- a/dom/plugins/base/PluginPRLibrary.h
+++ b/dom/plugins/base/PluginPRLibrary.h
@@ -138,19 +138,16 @@ public:
     virtual nsresult NPP_ClearSiteData(const char* site, uint64_t flags,
                                        uint64_t maxAge);
     virtual nsresult NPP_GetSitesWithData(InfallibleTArray<nsCString>& result);
 
     virtual nsresult AsyncSetWindow(NPP instance, NPWindow* window);
     virtual nsresult GetImage(NPP instance, ImageContainer* aContainer, Image** aImage);
     virtual nsresult GetImageSize(NPP instance, nsIntSize* aSize);
     NS_OVERRIDE virtual bool UseAsyncPainting() { return false; }
-#if defined(XP_MACOSX)
-    virtual nsresult IsRemoteDrawingCoreAnimation(NPP instance, PRBool *aDrawing);
-#endif
     NS_OVERRIDE
     virtual nsresult SetBackgroundUnknown(NPP instance);
     NS_OVERRIDE
     virtual nsresult BeginUpdateBackground(NPP instance,
                                            const nsIntRect&, gfxContext** aCtx);
     NS_OVERRIDE
     virtual nsresult EndUpdateBackground(NPP instance,
                                          gfxContext* aCtx, const nsIntRect&);
--- a/dom/plugins/base/nsNPAPIPluginInstance.cpp
+++ b/dom/plugins/base/nsNPAPIPluginInstance.cpp
@@ -724,32 +724,16 @@ nsresult nsNPAPIPluginInstance::GetDrawi
 #ifdef XP_MACOSX
   *aModel = (PRInt32)mDrawingModel;
   return NS_OK;
 #else
   return NS_ERROR_FAILURE;
 #endif
 }
 
-nsresult nsNPAPIPluginInstance::IsRemoteDrawingCoreAnimation(PRBool* aDrawing)
-{
-#ifdef XP_MACOSX
-  if (!mPlugin)
-      return NS_ERROR_FAILURE;
-
-  PluginLibrary* library = mPlugin->GetLibrary();
-  if (!library)
-      return NS_ERROR_FAILURE;
-  
-  return library->IsRemoteDrawingCoreAnimation(&mNPP, aDrawing);
-#else
-  return NS_ERROR_FAILURE;
-#endif
-}
-
 nsresult
 nsNPAPIPluginInstance::GetJSObject(JSContext *cx, JSObject** outObject)
 {
   NPObject *npobj = nsnull;
   nsresult rv = GetValueFromPlugin(NPPVpluginScriptableNPObject, &npobj);
   if (NS_FAILED(rv) || !npobj)
     return NS_ERROR_FAILURE;
 
--- a/dom/plugins/base/nsPluginInstanceOwner.cpp
+++ b/dom/plugins/base/nsPluginInstanceOwner.cpp
@@ -246,16 +246,38 @@ nsPluginInstanceOwner::EndUpdateBackgrou
                                            const nsIntRect& aRect)
 {
   nsIntRect rect = aRect;
   if (mInstance) {
     mInstance->EndUpdateBackground(aContext, &rect);
   }
 }
 
+PRBool
+nsPluginInstanceOwner::UseAsyncRendering()
+{
+#ifdef XP_MACOSX
+  nsRefPtr<ImageContainer> container = mObjectFrame->GetImageContainer();
+#endif
+
+  PRBool useAsyncRendering;
+  return (mInstance &&
+          NS_SUCCEEDED(mInstance->UseAsyncPainting(&useAsyncRendering)) &&
+          useAsyncRendering &&
+#ifdef XP_MACOSX
+          mObjectFrame && mObjectFrame->GetImageContainer().get() &&
+          mObjectFrame->GetImageContainer().get()->GetBackendType() == 
+                  LayerManager::LAYERS_OPENGL
+#else
+          (!mPluginWindow ||
+           mPluginWindow->type == NPWindowTypeDrawable)
+#endif
+          );
+}
+
 nsIntSize
 nsPluginInstanceOwner::GetCurrentImageSize()
 {
   nsIntSize size(0,0);
   if (mInstance) {
     mInstance->GetImageSize(&size);
   }
   return size;
@@ -1333,28 +1355,16 @@ NPDrawingModel nsPluginInstanceOwner::Ge
 
   if (!mInstance)
     return drawingModel;
 
   mInstance->GetDrawingModel((PRInt32*)&drawingModel);
   return drawingModel;
 }
 
-PRBool nsPluginInstanceOwner::IsRemoteDrawingCoreAnimation()
-{
-  if (!mInstance)
-    return PR_FALSE;
-
-  PRBool coreAnimation;
-  if (!NS_SUCCEEDED(mInstance->IsRemoteDrawingCoreAnimation(&coreAnimation)))
-    return PR_FALSE;
-
-  return coreAnimation;
-}
-
 NPEventModel nsPluginInstanceOwner::GetEventModel()
 {
   return mEventModel;
 }
 
 #define DEFAULT_REFRESH_RATE 20 // 50 FPS
 
 nsCOMPtr<nsITimer>                *nsPluginInstanceOwner::sCATimer = NULL;
@@ -3212,31 +3222,31 @@ void* nsPluginInstanceOwner::FixUpPlugin
 
   // if the clip rect changed, call SetWindow()
   // (RealPlayer needs this to draw correctly)
   if (mPluginWindow->clipRect.left    != oldClipRect.left   ||
       mPluginWindow->clipRect.top     != oldClipRect.top    ||
       mPluginWindow->clipRect.right   != oldClipRect.right  ||
       mPluginWindow->clipRect.bottom  != oldClipRect.bottom)
   {
-    mInstance->SetWindow(mPluginWindow);
+    CallSetWindow();
     mPluginPortChanged = PR_FALSE;
 #ifdef MAC_CARBON_PLUGINS
     // if the clipRect is of size 0, make the null timer fire less often
     CancelTimer();
     if (mPluginWindow->clipRect.left == mPluginWindow->clipRect.right ||
         mPluginWindow->clipRect.top == mPluginWindow->clipRect.bottom) {
       StartTimer(PR_FALSE);
     }
     else {
       StartTimer(PR_TRUE);
     }
 #endif
   } else if (mPluginPortChanged) {
-    mInstance->SetWindow(mPluginWindow);
+    CallSetWindow();
     mPluginPortChanged = PR_FALSE;
   }
 
   // After the first NPP_SetWindow call we need to send an initial
   // top-level window focus event.
   if (eventModel == NPEventModelCocoa && !mSentInitialTopLevelWindowEvent) {
     // Set this before calling ProcessEvent to avoid endless recursion.
     mSentInitialTopLevelWindowEvent = PR_TRUE;
@@ -3268,17 +3278,21 @@ nsPluginInstanceOwner::HidePluginWindow(
 {
   if (!mPluginWindow || !mInstance) {
     return;
   }
 
   mPluginWindow->clipRect.bottom = mPluginWindow->clipRect.top;
   mPluginWindow->clipRect.right  = mPluginWindow->clipRect.left;
   mWidgetVisible = PR_FALSE;
-  mInstance->SetWindow(mPluginWindow);
+  if (mAsyncHidePluginWindow) {
+    mInstance->AsyncSetWindow(mPluginWindow);
+  } else {
+    mInstance->SetWindow(mPluginWindow);
+  }
 }
 
 #else // XP_MACOSX
 
 void nsPluginInstanceOwner::UpdateWindowPositionAndClipRect(PRBool aSetWindow)
 {
   if (!mPluginWindow)
     return;
@@ -3317,37 +3331,39 @@ void nsPluginInstanceOwner::UpdateWindow
       mPluginWindow->clipRect.top    != oldWindow.clipRect.top    ||
       mPluginWindow->clipRect.right  != oldWindow.clipRect.right  ||
       mPluginWindow->clipRect.bottom != oldWindow.clipRect.bottom) {
     CallSetWindow();
   }
 }
 
 void
-nsPluginInstanceOwner::CallSetWindow()
-{
-  if (!mInstance)
-    return;
-
-  if (UseAsyncRendering()) {
-    mInstance->AsyncSetWindow(mPluginWindow);
-  } else {
-    mInstance->SetWindow(mPluginWindow);
-  }
-}
-
-void
 nsPluginInstanceOwner::UpdateWindowVisibility(PRBool aVisible)
 {
   mPluginWindowVisible = aVisible;
   UpdateWindowPositionAndClipRect(PR_TRUE);
 }
 
 #endif // XP_MACOSX
 
+void
+nsPluginInstanceOwner::CallSetWindow()
+{
+  if (!mInstance)
+    return;
+
+  if (UseAsyncRendering()) {
+    mAsyncHidePluginWindow = true;
+    mInstance->AsyncSetWindow(mPluginWindow);
+  } else {
+    mAsyncHidePluginWindow = false;
+    mInstance->SetWindow(mPluginWindow);
+  }
+}
+
 // Little helper function to resolve relative URL in
 // |value| for certain inputs of |name|
 void nsPluginInstanceOwner::FixUpURLS(const nsString &name, nsAString &value)
 {
   if (name.LowerCaseEqualsLiteral("pluginurl") ||
       name.LowerCaseEqualsLiteral("pluginspage")) {        
     nsCOMPtr<nsIURI> baseURI = mContent->GetBaseURI();
     nsAutoString newURL;
--- a/dom/plugins/base/nsPluginInstanceOwner.h
+++ b/dom/plugins/base/nsPluginInstanceOwner.h
@@ -174,17 +174,16 @@ public:
   void SetPluginHost(nsIPluginHost* aHost);
   
   nsEventStatus ProcessEvent(const nsGUIEvent & anEvent);
   
 #ifdef XP_MACOSX
   enum { ePluginPaintEnable, ePluginPaintDisable };
   
   NPDrawingModel GetDrawingModel();
-  PRBool IsRemoteDrawingCoreAnimation();
   NPEventModel GetEventModel();
   static void CARefresh(nsITimer *aTimer, void *aClosure);
   static void AddToCARefreshTimer(nsPluginInstanceOwner *aPluginInstance);
   static void RemoveFromCARefreshTimer(nsPluginInstanceOwner *aPluginInstance);
   void SetupCARefresh();
   void* FixUpPluginWindow(PRInt32 inPaintState);
   void HidePluginWindow();
   // Set a flag that (if true) indicates the plugin port info has changed and
@@ -202,19 +201,19 @@ public:
   // nsObjectFrame::PaintPlugin().  We need to know this in
   // FixUpPluginWindow() (i.e. we need to know when FixUpPluginWindow() has
   // been called from nsObjectFrame::PaintPlugin() when we're using the
   // CoreGraphics drawing model).
   void BeginCGPaint();
   void EndCGPaint();
 #else // XP_MACOSX
   void UpdateWindowPositionAndClipRect(PRBool aSetWindow);
-  void CallSetWindow();
   void UpdateWindowVisibility(PRBool aVisible);
 #endif // XP_MACOSX
+  void CallSetWindow();
   
   void SetOwner(nsObjectFrame *aOwner)
   {
     mObjectFrame = aOwner;
   }
   nsObjectFrame* GetOwner() {
     return mObjectFrame;
   }
@@ -290,25 +289,17 @@ public:
   
   // Methods to update the background image we send to async plugins.
   // The eventual target of these operations is PluginInstanceParent,
   // but it takes several hops to get there.
   void SetBackgroundUnknown();
   already_AddRefed<gfxContext> BeginUpdateBackground(const nsIntRect& aRect);
   void EndUpdateBackground(gfxContext* aContext, const nsIntRect& aRect);
   
-  PRBool UseAsyncRendering()
-  {
-    PRBool useAsyncRendering;
-    return (mInstance &&
-            NS_SUCCEEDED(mInstance->UseAsyncPainting(&useAsyncRendering)) &&
-            useAsyncRendering &&
-            (!mPluginWindow ||
-             mPluginWindow->type == NPWindowTypeDrawable));
-  }
+  PRBool UseAsyncRendering();
   
 private:
   
   // return FALSE if LayerSurface dirty (newly created and don't have valid plugin content yet)
   PRBool IsUpToDate()
   {
     nsIntSize size;
     return NS_SUCCEEDED(mInstance->GetImageSize(&size)) &&
@@ -334,16 +325,19 @@ private:
   PRInt32                                   mInCGPaintLevel;
   nsIOSurface                              *mIOSurface;
   nsCARenderer                              mCARenderer;
   CGColorSpaceRef                           mColorProfile;
   static nsCOMPtr<nsITimer>                *sCATimer;
   static nsTArray<nsPluginInstanceOwner*>  *sCARefreshListeners;
   PRBool                                    mSentInitialTopLevelWindowEvent;
 #endif
+  // We need to know if async hide window is required since we
+  // can not check UseAsyncRendering when executing StopPlugin
+  PRBool                                    mAsyncHidePluginWindow;
   
   // Initially, the event loop nesting level we were created on, it's updated
   // if we detect the appshell is on a lower level as long as we're not stopped.
   // We delay DoStopPlugin() until the appshell reaches this level or lower.
   PRUint32                    mLastEventloopNestingLevel;
   PRPackedBool                mContentFocused;
   PRPackedBool                mWidgetVisible;    // used on Mac to store our widget's visible state
 #ifdef XP_MACOSX
--- a/dom/plugins/ipc/PPluginInstance.ipdl
+++ b/dom/plugins/ipc/PPluginInstance.ipdl
@@ -64,20 +64,25 @@ namespace mozilla {
 namespace plugins {
 
 struct SurfaceDescriptorX11 {
   int XID;
   int xrenderPictID;
   gfxIntSize size;
 };
 
+struct IOSurfaceDescriptor {
+  uint32_t surfaceId;
+};
+
 union SurfaceDescriptor {
   Shmem;
   SurfaceDescriptorX11;
   PPluginSurface; // used on Windows
+  IOSurfaceDescriptor; // used on OSX 10.5+
   // Descriptor can be null here in case
   // 1) of first Show call (prevSurface is null)
   // 2) when child is going to destroy
   //    and it just want to grab prevSurface
   //     back without giving new surface
   null_t;
 };
 
--- a/dom/plugins/ipc/PluginInstanceChild.cpp
+++ b/dom/plugins/ipc/PluginInstanceChild.cpp
@@ -100,16 +100,17 @@ using mozilla::gfx::SharedDIB;
 // from Chromium's web plugin delegate src. See 'flash msg throttling
 // helpers' section for details.
 const int kFlashWMUSERMessageThrottleDelayMs = 5;
 
 static const TCHAR kPluginIgnoreSubclassProperty[] = TEXT("PluginIgnoreSubclassProperty");
 
 #elif defined(XP_MACOSX)
 #include <ApplicationServices/ApplicationServices.h>
+#include "PluginUtilsOSX.h"
 #endif // defined(XP_MACOSX)
 
 template<>
 struct RunnableMethodTraits<PluginInstanceChild>
 {
     static void RetainCallee(PluginInstanceChild* obj) { }
     static void ReleaseCallee(PluginInstanceChild* obj) { }
 };
@@ -130,16 +131,17 @@ PluginInstanceChild::PluginInstanceChild
     , mAsyncCallMutex("PluginInstanceChild::mAsyncCallMutex")
 #if defined(OS_MACOSX)
 #if defined(__i386__)
     , mEventModel(NPEventModelCarbon)
 #endif
     , mShColorSpace(nsnull)
     , mShContext(nsnull)
     , mDrawingModel(NPDrawingModelCoreGraphics)
+    , mCGLayer(nsnull)
     , mCurrentEvent(nsnull)
 #endif
     , mLayersRendering(false)
 #ifdef XP_WIN
     , mCurrentSurfaceActor(NULL)
     , mBackSurfaceActor(NULL)
 #endif
     , mAccumulatedInvalidRect(0,0,0,0)
@@ -178,16 +180,19 @@ PluginInstanceChild::~PluginInstanceChil
 #endif
 #if defined(OS_MACOSX)
     if (mShColorSpace) {
         ::CGColorSpaceRelease(mShColorSpace);
     }
     if (mShContext) {
         ::CGContextRelease(mShContext);
     }
+    if (mCGLayer) {
+        mozilla::plugins::PluginUtilsOSX::ReleaseCGLayer(mCGLayer);
+    }
 #endif
 }
 
 int
 PluginInstanceChild::GetQuirks()
 {
     return PluginModuleChild::current()->GetQuirks();
 }
@@ -472,29 +477,35 @@ PluginInstanceChild::NPN_SetValue(NPPVar
     case NPPVpluginDrawingModel: {
         NPError rv;
         int drawingModel = (int16) (intptr_t) aValue;
 
         if (!CallNPN_SetValue_NPPVpluginDrawingModel(drawingModel, &rv))
             return NPERR_GENERIC_ERROR;
         mDrawingModel = drawingModel;
 
+        PLUGIN_LOG_DEBUG(("  Plugin requested drawing model id  #%i\n",
+            mDrawingModel));
+
         return rv;
     }
 
     case NPPVpluginEventModel: {
         NPError rv;
         int eventModel = (int16) (intptr_t) aValue;
 
         if (!CallNPN_SetValue_NPPVpluginEventModel(eventModel, &rv))
             return NPERR_GENERIC_ERROR;
 #if defined(__i386__)
         mEventModel = static_cast<NPEventModel>(eventModel);
 #endif
 
+        PLUGIN_LOG_DEBUG(("  Plugin requested event model id # %i\n",
+            eventModel));
+
         return rv;
     }
 #endif
 
     default:
         PR_LOG(gPluginLog, PR_LOG_WARNING,
                ("In PluginInstanceChild::NPN_SetValue: Unhandled NPPVariable %i (%s)",
                 (int) aVar, NPPVariableToString(aVar)));
@@ -773,16 +784,42 @@ PluginInstanceChild::AnswerNPP_HandleEve
 {
     NS_RUNTIMEABORT("not reached.");
     *rtnmem = mem;
     return true;
 }
 #endif
 
 #ifdef XP_MACOSX
+
+void CallCGDraw(CGContextRef ref, void* aPluginInstance, nsIntRect aUpdateRect) {
+  PluginInstanceChild* pluginInstance = (PluginInstanceChild*)aPluginInstance;
+
+  pluginInstance->CGDraw(ref, aUpdateRect);
+}
+
+bool
+PluginInstanceChild::CGDraw(CGContextRef ref, nsIntRect aUpdateRect) {
+
+  NPCocoaEvent drawEvent;
+  drawEvent.type = NPCocoaEventDrawRect;
+  drawEvent.version = 0;
+  drawEvent.data.draw.x = aUpdateRect.x;
+  drawEvent.data.draw.y = aUpdateRect.y;
+  drawEvent.data.draw.width = aUpdateRect.width;
+  drawEvent.data.draw.height = aUpdateRect.height;
+  drawEvent.data.draw.context = ref;
+
+  NPRemoteEvent remoteDrawEvent = {drawEvent};
+
+  int16_t handled;
+  AnswerNPP_HandleEvent(remoteDrawEvent, &handled);
+  return handled == true;
+}
+
 bool
 PluginInstanceChild::AnswerNPP_HandleEvent_IOSurface(const NPRemoteEvent& event,
                                                      const uint32_t &surfaceid,
                                                      int16_t* handled)
 {
     PLUGIN_LOG_DEBUG_FUNCTION;
     AssertPluginThread();
 
@@ -798,23 +835,26 @@ PluginInstanceChild::AnswerNPP_HandleEve
 
     if (evcopy.type == NPCocoaEventDrawRect) {
         mCARenderer.AttachIOSurface(surf);
         if (!mCARenderer.isInit()) {
             void *caLayer = nsnull;
             NPError result = mPluginIface->getvalue(GetNPP(), 
                                      NPPVpluginCoreAnimationLayer,
                                      &caLayer);
+            
             if (result != NPERR_NO_ERROR || !caLayer) {
                 PLUGIN_LOG_DEBUG(("Plugin requested CoreAnimation but did not "
                                   "provide CALayer."));
                 *handled = false;
                 return false;
             }
+
             mCARenderer.SetupRenderer(caLayer, mWindow.width, mWindow.height);
+
             // Flash needs to have the window set again after this step
             if (mPluginIface->setwindow)
                 (void) mPluginIface->setwindow(&mData, &mWindow);
         }
     } else {
         PLUGIN_LOG_DEBUG(("Invalid event type for "
                           "AnswerNNP_HandleEvent_IOSurface."));
         *handled = false;
@@ -2273,22 +2313,27 @@ PluginInstanceChild::DoAsyncSetWindow(co
     if (aIsAsync) {
         if (!mCurrentAsyncSetWindowTask) {
             return;
         }
         mCurrentAsyncSetWindowTask = nsnull;
     }
 
     mWindow.window = NULL;
+#ifdef XP_MACOSX
+    if (mWindow.width != aWindow.width || mWindow.height != aWindow.height) 
+        mAccumulatedInvalidRect = nsIntRect(0, 0, aWindow.width, aWindow.height);
+#else
     if (mWindow.width != aWindow.width || mWindow.height != aWindow.height ||
         mWindow.clipRect.top != aWindow.clipRect.top ||
         mWindow.clipRect.left != aWindow.clipRect.left ||
         mWindow.clipRect.bottom != aWindow.clipRect.bottom ||
         mWindow.clipRect.right != aWindow.clipRect.right)
         mAccumulatedInvalidRect = nsIntRect(0, 0, aWindow.width, aWindow.height);
+#endif
 
     mWindow.x = aWindow.x;
     mWindow.y = aWindow.y;
     mWindow.width = aWindow.width;
     mWindow.height = aWindow.height;
     mWindow.clipRect = aWindow.clipRect;
     mWindow.type = aWindow.type;
 
@@ -2467,16 +2512,17 @@ PluginInstanceChild::MaybeCreatePlatform
 #endif
 
     return true;
 }
 
 bool
 PluginInstanceChild::EnsureCurrentBuffer(void)
 {
+#ifndef XP_MACOSX
     nsIntRect toInvalidate(0, 0, 0, 0);
     gfxIntSize winSize = gfxIntSize(mWindow.width, mWindow.height);
 
     if (mBackground && mBackground->GetSize() != winSize) {
         // It would be nice to keep the old background here, but doing
         // so can lead to cases in which we permanently keep the old
         // background size.
         mBackground = nsnull;
@@ -2498,30 +2544,89 @@ PluginInstanceChild::EnsureCurrentBuffer
             toInvalidate.UnionRect(toInvalidate,
                                    nsIntRect(0, 0, winSize.width, winSize.height));
         }
     }
 
     mAccumulatedInvalidRect.UnionRect(mAccumulatedInvalidRect, toInvalidate);
 
     if (mCurrentSurface) {
-       return true;
+        return true;
     }
 
     if (!CreateOptSurface()) {
         NS_ERROR("Cannot create optimized surface");
         return false;
     }
 
     if (!MaybeCreatePlatformHelperSurface()) {
         NS_ERROR("Cannot create helper surface");
         return false;
     }
 
     return true;
+#else // XP_MACOSX
+    if (mCurrentIOSurface && 
+        (mCurrentIOSurface->GetWidth() != mWindow.width ||
+         mCurrentIOSurface->GetHeight() != mWindow.height) ) {
+        mCurrentIOSurface = nsnull;
+    }
+
+    if (!mCARenderer.isInit() || !mCurrentIOSurface) {
+        if (!mCurrentIOSurface) {
+            mCurrentIOSurface = nsIOSurface::CreateIOSurface(mWindow.width, mWindow.height);
+
+            nsIntRect toInvalidate(0, 0, mWindow.width, mWindow.height);
+            mAccumulatedInvalidRect.UnionRect(mAccumulatedInvalidRect, toInvalidate);
+        }
+
+        if (!mCurrentIOSurface) {
+            NS_WARNING("Failed to allocate IOSurface");
+            return false;
+        }
+
+        nsIOSurface *rendererSurface = nsIOSurface::LookupSurface(mCurrentIOSurface->GetIOSurfaceID()); 
+        if (!rendererSurface) {
+            NS_WARNING("Failed to lookup IOSurface");
+            return false;
+        }
+        mCARenderer.AttachIOSurface(rendererSurface);
+
+        void *caLayer = nsnull;
+        if (mDrawingModel == NPDrawingModelCoreGraphics) {
+            if (mCGLayer) {
+                mozilla::plugins::PluginUtilsOSX::ReleaseCGLayer(mCGLayer);
+                mCGLayer = nsnull;
+            }
+
+            caLayer = mozilla::plugins::PluginUtilsOSX::GetCGLayer(CallCGDraw, this);
+            if (!caLayer) {
+                return false;
+            }
+
+            mCGLayer = caLayer;
+        } else {
+            NPError result = mPluginIface->getvalue(GetNPP(),
+                                     NPPVpluginCoreAnimationLayer,
+                                     &caLayer);
+            if (result != NPERR_NO_ERROR || !caLayer) {
+                PLUGIN_LOG_DEBUG(("Plugin requested CoreAnimation but did not "
+                                  "provide CALayer."));
+                return false;
+            }
+        }
+
+        mCARenderer.SetupRenderer(caLayer, mWindow.width, mWindow.height);
+        // Flash needs to have the window set again after this step
+        if (mPluginIface->setwindow)
+            (void) mPluginIface->setwindow(&mData, &mWindow);
+    }
+
+    return true;
+#endif
 }
 
 void
 PluginInstanceChild::UpdateWindowAttributes(bool aForceSetWindow)
 {
     nsRefPtr<gfxASurface> curSurface = mHelperSurface ? mHelperSurface : mCurrentSurface;
     bool needWindowUpdate = aForceSetWindow;
 #ifdef MOZ_X11
@@ -2888,16 +2993,67 @@ PluginInstanceChild::ShowPluginFrame()
     // paint.
     if (!mLayersRendering || mPendingPluginCall) {
         return false;
     }
 
     AutoRestore<bool> pending(mPendingPluginCall);
     mPendingPluginCall = true;
 
+#ifdef XP_MACOSX
+    // We can't use the thebes code with CoreAnimation so we will
+    // take a different code path.
+    if (mDrawingModel == NPDrawingModelCoreAnimation ||
+        mDrawingModel == NPDrawingModelInvalidatingCoreAnimation ||
+        mDrawingModel == NPDrawingModelCoreGraphics) {
+
+        if (!EnsureCurrentBuffer()) {
+          return false;
+        }
+
+        // Clear accRect here to be able to pass
+        // test_invalidate_during_plugin_paint  test
+        nsIntRect rect = mAccumulatedInvalidRect;
+        mAccumulatedInvalidRect.SetEmpty();
+
+        // Fix up old invalidations that might have been made when our
+        // surface was a different size
+        rect.IntersectRect(rect,
+                         nsIntRect(0, 0, mCurrentIOSurface->GetWidth(), mCurrentIOSurface->GetHeight()));
+      
+        if (!mCARenderer.isInit()) {
+            NS_ERROR("CARenderer not initialized");
+            return false;
+        }
+
+        if (mDrawingModel == NPDrawingModelCoreGraphics) {
+            mozilla::plugins::PluginUtilsOSX::Repaint(mCGLayer, rect);
+        }
+
+        mCARenderer.Render(mWindow.width, mWindow.height, nsnull);
+
+        NPRect r = { (uint16_t)rect.y, (uint16_t)rect.x,
+                     (uint16_t)rect.YMost(), (uint16_t)rect.XMost() };
+        SurfaceDescriptor currSurf;
+        currSurf = IOSurfaceDescriptor(mCurrentIOSurface->GetIOSurfaceID());
+
+        // Unused
+        SurfaceDescriptor returnSurf;
+
+        if (!SendShow(r, currSurf, &returnSurf)) {
+            return false;
+        }
+
+        return true;
+    } else {
+        NS_ERROR("Unsupported drawing model for async layer rendering");
+        return false;
+    }
+#endif
+
     bool temporarilyMakeVisible = !IsVisible() && !mHasPainted;
     if (temporarilyMakeVisible && mWindow.width && mWindow.height) {
         mWindow.clipRect.right = mWindow.width;
         mWindow.clipRect.bottom = mWindow.height;
     } else if (!IsVisible()) {
         // If we're not visible, don't bother painting a <0,0,0,0>
         // rect.  If we're eventually made visible, the visibility
         // change will invalidate our window.
@@ -3140,16 +3296,17 @@ PluginInstanceChild::InvalidateRect(NPRe
                     aInvalidRect->bottom - aInvalidRect->top);
 
         mAccumulatedInvalidRect.UnionRect(r, mAccumulatedInvalidRect);
         // If we are able to paint and invalidate sent, then reset
         // accumulated rectangle
         AsyncShowPluginFrame();
         return;
     }
+
     // If we were going to use layers rendering but it's not set up
     // yet, and the plugin happens to call this first, we'll forward
     // the invalidation to the browser.  It's unclear whether
     // non-layers plugins need this rect forwarded when their window
     // width or height is 0, which it would be for layers plugins
     // before their first SetWindow().
     SendNPN_InvalidateRect(*aInvalidRect);
 }
@@ -3379,16 +3536,28 @@ PluginInstanceChild::ClearAllSurfaces()
         PPluginSurfaceChild::Send__delete__(mCurrentSurfaceActor);
         mCurrentSurfaceActor = NULL;
     }
     if (mBackSurfaceActor) {
         PPluginSurfaceChild::Send__delete__(mBackSurfaceActor);
         mBackSurfaceActor = NULL;
     }
 #endif
+
+#ifdef XP_MACOSX
+    if (mCurrentIOSurface) {
+        // Get last surface back, and drop it
+        SurfaceDescriptor temp = null_t();
+        NPRect r = { 0, 0, 1, 1 };
+        SendShow(r, temp, &temp);
+
+    }
+
+    mCurrentIOSurface = nsnull;
+#endif
 }
 
 bool
 PluginInstanceChild::AnswerNPP_Destroy(NPError* aResult)
 {
     PLUGIN_LOG_DEBUG_METHOD;
     AssertPluginThread();
 
--- a/dom/plugins/ipc/PluginInstanceChild.h
+++ b/dom/plugins/ipc/PluginInstanceChild.h
@@ -409,21 +409,24 @@ private:
 private:
 #if defined(__i386__)
     NPEventModel          mEventModel;
 #endif
     CGColorSpaceRef       mShColorSpace;
     CGContextRef          mShContext;
     int16_t               mDrawingModel;
     nsCARenderer          mCARenderer;
+    void                 *mCGLayer;
 
 public:
     const NPCocoaEvent* getCurrentEvent() {
         return mCurrentEvent;
     }
+  
+    bool CGDraw(CGContextRef ref, nsIntRect aUpdateRect);
 
 #if defined(__i386__)
     NPEventModel EventModel() { return mEventModel; }
 #endif
 
 private:
     const NPCocoaEvent   *mCurrentEvent;
 #endif
@@ -506,16 +509,22 @@ private:
 
     // Current surface available for rendering
     nsRefPtr<gfxASurface> mCurrentSurface;
 
     // Back surface, just keeping reference to
     // surface which is on ParentProcess side
     nsRefPtr<gfxASurface> mBackSurface;
 
+#ifdef XP_MACOSX
+    // Current IOSurface available for rendering
+    // We can't use thebes gfxASurface like other platforms.
+    nsAutoPtr<nsIOSurface> mCurrentIOSurface; 
+#endif
+
     // (Not to be confused with mBackSurface).  This is a recent copy
     // of the opaque pixels under our object frame, if
     // |mIsTransparent|.  We ask the plugin render directly onto a
     // copy of the background pixels if available, and fall back on
     // alpha recovery otherwise.
     nsRefPtr<gfxASurface> mBackground;
 
 #ifdef XP_WIN
--- a/dom/plugins/ipc/PluginInstanceParent.cpp
+++ b/dom/plugins/ipc/PluginInstanceParent.cpp
@@ -98,17 +98,16 @@ PluginInstanceParent::PluginInstancePare
     , mNestedEventState(false)
 #endif // defined(XP_WIN)
     , mQuirks(0)
 #if defined(XP_MACOSX)
     , mShWidth(0)
     , mShHeight(0)
     , mShColorSpace(nsnull)
     , mDrawingModel(NPDrawingModelCoreGraphics)
-    , mIOSurface(nsnull)
 #endif
 {
     InitQuirksModes(aMimeType);
 }
 
 void
 PluginInstanceParent::InitQuirksModes(const nsCString& aMimeType)
 {
@@ -132,17 +131,16 @@ PluginInstanceParent::~PluginInstancePar
         "Subclass was not reset correctly before the dtor was reached!");
 #endif
 #if defined(OS_MACOSX)
     if (mShWidth != 0 && mShHeight != 0) {
         DeallocShmem(mShSurface);
     }
     if (mShColorSpace)
         ::CGColorSpaceRelease(mShColorSpace);
-    delete mIOSurface;
     if (mDrawingModel == NPDrawingModelCoreAnimation) {
         mParent->RemoveFromRefreshTimer(this);
     }
 #endif
 }
 
 bool
 PluginInstanceParent::Init()
@@ -512,16 +510,39 @@ PluginInstanceParent::RecvShow(const NPR
     nsRefPtr<gfxASurface> surface;
     if (newSurface.type() == SurfaceDescriptor::TShmem) {
         if (!newSurface.get_Shmem().IsReadable()) {
             NS_WARNING("back surface not readable");
             return false;
         }
         surface = gfxSharedImageSurface::Open(newSurface.get_Shmem());
     }
+#ifdef XP_MACOSX
+    else if (newSurface.type() == SurfaceDescriptor::TIOSurfaceDescriptor) {
+        IOSurfaceDescriptor iodesc = newSurface.get_IOSurfaceDescriptor();
+    
+        nsIOSurface *newIOSurface = nsIOSurface::LookupSurface(iodesc.surfaceId());
+
+        if (!newIOSurface) {
+            NS_WARNING("Got bad IOSurfaceDescriptor in RecvShow");
+            return false;
+        }
+      
+        mIOSurface = newIOSurface;
+
+        RecvNPN_InvalidateRect(updatedRect);
+
+        *prevSurface = null_t();
+
+        PLUGIN_LOG_DEBUG(("   (RecvShow invalidated for surface %p)",
+                          mFrontSurface.get()));
+
+        return true;
+    }
+#endif
 #ifdef MOZ_X11
     else if (newSurface.type() == SurfaceDescriptor::TSurfaceDescriptorX11) {
         SurfaceDescriptorX11 xdesc = newSurface.get_SurfaceDescriptorX11();
         XRenderPictFormat pf;
         pf.id = xdesc.xrenderPictID();
         XRenderPictFormat *incFormat =
             XRenderFindFormat(DefaultXDisplay(), PictFormatID, &pf, 0);
         surface =
@@ -598,18 +619,22 @@ PluginInstanceParent::GetImage(ImageCont
     if (!mFrontSurface && !mIOSurface)
 #else
     if (!mFrontSurface)
 #endif
         return NS_ERROR_NOT_AVAILABLE;
 
     Image::Format format = Image::CAIRO_SURFACE;
 #ifdef XP_MACOSX
-    if (mIOSurface)
+    if (mIOSurface) {
         format = Image::MAC_IO_SURFACE;
+        if (!aContainer->Manager()) {
+            return NS_ERROR_FAILURE;
+        }
+    }
 #endif
 
     nsRefPtr<Image> image;
     image = aContainer->CreateImage(&format, 1);
     if (!image) {
         return NS_ERROR_FAILURE;
     }
 
@@ -650,26 +675,16 @@ PluginInstanceParent::GetImageSize(nsInt
         *aSize = nsIntSize(mIOSurface->GetWidth(), mIOSurface->GetHeight());
         return NS_OK;
     }
 #endif
 
     return NS_ERROR_NOT_AVAILABLE;
 }
 
-#ifdef XP_MACOSX
-nsresult
-PluginInstanceParent::IsRemoteDrawingCoreAnimation(PRBool *aDrawing)
-{
-    *aDrawing = (NPDrawingModelCoreAnimation == (NPDrawingModel)mDrawingModel ||
-                 NPDrawingModelInvalidatingCoreAnimation == (NPDrawingModel)mDrawingModel);
-    return NS_OK;
-}
-#endif
-
 nsresult
 PluginInstanceParent::SetBackgroundUnknown()
 {
     PLUGIN_LOG_DEBUG(("[InstanceParent][%p] SetBackgroundUnknown", this));
 
     if (mBackground) {
         DestroyBackground();
         NS_ABORT_IF_FALSE(!mBackground, "Background not destroyed");
@@ -860,17 +875,16 @@ PluginInstanceParent::NPP_SetWindow(cons
     window.clipRect = aWindow->clipRect; // MacOS specific
     window.type = aWindow->type;
 #endif
 
 #if defined(XP_MACOSX)
     if (mShWidth != window.width || mShHeight != window.height) {
         if (mDrawingModel == NPDrawingModelCoreAnimation || 
             mDrawingModel == NPDrawingModelInvalidatingCoreAnimation) {
-            delete mIOSurface;
             mIOSurface = nsIOSurface::CreateIOSurface(window.width, window.height);
         } else if (mShWidth * mShHeight != window.width * window.height) {
             if (mShWidth != 0 && mShHeight != 0) {
                 DeallocShmem(mShSurface);
                 mShWidth = 0;
                 mShHeight = 0;
             }
 
--- a/dom/plugins/ipc/PluginInstanceParent.h
+++ b/dom/plugins/ipc/PluginInstanceParent.h
@@ -277,19 +277,16 @@ public:
 
 #if defined(OS_MACOSX)
     void Invalidate();
 #endif // definied(OS_MACOSX)
 
     nsresult AsyncSetWindow(NPWindow* window);
     nsresult GetImage(mozilla::layers::ImageContainer* aContainer, mozilla::layers::Image** aImage);
     nsresult GetImageSize(nsIntSize* aSize);
-#ifdef XP_MACOSX
-    nsresult IsRemoteDrawingCoreAnimation(PRBool *aDrawing);
-#endif
     nsresult SetBackgroundUnknown();
     nsresult BeginUpdateBackground(const nsIntRect& aRect,
                                    gfxContext** aCtx);
     nsresult EndUpdateBackground(gfxContext* aCtx,
                                  const nsIntRect& aRect);
 
 private:
     // Create an appropriate platform surface for a background of size
@@ -347,22 +344,22 @@ private:
     nsIntRect          mPluginPort;
     nsIntRect          mSharedSize;
     HWND               mPluginHWND;
     WNDPROC            mPluginWndProc;
     bool               mNestedEventState;
 #endif // defined(XP_WIN)
 #if defined(OS_MACOSX)
 private:
-    Shmem              mShSurface; 
-    size_t             mShWidth;
-    size_t             mShHeight;
-    CGColorSpaceRef    mShColorSpace;
-    int16_t            mDrawingModel;
-    nsIOSurface       *mIOSurface;
+    Shmem                  mShSurface; 
+    size_t                 mShWidth;
+    size_t                 mShHeight;
+    CGColorSpaceRef        mShColorSpace;
+    int16_t                mDrawingModel;
+    nsAutoPtr<nsIOSurface> mIOSurface;
 #endif // definied(OS_MACOSX)
 
     // ObjectFrame layer wrapper
     nsRefPtr<gfxASurface>    mFrontSurface;
     // For windowless+transparent instances, this surface contains a
     // "pretty recent" copy of the pixels under its <object> frame.
     // On the plugin side, we use this surface to avoid doing alpha
     // recovery when possible.  This surface is created and owned by
--- a/dom/plugins/ipc/PluginInterposeOSX.h
+++ b/dom/plugins/ipc/PluginInterposeOSX.h
@@ -27,16 +27,18 @@
 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
 #ifndef DOM_PLUGINS_IPC_PLUGININTERPOSEOSX_H
 #define DOM_PLUGINS_IPC_PLUGININTERPOSEOSX_H
 
 #include "base/basictypes.h"
 #include "nsPoint.h"
+#include "npapi.h"
+#include "nsRect.h"
 
 // Make this includable from non-Objective-C code.
 #ifndef __OBJC__
 class NSCursor;
 #else
 #import <Cocoa/Cocoa.h>
 #endif
 
--- a/dom/plugins/ipc/PluginLibrary.h
+++ b/dom/plugins/ipc/PluginLibrary.h
@@ -97,19 +97,16 @@ public:
   virtual nsresult NPP_ClearSiteData(const char* site, uint64_t flags,
                                      uint64_t maxAge) = 0;
   virtual nsresult NPP_GetSitesWithData(InfallibleTArray<nsCString>& aResult) = 0;
 
   virtual nsresult AsyncSetWindow(NPP instance, NPWindow* window) = 0;
   virtual nsresult GetImage(NPP instance, ImageContainer* aContainer, Image** aImage) = 0;
   virtual nsresult GetImageSize(NPP instance, nsIntSize* aSize) = 0;
   virtual bool UseAsyncPainting() = 0;
-#if defined(XP_MACOSX)
-  virtual nsresult IsRemoteDrawingCoreAnimation(NPP instance, PRBool *aDrawing) = 0;
-#endif
   /**
    * The next three methods are the third leg in the trip to
    * PluginInstanceParent.  They approximately follow the ReadbackSink
    * API.
    */
   virtual nsresult SetBackgroundUnknown(NPP instance) = 0;
   virtual nsresult BeginUpdateBackground(NPP instance,
                                          const nsIntRect&, gfxContext**) = 0;
--- a/dom/plugins/ipc/PluginModuleParent.cpp
+++ b/dom/plugins/ipc/PluginModuleParent.cpp
@@ -34,18 +34,18 @@
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifdef MOZ_WIDGET_GTK2
 #include <glib.h>
 #elif XP_MACOSX
+#include "PluginInterposeOSX.h"
 #include "PluginUtilsOSX.h"
-#include "PluginInterposeOSX.h"
 #include "nsIPrefService.h"
 #include "nsIPrefBranch.h"
 #endif
 #ifdef MOZ_WIDGET_QT
 #include <QtCore/QCoreApplication>
 #include <QtCore/QEventLoop>
 #endif
 
@@ -919,28 +919,16 @@ PluginModuleParent::NPP_GetSitesWithData
         return NS_ERROR_NOT_AVAILABLE;
 
     if (!CallNPP_GetSitesWithData(&result))
         return NS_ERROR_FAILURE;
 
     return NS_OK;
 }
 
-#if defined(XP_MACOSX)
-nsresult
-PluginModuleParent::IsRemoteDrawingCoreAnimation(NPP instance, PRBool *aDrawing)
-{
-    PluginInstanceParent* i = InstCast(instance);
-    if (!i)
-        return NS_ERROR_FAILURE;
-
-    return i->IsRemoteDrawingCoreAnimation(aDrawing);
-}
-#endif
-
 bool
 PluginModuleParent::AnswerNPN_GetValue_WithBoolReturn(const NPNVariable& aVariable,
                                                       NPError* aError,
                                                       bool* aBoolVal)
 {
     NPBool boolVal = false;
     *aError = mozilla::plugins::parent::_getvalue(nsnull, aVariable, &boolVal);
     *aBoolVal = boolVal ? true : false;
--- a/dom/plugins/ipc/PluginModuleParent.h
+++ b/dom/plugins/ipc/PluginModuleParent.h
@@ -277,20 +277,16 @@ private:
     virtual nsresult NPP_New(NPMIMEType pluginType, NPP instance,
                              uint16_t mode, int16_t argc, char* argn[],
                              char* argv[], NPSavedData* saved,
                              NPError* error);
     virtual nsresult NPP_ClearSiteData(const char* site, uint64_t flags,
                                        uint64_t maxAge);
     virtual nsresult NPP_GetSitesWithData(InfallibleTArray<nsCString>& result);
 
-#if defined(XP_MACOSX)
-    virtual nsresult IsRemoteDrawingCoreAnimation(NPP instance, PRBool *aDrawing);
-#endif
-
 private:
     void WritePluginExtraDataForMinidump(const nsAString& id);
     void WriteExtraDataForHang();
     void CleanupFromTimeout();
     static int TimeoutChanged(const char* aPref, void* aModule);
     void NotifyPluginCrashed();
 
     nsCString mCrashNotes;
--- a/dom/plugins/ipc/PluginUtilsOSX.h
+++ b/dom/plugins/ipc/PluginUtilsOSX.h
@@ -33,23 +33,32 @@
   * decision by deleting the provisions above and replace them with the notice
   * and other provisions required by the GPL or the LGPL. If you do not delete
   * the provisions above, a recipient may use your version of this file under
   * the terms of any one of the MPL, the GPL or the LGPL.
   *
   * ***** END LICENSE BLOCK ***** */
 
 #include "npapi.h"
+#include "nsRect.h"
 
 namespace mozilla {
 namespace plugins {
 namespace PluginUtilsOSX {
 
-// Need to call back into the browser's to process event.
+// Need to call back into the browser's message loop to process event.
 typedef void (*RemoteProcessEvents) (void*);
 
 NPError ShowCocoaContextMenu(void* aMenu, int aX, int aY, void* pluginModule, RemoteProcessEvents remoteEvent);
 
 void InvokeNativeEventLoop();
 
+// Need to call back and send a cocoa draw event to the plugin.
+typedef void (*DrawPluginFunc) (CGContextRef, void*, nsIntRect aUpdateRect);
+
+void* GetCGLayer(DrawPluginFunc aFunc, void* aPluginInstance);
+void ReleaseCGLayer(void* cgLayer);
+void Repaint(void* cgLayer, nsIntRect aRect);
+
+
 } // namespace PluginUtilsOSX
 } // namespace plugins
 } // namespace mozilla
--- a/dom/plugins/ipc/PluginUtilsOSX.mm
+++ b/dom/plugins/ipc/PluginUtilsOSX.mm
@@ -33,23 +33,79 @@
   * decision by deleting the provisions above and replace them with the notice
   * and other provisions required by the GPL or the LGPL. If you do not delete
   * the provisions above, a recipient may use your version of this file under
   * the terms of any one of the MPL, the GPL or the LGPL.
   *
   * ***** END LICENSE BLOCK ***** */
 
 #import <AppKit/AppKit.h>
+#import <QuartzCore/QuartzCore.h>
 #include "PluginUtilsOSX.h"
 
 // Remove definitions for try/catch interfering with ObjCException macros.
 #include "nsObjCExceptions.h"
 
 using namespace mozilla::plugins::PluginUtilsOSX;
 
+@interface CGBridgeLayer : CALayer {
+  DrawPluginFunc mDrawFunc;
+  void* mPluginInstance;
+  nsIntRect mUpdateRect;
+}
+- (void) setDrawFunc: (DrawPluginFunc)aFunc pluginInstance:(void*) aPluginInstance;
+- (void) updateRect: (nsIntRect)aRect;
+
+@end
+
+@implementation CGBridgeLayer
+- (void) updateRect: (nsIntRect)aRect
+{
+   mUpdateRect.UnionRect(mUpdateRect, aRect);
+}
+
+- (void) setDrawFunc: (DrawPluginFunc)aFunc pluginInstance:(void*) aPluginInstance
+{
+  mDrawFunc = aFunc;
+  mPluginInstance = aPluginInstance;
+}
+
+- (void)drawInContext:(CGContextRef)aCGContext
+
+{
+  ::CGContextSaveGState(aCGContext); 
+  ::CGContextTranslateCTM(aCGContext, 0, self.bounds.size.height);
+  ::CGContextScaleCTM(aCGContext, (CGFloat) 1, (CGFloat) -1);
+
+  mDrawFunc(aCGContext, mPluginInstance, mUpdateRect);
+
+  ::CGContextRestoreGState(aCGContext); 
+
+  mUpdateRect.SetEmpty();
+}
+
+@end
+
+void* mozilla::plugins::PluginUtilsOSX::GetCGLayer(DrawPluginFunc aFunc, void* aPluginInstance) {
+  CGBridgeLayer *bridgeLayer = [[CGBridgeLayer alloc] init ];
+  [bridgeLayer setDrawFunc:aFunc pluginInstance:aPluginInstance];
+  return bridgeLayer;
+}
+
+void mozilla::plugins::PluginUtilsOSX::ReleaseCGLayer(void *cgLayer) {
+  CGBridgeLayer *bridgeLayer = (CGBridgeLayer*)cgLayer;
+  [bridgeLayer release];
+}
+
+void mozilla::plugins::PluginUtilsOSX::Repaint(void *caLayer, nsIntRect aRect) {
+  CGBridgeLayer *bridgeLayer = (CGBridgeLayer*)caLayer;
+  [bridgeLayer updateRect:aRect];
+  [bridgeLayer setNeedsDisplay];
+}
+
 @interface EventProcessor : NSObject {
   RemoteProcessEvents   aRemoteEvents;
   void                 *aPluginModule;
 }
 - (void)setRemoteEvents:(RemoteProcessEvents) remoteEvents pluginModule:(void*) pluginModule;
 - (void)onTick;
 @end
 
--- a/dom/plugins/test/mochitest/test_xulbrowser_plugin_visibility.xul
+++ b/dom/plugins/test/mochitest/test_xulbrowser_plugin_visibility.xul
@@ -1,11 +1,11 @@
 <?xml version="1.0"?>
 <?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
-<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.cs" type="text/css"?>
+<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" type="text/css"?>
 
 <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
   <script type="application/javascript"
 	  src="chrome://mochikit/content/MochiKit/packed.js" />
   <script type="application/javascript"
 	  src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" />
 
   <script>
--- a/dom/plugins/test/mochitest/xulbrowser_plugin_visibility.xul
+++ b/dom/plugins/test/mochitest/xulbrowser_plugin_visibility.xul
@@ -47,20 +47,24 @@
       if (2 == loadCount)
         startTest();
     }
 
     var tabbox = document.getElementById('tabbox');
     var browser1 = document.getElementById('browser1');
     var browser2 = document.getElementById('browser2');
 
+    var progressListener1, progressListener2;
+
     function setup() {
-      browser1.addProgressListener(new ProgressListener(), nsIWebProgress.NOTIFY_STATE_WINDOW);
+      progressListener1 = new ProgressListener();
+      browser1.addProgressListener(progressListener1, nsIWebProgress.NOTIFY_STATE_WINDOW);
       browser1.loadURI(kURI, null, null);
-      browser2.addProgressListener(new ProgressListener(), nsIWebProgress.NOTIFY_STATE_WINDOW);
+      progressListener2 = new ProgressListener();
+      browser2.addProgressListener(progressListener2, nsIWebProgress.NOTIFY_STATE_WINDOW);
       browser2.loadURI(kURI, null, null);
     }
 
     window.addEventListener("load", setup, false);
 
     var plugin1, plugin2;
 
     const kTimeout = 5000; // 5 seconds
--- a/dom/src/threads/nsDOMThreadService.cpp
+++ b/dom/src/threads/nsDOMThreadService.cpp
@@ -669,18 +669,17 @@ DOMWorkerErrorReporter(JSContext* aCx,
                                       "DOM Worker javascript",
                                       worker->Pool()->WindowID());
 
   if (NS_FAILED(rv)) {
     return;
   }
 
   // Don't call the error handler if we're out of stack space.
-  if (errorNumber != JSMSG_SCRIPT_STACK_QUOTA &&
-      errorNumber != JSMSG_OVER_RECURSED) {
+  if (errorNumber != JSMSG_OVER_RECURSED) {
     // Try the onerror handler for the worker's scope.
     nsRefPtr<nsDOMWorkerScope> scope = worker->GetInnerScope();
     NS_ASSERTION(scope, "Null scope!");
 
     PRBool hasListeners = scope->HasListeners(NS_LITERAL_STRING("error"));
     if (hasListeners) {
       nsRefPtr<nsDOMWorkerErrorEvent> event(new nsDOMWorkerErrorEvent());
       if (event) {
@@ -1067,17 +1066,16 @@ nsDOMThreadService::CreateJSContext()
 
   JS_ClearContextDebugHooks(cx);
 
   nsresult rv = nsContentUtils::XPConnect()->
     SetSecurityManagerForJSContext(cx, gWorkerSecurityManager, 0);
   NS_ENSURE_SUCCESS(rv, nsnull);
 
   JS_SetNativeStackQuota(cx, 256*1024);
-  JS_SetScriptStackQuota(cx, 100*1024*1024);
 
   JS_SetOptions(cx,
     JS_GetOptions(cx) | JSOPTION_METHODJIT | JSOPTION_JIT |
     JSOPTION_PROFILING | JSOPTION_ANONFUNFIX);
   JS_SetGCParameterForThread(cx, JSGC_MAX_CODE_CACHE_BYTES, 1 * 1024 * 1024);
 
   return cx.forget();
 }
--- a/dom/src/threads/nsDOMWorker.cpp
+++ b/dom/src/threads/nsDOMWorker.cpp
@@ -909,17 +909,16 @@ nsDOMWorkerScope::PostCreate(nsIXPConnec
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsDOMWorkerScope::Trace(nsIXPConnectWrappedNative* /* aWrapper */,
                         JSTracer* aTracer,
                         JSObject* /*aObj */)
 {
-  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
   nsDOMWorkerMessageHandler::Trace(aTracer);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsDOMWorkerScope::Finalize(nsIXPConnectWrappedNative* /* aWrapper */,
                            JSContext* /* aCx */,
                            JSObject* /* aObj */)
@@ -1504,18 +1503,16 @@ nsDOMWorker::PostCreate(nsIXPConnectWrap
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsDOMWorker::Trace(nsIXPConnectWrappedNative* /* aWrapper */,
                    JSTracer* aTracer,
                    JSObject* /*aObj */)
 {
-  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
-
   PRBool canceled = PR_FALSE;
   {
     MutexAutoLock lock(mLock);
     canceled = mStatus == eKilled;
   }
 
   if (!canceled) {
     nsDOMWorkerMessageHandler::Trace(aTracer);
--- a/dom/src/threads/nsDOMWorkerXHR.cpp
+++ b/dom/src/threads/nsDOMWorkerXHR.cpp
@@ -425,18 +425,16 @@ NS_IMPL_THREADSAFE_DOM_CI_GETINTERFACES(
 
 #include "xpc_map_end.h"
 
 NS_IMETHODIMP
 nsDOMWorkerXHR::Trace(nsIXPConnectWrappedNative* /* aWrapper */,
                       JSTracer* aTracer,
                       JSObject* /*aObj */)
 {
-  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
-
   if (!mCanceled) {
     nsDOMWorkerMessageHandler::Trace(aTracer);
     if (mUpload) {
       mUpload->Trace(aTracer);
     }
   }
 
   return NS_OK;
--- a/dom/tests/mochitest/dom-level2-html/test_HTMLBodyElement02.html
+++ b/dom/tests/mochitest/dom-level2-html/test_HTMLBodyElement02.html
@@ -90,19 +90,17 @@ function HTMLBodyElement02() {
       if (typeof(this.doc) != 'undefined') {
         docRef = this.doc;
       }
       doc = load(docRef, "doc", "body");
       nodeList = doc.getElementsByTagName("body");
       assertSize("Asize",1,nodeList);
 testNode = nodeList.item(0);
       vbackground = testNode.background;
-      // its not clear if this test is valid
-      //assertEquals("backgroundLink","./pix/back1.gif",vbackground);
-      todo_is(vbackground, "./pix/back1.gif", "backgroundLink");
+      assertEquals("backgroundLink","./pix/back1.gif",vbackground);
        
 }
 
 </script>
 </head>
 <body>
 <h2>Test http://www.w3.org/2001/DOM-Test-Suite/level2/html/HTMLBodyElement02</h2>
 <p>&lt;test name='HTMLBodyElement02' schemaLocation='http://www.w3.org/2001/DOM-Test-Suite/Level-1 dom1.xsd'&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;metadata&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;title&gt;HTMLBodyElement02&lt;/title&gt;
--- a/editor/libeditor/html/nsHTMLEditRules.cpp
+++ b/editor/libeditor/html/nsHTMLEditRules.cpp
@@ -2018,17 +2018,17 @@ nsHTMLEditRules::WillDeleteSelection(nsI
         res = range->GetStartOffset(&so);
         NS_ENSURE_SUCCESS(res, res);
         res = range->GetEndOffset(&eo);
         NS_ENSURE_SUCCESS(res, res);
       }
       res = nsWSRunObject::PrepareToDeleteRange(mHTMLEditor, address_of(visNode), &so, address_of(visNode), &eo);
       NS_ENSURE_SUCCESS(res, res);
       nsCOMPtr<nsIDOMCharacterData> nodeAsText(do_QueryInterface(visNode));
-      res = mHTMLEditor->DeleteText(nodeAsText, NS_MIN(so, eo), PR_ABS(eo - so));
+      res = mHTMLEditor->DeleteText(nodeAsText, NS_MIN(so, eo), NS_ABS(eo - so));
       *aHandled = PR_TRUE;
       NS_ENSURE_SUCCESS(res, res);    
       res = InsertBRIfNeeded(aSelection);
       return res;
     }
     else if ( (wsType==nsWSRunObject::eSpecial)  || 
               (wsType==nsWSRunObject::eBreak)    ||
               nsHTMLEditUtils::IsHR(visNode) ) 
--- a/editor/libeditor/html/nsHTMLObjectResizer.cpp
+++ b/editor/libeditor/html/nsHTMLObjectResizer.cpp
@@ -922,18 +922,18 @@ nsHTMLEditor::MouseMove(nsIDOMEvent* aMo
 
     nsCOMPtr<nsILookAndFeel> look = do_GetService(kLookAndFeelCID);
     NS_ASSERTION(look, "Look and feel service must be implemented for this toolkit");
 
     PRInt32 xThreshold=1, yThreshold=1;
     look->GetMetric(nsILookAndFeel::eMetric_DragThresholdX, xThreshold);
     look->GetMetric(nsILookAndFeel::eMetric_DragThresholdY, yThreshold);
 
-    if (PR_ABS(clientX - mOriginalX ) * 2 >= xThreshold ||
-        PR_ABS(clientY - mOriginalY ) * 2 >= yThreshold) {
+    if (NS_ABS(clientX - mOriginalX ) * 2 >= xThreshold ||
+        NS_ABS(clientY - mOriginalY ) * 2 >= yThreshold) {
       mGrabberClicked = PR_FALSE;
       StartMoving(nsnull);
     }
   }
   if (mIsMoving) {
     nsCOMPtr<nsIDOMMouseEvent> mouseEvent ( do_QueryInterface(aMouseEvent) );
     PRInt32 clientX, clientY;
     mouseEvent->GetClientX(&clientX);
new file mode 100644
--- /dev/null
+++ b/extensions/cookie/test/unit/test_bug650522.js
@@ -0,0 +1,16 @@
+/* Any copyright is dedicated to the Public Domain.
+   http://creativecommons.org/publicdomain/zero/1.0/ */
+
+Components.utils.import("resource://gre/modules/NetUtil.jsm");
+
+function run_test() {
+  var cs = Cc["@mozilla.org/cookieService;1"].getService(Ci.nsICookieService);
+  var cm = Cc["@mozilla.org/cookiemanager;1"].getService(Ci.nsICookieManager2);
+  var expiry = (Date.now() + 1000) * 1000;
+
+  // Test our handling of host names with a single character at the beginning
+  // followed by a dot.
+  cm.add("e.mail.com", "/", "foo", "bar", false, false, true, expiry);
+  do_check_eq(cm.countCookiesFromHost("e.mail.com"), 1);
+  do_check_eq(cs.getCookieString(NetUtil.newURI("http://e.mail.com"), null), "foo=bar");
+}
--- a/extensions/cookie/test/unit/xpcshell.ini
+++ b/extensions/cookie/test/unit/xpcshell.ini
@@ -1,14 +1,15 @@
 [DEFAULT]
 head = head_cookies.js
 tail = 
 
 [test_bug468700.js]
 [test_bug526789.js]
+[test_bug650522.js]
 [test_cookies_async_failure.js]
 [test_cookies_persistence.js]
 [test_cookies_privatebrowsing.js]
 [test_cookies_profile_close.js]
 [test_cookies_read.js]
 [test_cookies_sync_failure.js]
 [test_cookies_thirdparty.js]
 [test_cookies_thirdparty_session.js]
--- a/extensions/gnomevfs/nsGnomeVFSProtocolHandler.cpp
+++ b/extensions/gnomevfs/nsGnomeVFSProtocolHandler.cpp
@@ -518,17 +518,17 @@ nsGnomeVFSInputStream::DoRead(char *aBuf
     rv = GNOME_VFS_OK;
 
     while (aCount && rv != GNOME_VFS_ERROR_EOF)
     {
       // Copy data out of our buffer
       PRUint32 bufLen = mDirBuf.Length() - mDirBufCursor;
       if (bufLen)
       {
-        PRUint32 n = PR_MIN(bufLen, aCount);
+        PRUint32 n = NS_MIN(bufLen, aCount);
         memcpy(aBuf, mDirBuf.get() + mDirBufCursor, n);
         *aCountRead += n;
         aBuf += n;
         aCount -= n;
         mDirBufCursor += n;
       }
 
       if (!mDirListPtr)    // Are we at the end of the directory list?
--- a/extensions/pref/autoconfig/src/nsAutoConfig.cpp
+++ b/extensions/pref/autoconfig/src/nsAutoConfig.cpp
@@ -132,17 +132,17 @@ nsAutoConfig::OnDataAvailable(nsIRequest
                               PRUint32 aSourceOffset,
                               PRUint32 aLength)
 {    
     PRUint32 amt, size;
     nsresult rv;
     char buf[1024];
     
     while (aLength) {
-        size = PR_MIN(aLength, sizeof(buf));
+        size = NS_MIN<size_t>(aLength, sizeof(buf));
         rv = aIStream->Read(buf, size, &amt);
         if (NS_FAILED(rv))
             return rv;
         mBuf.Append(buf, amt);
         aLength -= amt;
     }
     return NS_OK;
 }
--- a/gfx/cairo/cairo/src/cairo-d2d-private.h
+++ b/gfx/cairo/cairo/src/cairo-d2d-private.h
@@ -73,17 +73,17 @@ struct _cairo_d2d_device
 };
 
 const unsigned int TEXT_TEXTURE_WIDTH = 2048;
 const unsigned int TEXT_TEXTURE_HEIGHT = 512;
 typedef struct _cairo_d2d_device cairo_d2d_device_t;
 
 struct _cairo_d2d_surface {
     _cairo_d2d_surface() : d2d_clip(NULL), clipping(false), isDrawing(false),
-	textRenderingInit(false)
+            textRenderingState(TEXT_RENDERING_UNINITIALIZED)
     {
 	_cairo_clip_init (&this->clip);
     }
 
     cairo_surface_t base;
     /* Device used by this surface 
      * NOTE: In upstream cairo this is in the surface base class */
     cairo_d2d_device_t *device;
@@ -123,17 +123,22 @@ struct _cairo_d2d_surface {
     bool clipping;
     /** Brush used for bitmaps */
     RefPtr<ID2D1BitmapBrush> bitmapBrush;
     /** Brush used for solid colors */
     RefPtr<ID2D1SolidColorBrush> solidColorBrush;
     /** Indicates if our render target is currently in drawing mode */
     bool isDrawing;
     /** Indicates if text rendering is initialized */
-    bool textRenderingInit;
+    enum TextRenderingState {
+        TEXT_RENDERING_UNINITIALIZED,
+        TEXT_RENDERING_NORMAL,
+        TEXT_RENDERING_GDI_CLASSIC
+    };
+    TextRenderingState textRenderingState;
 
     RefPtr<ID3D10RenderTargetView> buffer_rt_view;
     RefPtr<ID3D10ShaderResourceView> buffer_sr_view;
 
 
     //cairo_surface_clipper_t clipper;
 };
 typedef struct _cairo_d2d_surface cairo_d2d_surface_t;
--- a/gfx/cairo/cairo/src/cairo-d2d-surface.cpp
+++ b/gfx/cairo/cairo/src/cairo-d2d-surface.cpp
@@ -4104,20 +4104,26 @@ static cairo_int_status_t
 			cairo_scaled_font_t	*scaled_font,
 			cairo_clip_t            *clip,
 			int			*remaining_glyphs)
 {
     if (((cairo_surface_t*)surface)->type != CAIRO_SURFACE_TYPE_D2D) {
 	return CAIRO_INT_STATUS_UNSUPPORTED;
     }
     cairo_d2d_surface_t *d2dsurf = static_cast<cairo_d2d_surface_t*>(surface);
-    if (!d2dsurf->textRenderingInit) {
-	RefPtr<IDWriteRenderingParams> params = DWriteFactory::RenderingParams();
+    cairo_bool_t forceGDIClassic =
+        scaled_font->backend->type == CAIRO_FONT_TYPE_DWRITE &&
+        reinterpret_cast<cairo_dwrite_scaled_font_t*>(scaled_font)->force_GDI_classic;
+    cairo_d2d_surface_t::TextRenderingState textRenderingState =
+        (forceGDIClassic ? cairo_d2d_surface_t::TEXT_RENDERING_GDI_CLASSIC : cairo_d2d_surface_t::TEXT_RENDERING_NORMAL);
+    if (d2dsurf->textRenderingState != textRenderingState) {
+	RefPtr<IDWriteRenderingParams> params =
+	    DWriteFactory::RenderingParams(forceGDIClassic);
 	d2dsurf->rt->SetTextRenderingParams(params);
-	d2dsurf->textRenderingInit = true;
+	d2dsurf->textRenderingState = textRenderingState;
     }
     cairo_int_status_t status = CAIRO_INT_STATUS_UNSUPPORTED;
     if (scaled_font->backend->type == CAIRO_FONT_TYPE_DWRITE) {
 	status = (cairo_int_status_t)
 	    _cairo_dwrite_show_glyphs_on_d2d_surface(surface, op, source, glyphs, num_glyphs, scaled_font, clip);
     }
 
     return status;
--- a/gfx/cairo/cairo/src/cairo-dwrite-font.cpp
+++ b/gfx/cairo/cairo/src/cairo-dwrite-font.cpp
@@ -61,16 +61,17 @@ cairo_int_status_t
 				       COLORREF color,
 				       const RECT &area);
 
 cairo_int_status_t
 _dwrite_draw_glyphs_to_gdi_surface_gdi(cairo_win32_surface_t *surface,
 				       DWRITE_MATRIX *transform,
 				       DWRITE_GLYPH_RUN *run,
 				       COLORREF color,
+				       cairo_dwrite_scaled_font_t *scaled_font,
 				       const RECT &area);
 
 class D2DFactory
 {
 public:
     static ID2D1Factory *Instance()
     {
 	if (!mFactoryInstance) {
@@ -114,16 +115,17 @@ public:
 private:
     static ID2D1Factory *mFactoryInstance;
     static ID2D1DCRenderTarget *mRenderTarget;
 };
 
 IDWriteFactory *DWriteFactory::mFactoryInstance = NULL;
 IDWriteFontCollection *DWriteFactory::mSystemCollection = NULL;
 IDWriteRenderingParams *DWriteFactory::mRenderingParams = NULL;
+IDWriteRenderingParams *DWriteFactory::mForceGDIClassicRenderingParams = NULL;
 FLOAT DWriteFactory::mGamma = -1.0;
 FLOAT DWriteFactory::mEnhancedContrast = -1.0;
 FLOAT DWriteFactory::mClearTypeLevel = -1.0;
 int DWriteFactory::mPixelGeometry = -1;
 int DWriteFactory::mRenderingMode = -1;
 
 ID2D1Factory *D2DFactory::mFactoryInstance = NULL;
 ID2D1DCRenderTarget *D2DFactory::mRenderTarget = NULL;
@@ -489,16 +491,17 @@ static cairo_status_t
 
     if (options->antialias == CAIRO_ANTIALIAS_DEFAULT) {
 	dwriteFont->antialias_mode = default_quality;
     } else {
 	dwriteFont->antialias_mode = options->antialias;
     }
 
     dwriteFont->manual_show_glyphs_allowed = TRUE;
+    dwriteFont->force_GDI_classic = FALSE;
 
     return _cairo_scaled_font_set_metrics (*font, &extents);
 }
 
 /* Implementation cairo_dwrite_scaled_font_backend_t */
 void
 _cairo_dwrite_scaled_font_fini(void *scaled_font)
 {
@@ -986,17 +989,18 @@ cairo_int_status_t
     run.fontEmSize = 1.0f;
     run.bidiLevel = 0;
     run.glyphIndices = &index;
     run.isSideways = FALSE;
     run.glyphOffsets = &offset;
 
     DWRITE_MATRIX matrix = _cairo_dwrite_matrix_from_matrix(&scaled_font->mat);
 
-    status = _dwrite_draw_glyphs_to_gdi_surface_gdi (surface, &matrix, &run, RGB(0,0,0), area);
+    status = _dwrite_draw_glyphs_to_gdi_surface_gdi (surface, &matrix, &run,
+            RGB(0,0,0), scaled_font, area);
     if (status)
 	goto FAIL;
 
     GdiFlush();
 
     image = _compute_a8_mask (surface);
     status = (cairo_int_status_t)image->status;
     if (status)
@@ -1064,41 +1068,57 @@ cairo_dwrite_font_face_create_for_dwrite
     font_face = (cairo_font_face_t*)face;
     
     _cairo_font_face_init (&((cairo_dwrite_font_face_t*)font_face)->base, &_cairo_dwrite_font_face_backend);
 
     return font_face;
 }
 
 void
-cairo_dwrite_scaled_font_allow_manual_show_glyphs(void* dwrite_scaled_font, cairo_bool_t allowed)
+cairo_dwrite_scaled_font_allow_manual_show_glyphs(cairo_scaled_font_t *dwrite_scaled_font, cairo_bool_t allowed)
+{
+    cairo_dwrite_scaled_font_t *font = reinterpret_cast<cairo_dwrite_scaled_font_t*>(dwrite_scaled_font);
+    font->manual_show_glyphs_allowed = allowed;
+}
+
+void
+cairo_dwrite_scaled_font_set_force_GDI_classic(cairo_scaled_font_t *dwrite_scaled_font, cairo_bool_t force)
 {
-    cairo_dwrite_scaled_font_t *font = static_cast<cairo_dwrite_scaled_font_t*>(dwrite_scaled_font);
-    font->manual_show_glyphs_allowed = allowed;
+    cairo_dwrite_scaled_font_t *font = reinterpret_cast<cairo_dwrite_scaled_font_t*>(dwrite_scaled_font);
+    font->force_GDI_classic = force;
+}
+
+cairo_bool_t
+cairo_dwrite_scaled_font_get_force_GDI_classic(cairo_scaled_font_t *dwrite_scaled_font)
+{
+    cairo_dwrite_scaled_font_t *font = reinterpret_cast<cairo_dwrite_scaled_font_t*>(dwrite_scaled_font);
+    return font->force_GDI_classic;
 }
 
 void
 cairo_dwrite_set_cleartype_params(FLOAT gamma, FLOAT contrast, FLOAT level,
 				  int geometry, int mode)
 {
     DWriteFactory::SetRenderingParams(gamma, contrast, level, geometry, mode);
 }
 
 cairo_int_status_t
 _dwrite_draw_glyphs_to_gdi_surface_gdi(cairo_win32_surface_t *surface,
 				       DWRITE_MATRIX *transform,
 				       DWRITE_GLYPH_RUN *run,
 				       COLORREF color,
+				       cairo_dwrite_scaled_font_t *scaled_font,
 				       const RECT &area)
 {
     IDWriteGdiInterop *gdiInterop;
     DWriteFactory::Instance()->GetGdiInterop(&gdiInterop);
     IDWriteBitmapRenderTarget *rt;
 
-    IDWriteRenderingParams *params = DWriteFactory::RenderingParams();
+    IDWriteRenderingParams *params =
+        DWriteFactory::RenderingParams(scaled_font->force_GDI_classic);
 
     gdiInterop->CreateBitmapRenderTarget(surface->dc, 
 					 area.right - area.left, 
 					 area.bottom - area.top, 
 					 &rt);
 
     /**
      * We set the number of pixels per DIP to 1.0. This is because we always want
@@ -1136,16 +1156,18 @@ cairo_int_status_t
 				       DWRITE_GLYPH_RUN *run,
 				       COLORREF color,
 				       const RECT &area)
 {
     HRESULT rv;
 
     ID2D1DCRenderTarget *rt = D2DFactory::RenderTarget();
 
+    // XXX don't we need to set RenderingParams on this RenderTarget?
+
     rv = rt->BindDC(surface->dc, &area);
 
     printf("Rendering to surface: %p\n", surface->dc);
 
     if (FAILED(rv)) {
 	rt->Release();
 	return CAIRO_INT_STATUS_UNSUPPORTED;
     }
@@ -1364,16 +1386,17 @@ cairo_int_status_t
 						    fontArea);
 
     if (status == (cairo_status_t)CAIRO_INT_STATUS_UNSUPPORTED) {
 #endif
 	status = _dwrite_draw_glyphs_to_gdi_surface_gdi(dst,
 							mat,
 							&run,
 							color,
+							dwritesf,
 							fontArea);
 #ifdef CAIRO_TRY_D2D_TO_GDI
     }
 #endif
 
     delete [] indices;
     delete [] offsets;
     delete [] advances;
@@ -1408,25 +1431,32 @@ DWriteFactory::CreateRenderingParams()
 	    RegCloseKey(hKey);
 	} else {
 	    contrast = 1.0;
 	}
     }
 
     // For parameters that have not been explicitly set via the SetRenderingParams API,
     // we copy values from default params (or our overridden value for contrast)
-    Instance()->CreateCustomRenderingParams(
-	mGamma >= 1.0 && mGamma <= 2.2 ? mGamma : defaultParams->GetGamma(),
-	contrast,
-	mClearTypeLevel >= 0.0 && mClearTypeLevel <= 1.0 ? mClearTypeLevel : defaultParams->GetClearTypeLevel(),
-	mPixelGeometry >= DWRITE_PIXEL_GEOMETRY_FLAT && mPixelGeometry <= DWRITE_PIXEL_GEOMETRY_BGR ?
-	    (DWRITE_PIXEL_GEOMETRY)mPixelGeometry : defaultParams->GetPixelGeometry(),
-	mRenderingMode >= DWRITE_RENDERING_MODE_DEFAULT && mRenderingMode <= DWRITE_RENDERING_MODE_CLEARTYPE_NATURAL_SYMMETRIC ?
-	    (DWRITE_RENDERING_MODE)mRenderingMode : defaultParams->GetRenderingMode(), 
+    FLOAT gamma =
+        mGamma >= 1.0 && mGamma <= 2.2 ? mGamma : defaultParams->GetGamma();
+    FLOAT clearTypeLevel =
+        mClearTypeLevel >= 0.0 && mClearTypeLevel <= 1.0 ? mClearTypeLevel : defaultParams->GetClearTypeLevel();
+    DWRITE_PIXEL_GEOMETRY pixelGeometry =
+        mPixelGeometry >= DWRITE_PIXEL_GEOMETRY_FLAT && mPixelGeometry <= DWRITE_PIXEL_GEOMETRY_BGR ?
+            (DWRITE_PIXEL_GEOMETRY)mPixelGeometry : defaultParams->GetPixelGeometry();
+    DWRITE_RENDERING_MODE renderingMode =
+        mRenderingMode >= DWRITE_RENDERING_MODE_DEFAULT && mRenderingMode <= DWRITE_RENDERING_MODE_CLEARTYPE_NATURAL_SYMMETRIC ?
+            (DWRITE_RENDERING_MODE)mRenderingMode : defaultParams->GetRenderingMode();
+    Instance()->CreateCustomRenderingParams(gamma, contrast, clearTypeLevel,
+	pixelGeometry, renderingMode,
 	&mRenderingParams);
+    Instance()->CreateCustomRenderingParams(gamma, contrast, clearTypeLevel,
+        pixelGeometry, DWRITE_RENDERING_MODE_CLEARTYPE_GDI_CLASSIC,
+        &mForceGDIClassicRenderingParams);
 }
 
 // Helper for _cairo_win32_printing_surface_show_glyphs to create a win32 equivalent
 // of a dwrite scaled_font so that we can print using ExtTextOut instead of drawing
 // paths or blitting glyph bitmaps.
 cairo_int_status_t
 _cairo_dwrite_scaled_font_create_win32_scaled_font (cairo_scaled_font_t *scaled_font,
                                                     cairo_scaled_font_t **new_font)
--- a/gfx/cairo/cairo/src/cairo-dwrite-private.h
+++ b/gfx/cairo/cairo/src/cairo-dwrite-private.h
@@ -39,16 +39,27 @@
 
 // DirectWrite is not available on all platforms.
 typedef HRESULT (WINAPI*DWriteCreateFactoryFunc)(
   __in   DWRITE_FACTORY_TYPE factoryType,
   __in   REFIID iid,
   __out