Merge last PGO-green changeset of mozilla-inbound to mozilla-central
authorEd Morley <emorley@mozilla.com>
Fri, 19 Oct 2012 15:23:32 +0100
changeset 110886 7fcac30161593d16fba7b0cdea3f5b002b10be10
parent 110844 987d2f22f83f6f48cdcf284212c77ba2a55ba336 (current diff)
parent 110885 445aca56acf68c6a2a51c439ea5c7e0329a275ad (diff)
child 110887 ca6044e25cd24ef7616979ff3e30d320597d3300
child 110906 be16da4e188bd7a8e217367acaf4e42a0077cb0e
push id93
push usernmatsakis@mozilla.com
push dateWed, 31 Oct 2012 21:26:57 +0000
milestone19.0a1
Merge last PGO-green changeset of mozilla-inbound to mozilla-central
--- a/accessible/src/atk/AccessibleWrap.cpp
+++ b/accessible/src/atk/AccessibleWrap.cpp
@@ -737,32 +737,30 @@ ConvertToAtkAttributeSet(nsIPersistentPr
 
     //libspi will free it
     return objAttributeSet;
 }
 
 AtkAttributeSet*
 GetAttributeSet(Accessible* aAccessible)
 {
-    nsCOMPtr<nsIPersistentProperties> attributes;
-    aAccessible->GetAttributes(getter_AddRefs(attributes));
-
-    if (attributes) {
-        // Deal with attributes that we only need to expose in ATK
-        if (aAccessible->State() & states::HASPOPUP) {
-          // There is no ATK state for haspopup, must use object attribute to expose the same info
-          nsAutoString oldValueUnused;
-          attributes->SetStringProperty(NS_LITERAL_CSTRING("haspopup"), NS_LITERAL_STRING("true"),
-                                        oldValueUnused);
-        }
-
-        return ConvertToAtkAttributeSet(attributes);
+  nsCOMPtr<nsIPersistentProperties> attributes = aAccessible->Attributes();
+  if (attributes) {
+    // There is no ATK state for haspopup, must use object attribute to expose
+    // the same info.
+    if (aAccessible->State() & states::HASPOPUP) {
+      nsAutoString unused;
+      attributes->SetStringProperty(NS_LITERAL_CSTRING("haspopup"),
+                                    NS_LITERAL_STRING("true"), unused);
     }
 
-    return nullptr;
+    return ConvertToAtkAttributeSet(attributes);
+  }
+
+  return nullptr;
 }
 
 AtkAttributeSet *
 getAttributesCB(AtkObject *aAtkObj)
 {
   AccessibleWrap* accWrap = GetAccessibleWrap(aAtkObj);
   return accWrap ? GetAttributeSet(accWrap) : nullptr;
 }
--- a/accessible/src/base/nsARIAMap.h
+++ b/accessible/src/base/nsARIAMap.h
@@ -87,25 +87,25 @@ const bool kUseMapRole = true;
 const bool kUseNativeRole = false;
 
 
 ////////////////////////////////////////////////////////////////////////////////
 // ARIA attribute characteristic masks
 
 /**
  * This mask indicates the attribute should not be exposed as an object
- * attribute via the catch-all logic in Accessible::GetAttributes.
+ * attribute via the catch-all logic in Accessible::Attributes().
  * This means it either isn't mean't to be exposed as an object attribute, or
  * that it should, but is already handled in other code.
  */
 const uint8_t ATTR_BYPASSOBJ  = 0x0001;
 
 /**
  * This mask indicates the attribute is expected to have an NMTOKEN or bool value.
- * (See for example usage in Accessible::GetAttributes)
+ * (See for example usage in Accessible::Attributes())
  */
 const uint8_t ATTR_VALTOKEN   = 0x0010;
 
 /**
  * Small footprint storage of persistent aria attribute characteristics.
  */
 struct nsAttributeCharacteristics
 {
--- a/accessible/src/generic/ARIAGridAccessible.cpp
+++ b/accessible/src/generic/ARIAGridAccessible.cpp
@@ -609,29 +609,26 @@ ARIAGridCellAccessible::ApplyARIAState(u
   if (nsAccUtils::HasDefinedARIAToken(rowContent,
                                       nsGkAtoms::aria_selected) &&
       !rowContent->AttrValueIs(kNameSpaceID_None,
                                nsGkAtoms::aria_selected,
                                nsGkAtoms::_false, eCaseMatters))
     *aState |= states::SELECTABLE | states::SELECTED;
 }
 
-nsresult
-ARIAGridCellAccessible::GetAttributesInternal(nsIPersistentProperties* aAttributes)
+already_AddRefed<nsIPersistentProperties>
+ARIAGridCellAccessible::NativeAttributes()
 {
-  if (IsDefunct())
-    return NS_ERROR_FAILURE;
-
-  nsresult rv = HyperTextAccessibleWrap::GetAttributesInternal(aAttributes);
-  NS_ENSURE_SUCCESS(rv, rv);
+  nsCOMPtr<nsIPersistentProperties> attributes =
+    HyperTextAccessibleWrap::NativeAttributes();
 
   // Expose "table-cell-index" attribute.
   Accessible* thisRow = Row();
   if (!thisRow)
-    return NS_OK;
+    return attributes.forget();
 
   int32_t colIdx = 0, colCount = 0;
   uint32_t childCount = thisRow->ChildCount();
   for (uint32_t childIdx = 0; childIdx < childCount; childIdx++) {
     Accessible* child = thisRow->GetChildAt(childIdx);
     if (child == this)
       colIdx = colCount;
 
@@ -640,20 +637,19 @@ ARIAGridCellAccessible::GetAttributesInt
         role == roles::COLUMNHEADER)
       colCount++;
   }
 
   int32_t rowIdx = RowIndexFor(thisRow);
 
   nsAutoString stringIdx;
   stringIdx.AppendInt(rowIdx * colCount + colIdx);
-  nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::tableCellIndex,
-                         stringIdx);
+  nsAccUtils::SetAccAttr(attributes, nsGkAtoms::tableCellIndex, stringIdx);
 
-  return NS_OK;
+  return attributes.forget();
 }
 
 void
 ARIAGridCellAccessible::Shutdown()
 {
   mTableCell = nullptr;
   HyperTextAccessibleWrap::Shutdown();
 }
--- a/accessible/src/generic/ARIAGridAccessible.h
+++ b/accessible/src/generic/ARIAGridAccessible.h
@@ -111,17 +111,17 @@ public:
 
   // nsIAccessibleTableCell
   NS_FORWARD_NSIACCESSIBLETABLECELL(xpcAccessibleTableCell::)
 
   // Accessible
   virtual TableCellAccessible* AsTableCell() { return this; }
   virtual void Shutdown();
   virtual void ApplyARIAState(uint64_t* aState) const;
-  virtual nsresult GetAttributesInternal(nsIPersistentProperties *aAttributes);
+  virtual already_AddRefed<nsIPersistentProperties> NativeAttributes() MOZ_OVERRIDE;
 
 protected:
 
   /**
    * Return a containing row.
    */
   Accessible* Row() const
   {
--- a/accessible/src/generic/Accessible.cpp
+++ b/accessible/src/generic/Accessible.cpp
@@ -1181,205 +1181,208 @@ Accessible::GetRole(uint32_t *aRole)
   if (IsDefunct())
     return NS_ERROR_FAILURE;
 
   *aRole = Role();
   return NS_OK;
 }
 
 NS_IMETHODIMP
-Accessible::GetAttributes(nsIPersistentProperties **aAttributes)
+Accessible::GetAttributes(nsIPersistentProperties** aAttributes)
 {
-  NS_ENSURE_ARG_POINTER(aAttributes);  // In/out param. Created if necessary.
-  
+  NS_ENSURE_ARG_POINTER(aAttributes);
+  *aAttributes = nullptr;
+
   if (IsDefunct())
     return NS_ERROR_FAILURE;
 
-  nsCOMPtr<nsIPersistentProperties> attributes = *aAttributes;
-  if (!attributes) {
-    // Create only if an array wasn't already passed in
-    attributes = do_CreateInstance(NS_PERSISTENTPROPERTIES_CONTRACTID);
-    NS_ENSURE_TRUE(attributes, NS_ERROR_OUT_OF_MEMORY);
-    NS_ADDREF(*aAttributes = attributes);
-  }
- 
-  nsresult rv = GetAttributesInternal(attributes);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  nsAutoString id;
-  nsAutoString oldValueUnused;
-  if (nsCoreUtils::GetID(mContent, id)) {
-    // Expose ID. If an <iframe id> exists override the one on the <body> of the source doc,
-    // because the specific instance is what makes the ID useful for scripts
-    attributes->SetStringProperty(NS_LITERAL_CSTRING("id"), id, oldValueUnused);
-  }
-  
-  nsAutoString xmlRoles;
+  nsCOMPtr<nsIPersistentProperties> attributes = Attributes();
+  attributes.swap(*aAttributes);
+
+  return NS_OK;
+}
+
+already_AddRefed<nsIPersistentProperties>
+Accessible::Attributes()
+{
+  nsCOMPtr<nsIPersistentProperties> attributes = NativeAttributes();
+  if (!HasOwnContent() || !mContent->IsElement())
+    return attributes.forget();
+
+  // 'xml-roles' attribute coming from ARIA.
+  nsAutoString xmlRoles, unused;
   if (mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::role, xmlRoles)) {
-    attributes->SetStringProperty(NS_LITERAL_CSTRING("xml-roles"),  xmlRoles, oldValueUnused);          
+    attributes->SetStringProperty(NS_LITERAL_CSTRING("xml-roles"),
+                                  xmlRoles, unused);
   }
 
-  if (HasNumericValue()) {
-    // We support values, so expose the string value as well, via the valuetext object attribute
-    // We test for the value interface because we don't want to expose traditional get_accValue()
-    // information such as URL's on links and documents, or text in an input
-    nsAutoString valuetext;
-    GetValue(valuetext);
-    attributes->SetStringProperty(NS_LITERAL_CSTRING("valuetext"), valuetext, oldValueUnused);
-  }
-
-  // Expose checkable object attribute if the accessible has checkable state
-  if (State() & states::CHECKABLE)
-    nsAccUtils::SetAccAttr(attributes, nsGkAtoms::checkable, NS_LITERAL_STRING("true"));
-
-  // Expose 'explicit-name' attribute.
-  if (!nsTextEquivUtils::IsNameFromSubtreeAllowed(this) ||
-      Name(oldValueUnused) != eNameFromSubtree) {
-    attributes->SetStringProperty(NS_LITERAL_CSTRING("explicit-name"),
-                                  NS_LITERAL_STRING("true"), oldValueUnused);
-  }
-
-  // Group attributes (level/setsize/posinset)
-  GroupPos groupPos = GroupPosition();
-  nsAccUtils::SetAccGroupAttrs(attributes, groupPos.level,
-                               groupPos.setSize, groupPos.posInSet);
-
   // Expose object attributes from ARIA attributes.
   aria::AttrIterator attribIter(mContent);
   nsAutoString name, value;
-  while(attribIter.Next(name, value)) {
-    attributes->SetStringProperty(NS_ConvertUTF16toUTF8(name), value, 
-                                  oldValueUnused);
-  }
+  while(attribIter.Next(name, value))
+    attributes->SetStringProperty(NS_ConvertUTF16toUTF8(name), value, unused);
 
   // If there is no aria-live attribute then expose default value of 'live'
   // object attribute used for ARIA role of this accessible.
   if (mRoleMapEntry) {
     nsAutoString live;
     nsAccUtils::GetAccAttr(attributes, nsGkAtoms::live, live);
     if (live.IsEmpty()) {
       if (nsAccUtils::GetLiveAttrValue(mRoleMapEntry->liveAttRule, live))
         nsAccUtils::SetAccAttr(attributes, nsGkAtoms::live, live);
     }
   }
 
-  return NS_OK;
+  return attributes.forget();
 }
 
-nsresult
-Accessible::GetAttributesInternal(nsIPersistentProperties *aAttributes)
+already_AddRefed<nsIPersistentProperties>
+Accessible::NativeAttributes()
 {
-  // If the accessible isn't primary for its node (such as list item bullet or
-  // xul tree item then don't calculate content based attributes.
+  nsCOMPtr<nsIPersistentProperties> attributes =
+    do_CreateInstance(NS_PERSISTENTPROPERTIES_CONTRACTID);
+
+  nsAutoString unused;
+
+  // We support values, so expose the string value as well, via the valuetext
+  // object attribute. We test for the value interface because we don't want
+  // to expose traditional Value() information such as URL's on links and
+  // documents, or text in an input.
+  if (HasNumericValue()) {
+    nsAutoString valuetext;
+    GetValue(valuetext);
+    attributes->SetStringProperty(NS_LITERAL_CSTRING("valuetext"), valuetext,
+                                  unused);
+  }
+
+  // Expose checkable object attribute if the accessible has checkable state
+  if (State() & states::CHECKABLE) {
+    nsAccUtils::SetAccAttr(attributes, nsGkAtoms::checkable,
+                           NS_LITERAL_STRING("true"));
+  }
+
+  // Expose 'explicit-name' attribute.
+  if (!nsTextEquivUtils::IsNameFromSubtreeAllowed(this) ||
+      Name(unused) != eNameFromSubtree) {
+    attributes->SetStringProperty(NS_LITERAL_CSTRING("explicit-name"),
+                                  NS_LITERAL_STRING("true"), unused);
+  }
+
+  // Group attributes (level/setsize/posinset)
+  GroupPos groupPos = GroupPosition();
+  nsAccUtils::SetAccGroupAttrs(attributes, groupPos.level,
+                               groupPos.setSize, groupPos.posInSet);
+
+  // If the accessible doesn't have own content (such as list item bullet or
+  // xul tree item) then don't calculate content based attributes.
   if (!HasOwnContent())
-    return NS_OK;
-
-  // Attributes set by this method will not be used to override attributes on a sub-document accessible
-  // when there is a <frame>/<iframe> element that spawned the sub-document
-
-  nsEventShell::GetEventAttributes(GetNode(), aAttributes);
- 
-  // Expose class because it may have useful microformat information
-  // Let the class from an iframe's document be exposed, don't override from <iframe class>
-  nsAutoString _class;
-  if (mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::_class, _class))
-    nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::_class, _class);
-
-  // Get container-foo computed live region properties based on the closest container with
-  // the live region attribute. 
-  // Inner nodes override outer nodes within the same document --
-  //   The inner nodes can be used to override live region behavior on more general outer nodes
-  // However, nodes in outer documents override nodes in inner documents:
-  //   Outer doc author may want to override properties on a widget they used in an iframe
+    return attributes.forget();
+
+  nsEventShell::GetEventAttributes(GetNode(), attributes);
+
+  // Get container-foo computed live region properties based on the closest
+  // container with the live region attribute. Inner nodes override outer nodes
+  // within the same document. The inner nodes can be used to override live
+  // region behavior on more general outer nodes. However, nodes in outer
+  // documents override nodes in inner documents: outer doc author may want to
+  // override properties on a widget they used in an iframe.
   nsIContent* startContent = mContent;
   while (startContent) {
     nsIDocument* doc = startContent->GetDocument();
-    nsIContent* rootContent = nsCoreUtils::GetRoleContent(doc);
-    if (!rootContent)
-      return NS_OK;
-
-    nsAccUtils::SetLiveContainerAttributes(aAttributes, startContent,
-                                           rootContent);
+    if (!doc)
+      break;
+
+    nsAccUtils::SetLiveContainerAttributes(attributes, startContent,
+                                           nsCoreUtils::GetRoleContent(doc));
 
     // Allow ARIA live region markup from outer documents to override
     nsCOMPtr<nsISupports> container = doc->GetContainer(); 
     nsCOMPtr<nsIDocShellTreeItem> docShellTreeItem =
       do_QueryInterface(container);
     if (!docShellTreeItem)
       break;
 
     nsCOMPtr<nsIDocShellTreeItem> sameTypeParent;
     docShellTreeItem->GetSameTypeParent(getter_AddRefs(sameTypeParent));
     if (!sameTypeParent || sameTypeParent == docShellTreeItem)
       break;
 
-    nsIDocument *parentDoc = doc->GetParentDocument();
+    nsIDocument* parentDoc = doc->GetParentDocument();
     if (!parentDoc)
       break;
 
-    startContent = parentDoc->FindContentForSubDocument(doc);      
+    startContent = parentDoc->FindContentForSubDocument(doc);
   }
 
   if (!mContent->IsElement())
-    return NS_OK;
+    return attributes.forget();
+
+  nsAutoString id;
+  if (nsCoreUtils::GetID(mContent, id))
+    attributes->SetStringProperty(NS_LITERAL_CSTRING("id"), id, unused);
+
+  // Expose class because it may have useful microformat information.
+  nsAutoString _class;
+  if (mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::_class, _class))
+    nsAccUtils::SetAccAttr(attributes, nsGkAtoms::_class, _class);
 
   // Expose tag.
   nsAutoString tagName;
   mContent->NodeInfo()->GetName(tagName);
-  nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::tag, tagName);
-
-  // Expose draggable object attribute?
+  nsAccUtils::SetAccAttr(attributes, nsGkAtoms::tag, tagName);
+
+  // Expose draggable object attribute.
   nsCOMPtr<nsIDOMHTMLElement> htmlElement = do_QueryInterface(mContent);
   if (htmlElement) {
     bool draggable = false;
     htmlElement->GetDraggable(&draggable);
     if (draggable) {
-      nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::draggable,
+      nsAccUtils::SetAccAttr(attributes, nsGkAtoms::draggable,
                              NS_LITERAL_STRING("true"));
     }
   }
 
   // Don't calculate CSS-based object attributes when no frame (i.e.
   // the accessible is unattached from the tree).
   if (!mContent->GetPrimaryFrame())
-    return NS_OK;
+    return attributes.forget();
 
   // CSS style based object attributes.
   nsAutoString value;
   StyleInfo styleInfo(mContent->AsElement(), mDoc->PresShell());
 
   // Expose 'display' attribute.
   styleInfo.Display(value);
-  nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::display, value);
+  nsAccUtils::SetAccAttr(attributes, nsGkAtoms::display, value);
 
   // Expose 'text-align' attribute.
   styleInfo.TextAlign(value);
-  nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::textAlign, value);
+  nsAccUtils::SetAccAttr(attributes, nsGkAtoms::textAlign, value);
 
   // Expose 'text-indent' attribute.
   styleInfo.TextIndent(value);
-  nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::textIndent, value);
+  nsAccUtils::SetAccAttr(attributes, nsGkAtoms::textIndent, value);
 
   // Expose 'margin-left' attribute.
   styleInfo.MarginLeft(value);
-  nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::marginLeft, value);
+  nsAccUtils::SetAccAttr(attributes, nsGkAtoms::marginLeft, value);
 
   // Expose 'margin-right' attribute.
   styleInfo.MarginRight(value);
-  nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::marginRight, value);
+  nsAccUtils::SetAccAttr(attributes, nsGkAtoms::marginRight, value);
 
   // Expose 'margin-top' attribute.
   styleInfo.MarginTop(value);
-  nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::marginTop, value);
+  nsAccUtils::SetAccAttr(attributes, nsGkAtoms::marginTop, value);
 
   // Expose 'margin-bottom' attribute.
   styleInfo.MarginBottom(value);
-  nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::marginBottom, value);
-
-  return NS_OK;
+  nsAccUtils::SetAccAttr(attributes, nsGkAtoms::marginBottom, value);
+
+  return attributes.forget();
 }
 
 GroupPos
 Accessible::GroupPosition()
 {
   GroupPos groupPos;
 
   // Get group position from ARIA attributes.
--- a/accessible/src/generic/Accessible.h
+++ b/accessible/src/generic/Accessible.h
@@ -243,20 +243,19 @@ public:
   uint64_t VisibilityState();
 
   /**
    * Return true if native unavailable state present.
    */
   virtual bool NativelyUnavailable() const;
 
   /**
-   * Returns attributes for accessible without explicitly setted ARIA
-   * attributes.
+   * Return object attributes for the accessible.
    */
-  virtual nsresult GetAttributesInternal(nsIPersistentProperties *aAttributes);
+  virtual already_AddRefed<nsIPersistentProperties> Attributes();
 
   /**
    * Return group position (level, position in set and set size).
    */
   virtual mozilla::a11y::GroupPos GroupPosition();
 
   /**
    * Used by ChildAtPoint() method to get direct or deepest child at point.
@@ -707,16 +706,28 @@ public:
 
   /**
   * Return true if the accessible has a numeric value.
   */
   bool HasNumericValue() const;
 
 protected:
 
+  /**
+   * Return the accessible name provided by native markup. It doesn't take
+   * into account ARIA markup used to specify the name.
+   */
+  virtual mozilla::a11y::ENameValueFlag NativeName(nsString& aName);
+
+  /**
+   * Return object attributes provided by native markup. It doesn't take into
+   * account ARIA.
+   */
+  virtual already_AddRefed<nsIPersistentProperties> NativeAttributes();
+
   //////////////////////////////////////////////////////////////////////////////
   // Initializing, cache and tree traverse methods
 
   /**
    * Cache accessible children.
    */
   virtual void CacheChildren();
 
@@ -797,22 +808,16 @@ protected:
    * Return ARIA role (helper method).
    */
   mozilla::a11y::role ARIATransformRole(mozilla::a11y::role aRole);
 
   //////////////////////////////////////////////////////////////////////////////
   // Name helpers
 
   /**
-   * Return the accessible name provided by native markup. It doesn't take
-   * into account ARIA markup used to specify the name.
-   */
-  virtual mozilla::a11y::ENameValueFlag NativeName(nsString& aName);
-
-  /**
    * Returns the accessible name specified by ARIA.
    */
   void ARIAName(nsString& aName);
 
   /**
    * Compute the name of HTML/XUL node.
    */
   mozilla::a11y::ENameValueFlag GetHTMLName(nsString& aName);
--- a/accessible/src/generic/ApplicationAccessible.cpp
+++ b/accessible/src/generic/ApplicationAccessible.cpp
@@ -105,22 +105,20 @@ ApplicationAccessible::Value(nsString& a
 }
 
 uint64_t
 ApplicationAccessible::State()
 {
   return IsDefunct() ? states::DEFUNCT : 0;
 }
 
-NS_IMETHODIMP
-ApplicationAccessible::GetAttributes(nsIPersistentProperties** aAttributes)
+already_AddRefed<nsIPersistentProperties>
+ApplicationAccessible::NativeAttributes()
 {
-  NS_ENSURE_ARG_POINTER(aAttributes);
-  *aAttributes = nullptr;
-  return NS_OK;
+  return nullptr;
 }
 
 GroupPos
 ApplicationAccessible::GroupPosition()
 {
   return GroupPos();
 }
 
--- a/accessible/src/generic/ApplicationAccessible.h
+++ b/accessible/src/generic/ApplicationAccessible.h
@@ -40,17 +40,16 @@ public:
   // nsIAccessible
   NS_IMETHOD GetRootDocument(nsIAccessibleDocument** aRootDocument);
   NS_IMETHOD ScrollTo(uint32_t aScrollType);
   NS_IMETHOD ScrollToPoint(uint32_t aCoordinateType, int32_t aX, int32_t aY);
   NS_IMETHOD GetLanguage(nsAString& aLanguage);
   NS_IMETHOD GetParent(nsIAccessible **aParent);
   NS_IMETHOD GetNextSibling(nsIAccessible **aNextSibling);
   NS_IMETHOD GetPreviousSibling(nsIAccessible **aPreviousSibling);
-  NS_IMETHOD GetAttributes(nsIPersistentProperties **aAttributes);
   NS_IMETHOD GetBounds(int32_t *aX, int32_t *aY,
                        int32_t *aWidth, int32_t *aHeight);
   NS_IMETHOD SetSelected(bool aIsSelected);
   NS_IMETHOD TakeSelection();
   NS_IMETHOD TakeFocus();
   NS_IMETHOD GetActionName(uint8_t aIndex, nsAString &aName);
   NS_IMETHOD GetActionDescription(uint8_t aIndex, nsAString &aDescription);
   NS_IMETHOD DoAction(uint8_t aIndex);
@@ -58,16 +57,17 @@ public:
   // nsIAccessibleApplication
   NS_DECL_NSIACCESSIBLEAPPLICATION
 
   // nsAccessNode
   virtual void Init();
   virtual void Shutdown();
 
   // Accessible
+  virtual already_AddRefed<nsIPersistentProperties> NativeAttributes() MOZ_OVERRIDE;
   virtual GroupPos GroupPosition();
   virtual ENameValueFlag Name(nsString& aName);
   virtual void ApplyARIAState(uint64_t* aState) const;
   virtual void Description(nsString& aDescription);
   virtual void Value(nsString& aValue);
   virtual mozilla::a11y::role NativeRole();
   virtual uint64_t State();
   virtual uint64_t NativeState();
--- a/accessible/src/generic/DocAccessible.cpp
+++ b/accessible/src/generic/DocAccessible.cpp
@@ -334,27 +334,34 @@ DocAccessible::ApplyARIAState(uint64_t* 
 {
   // Combine with states from outer doc
   // 
   Accessible::ApplyARIAState(aState);
 
   // Allow iframe/frame etc. to have final state override via ARIA
   if (mParent)
     mParent->ApplyARIAState(aState);
-
 }
 
-NS_IMETHODIMP
-DocAccessible::GetAttributes(nsIPersistentProperties** aAttributes)
+already_AddRefed<nsIPersistentProperties>
+DocAccessible::Attributes()
 {
-  Accessible::GetAttributes(aAttributes);
-  if (mParent) {
-    mParent->GetAttributes(aAttributes); // Add parent attributes (override inner)
-  }
-  return NS_OK;
+  nsCOMPtr<nsIPersistentProperties> attributes =
+    HyperTextAccessibleWrap::Attributes();
+
+  if (!mParent)
+    return attributes.forget();
+
+  // Override ARIA object attributes from outerdoc.
+  aria::AttrIterator attribIter(mParent->GetContent());
+  nsAutoString name, value, unused;
+  while(attribIter.Next(name, value))
+    attributes->SetStringProperty(NS_ConvertUTF16toUTF8(name), value, unused);
+
+  return attributes.forget();
 }
 
 Accessible*
 DocAccessible::FocusedChild()
 {
   // Return an accessible for the current global focus, which does not have to
   // be contained within the current document.
   return FocusMgr()->FocusedAccessible();
--- a/accessible/src/generic/DocAccessible.h
+++ b/accessible/src/generic/DocAccessible.h
@@ -63,17 +63,16 @@ class DocAccessible : public HyperTextAc
 
 public:
 
   DocAccessible(nsIDocument* aDocument, nsIContent* aRootContent,
                 nsIPresShell* aPresShell);
   virtual ~DocAccessible();
 
   // nsIAccessible
-  NS_IMETHOD GetAttributes(nsIPersistentProperties** aAttributes);
   NS_IMETHOD TakeFocus(void);
 
   // nsIScrollPositionListener
   virtual void ScrollPositionWillChange(nscoord aX, nscoord aY) {}
   virtual void ScrollPositionDidChange(nscoord aX, nscoord aY);
 
   // nsIDocumentObserver
   NS_DECL_NSIDOCUMENTOBSERVER
@@ -89,16 +88,17 @@ public:
   virtual mozilla::a11y::ENameValueFlag Name(nsString& aName);
   virtual void Description(nsString& aDescription);
   virtual Accessible* FocusedChild();
   virtual mozilla::a11y::role NativeRole();
   virtual uint64_t NativeState();
   virtual uint64_t NativeInteractiveState() const;
   virtual bool NativelyUnavailable() const;
   virtual void ApplyARIAState(uint64_t* aState) const;
+  virtual already_AddRefed<nsIPersistentProperties> Attributes();
 
   virtual void SetRoleMapEntry(nsRoleMapEntry* aRoleMapEntry);
 
 #ifdef A11Y_LOG
   virtual nsresult HandleAccEvent(AccEvent* aEvent);
 #endif
 
   virtual void GetBoundsRect(nsRect& aRect, nsIFrame** aRelativeFrame);
--- a/accessible/src/generic/HyperTextAccessible.cpp
+++ b/accessible/src/generic/HyperTextAccessible.cpp
@@ -1130,64 +1130,61 @@ HyperTextAccessible::GetLevelInternal()
   if (tag == nsGkAtoms::h5)
     return 5;
   if (tag == nsGkAtoms::h6)
     return 6;
 
   return AccessibleWrap::GetLevelInternal();
 }
 
-nsresult
-HyperTextAccessible::GetAttributesInternal(nsIPersistentProperties* aAttributes)
+already_AddRefed<nsIPersistentProperties>
+HyperTextAccessible::NativeAttributes()
 {
-  nsresult rv = AccessibleWrap::GetAttributesInternal(aAttributes);
-  NS_ENSURE_SUCCESS(rv, rv);
+  nsCOMPtr<nsIPersistentProperties> attributes =
+    AccessibleWrap::NativeAttributes();
 
-  // Indicate when the current object uses block-level formatting
-  // via formatting: block
-  // XXX: 'formatting' attribute is deprecated and will be removed in Mozilla2,
-  // use 'display' attribute instead.
+  // 'formatting' attribute is deprecated, 'display' attribute should be
+  // instead.
   nsIFrame *frame = GetFrame();
   if (frame && frame->GetType() == nsGkAtoms::blockFrame) {
-    nsAutoString oldValueUnused;
-    aAttributes->SetStringProperty(NS_LITERAL_CSTRING("formatting"), NS_LITERAL_STRING("block"),
-                                   oldValueUnused);
+    nsAutoString unused;
+    attributes->SetStringProperty(NS_LITERAL_CSTRING("formatting"),
+                                  NS_LITERAL_STRING("block"), unused);
   }
 
   if (FocusMgr()->IsFocused(this)) {
     int32_t lineNumber = CaretLineNumber();
     if (lineNumber >= 1) {
       nsAutoString strLineNumber;
       strLineNumber.AppendInt(lineNumber);
-      nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::lineNumber,
-                             strLineNumber);
+      nsAccUtils::SetAccAttr(attributes, nsGkAtoms::lineNumber, strLineNumber);
     }
   }
 
   // For the html landmark elements we expose them like we do aria landmarks to
   // make AT navigation schemes "just work". Note html:header is redundant as
   // a landmark since it usually contains headings. We're not yet sure how the
   // web will use html:footer but our best bet right now is as contentinfo.
   if (mContent->Tag() == nsGkAtoms::nav)
-    nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::xmlroles,
+    nsAccUtils::SetAccAttr(attributes, nsGkAtoms::xmlroles,
                            NS_LITERAL_STRING("navigation"));
   else if (mContent->Tag() == nsGkAtoms::section) 
-    nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::xmlroles,
+    nsAccUtils::SetAccAttr(attributes, nsGkAtoms::xmlroles,
                            NS_LITERAL_STRING("region"));
   else if (mContent->Tag() == nsGkAtoms::footer) 
-    nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::xmlroles,
+    nsAccUtils::SetAccAttr(attributes, nsGkAtoms::xmlroles,
                            NS_LITERAL_STRING("contentinfo"));
   else if (mContent->Tag() == nsGkAtoms::aside) 
-    nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::xmlroles,
+    nsAccUtils::SetAccAttr(attributes, nsGkAtoms::xmlroles,
                            NS_LITERAL_STRING("complementary"));
   else if (mContent->Tag() == nsGkAtoms::article)
-    nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::xmlroles,
+    nsAccUtils::SetAccAttr(attributes, nsGkAtoms::xmlroles,
                            NS_LITERAL_STRING("article"));
 
-  return  NS_OK;
+  return attributes.forget();
 }
 
 /*
  * Given an offset, the x, y, width, and height values are filled appropriately.
  */
 NS_IMETHODIMP
 HyperTextAccessible::GetCharacterExtents(int32_t aOffset, int32_t* aX, int32_t* aY,
                                          int32_t* aWidth, int32_t* aHeight,
--- a/accessible/src/generic/HyperTextAccessible.h
+++ b/accessible/src/generic/HyperTextAccessible.h
@@ -46,17 +46,17 @@ public:
 
   NS_DECL_ISUPPORTS_INHERITED
   NS_DECL_NSIACCESSIBLETEXT
   NS_DECL_NSIACCESSIBLEHYPERTEXT
   NS_DECL_NSIACCESSIBLEEDITABLETEXT
 
   // Accessible
   virtual int32_t GetLevelInternal();
-  virtual nsresult GetAttributesInternal(nsIPersistentProperties *aAttributes);
+  virtual already_AddRefed<nsIPersistentProperties> NativeAttributes() MOZ_OVERRIDE;
   virtual mozilla::a11y::role NativeRole();
   virtual uint64_t NativeState();
 
   virtual void InvalidateChildren();
   virtual bool RemoveChild(Accessible* aAccessible);
 
   // HyperTextAccessible (static helper method)
 
--- a/accessible/src/generic/ImageAccessible.cpp
+++ b/accessible/src/generic/ImageAccessible.cpp
@@ -164,31 +164,28 @@ ImageAccessible::GetImagePosition(uint32
 NS_IMETHODIMP
 ImageAccessible::GetImageSize(int32_t* aWidth, int32_t* aHeight)
 {
   int32_t x, y;
   return GetBounds(&x, &y, aWidth, aHeight);
 }
 
 // Accessible
-nsresult
-ImageAccessible::GetAttributesInternal(nsIPersistentProperties* aAttributes)
+already_AddRefed<nsIPersistentProperties>
+ImageAccessible::NativeAttributes()
 {
-  if (IsDefunct())
-    return NS_ERROR_FAILURE;
-
-  nsresult rv = LinkableAccessible::GetAttributesInternal(aAttributes);
-  NS_ENSURE_SUCCESS(rv, rv);
+  nsCOMPtr<nsIPersistentProperties> attributes =
+    LinkableAccessible::NativeAttributes();
 
   nsAutoString src;
   mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::src, src);
   if (!src.IsEmpty())
-    nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::src, src);
+    nsAccUtils::SetAccAttr(attributes, nsGkAtoms::src, src);
 
-  return NS_OK;
+  return attributes.forget();
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // Private methods
 
 already_AddRefed<nsIURI>
 ImageAccessible::GetLongDescURI() const
 {
--- a/accessible/src/generic/ImageAccessible.h
+++ b/accessible/src/generic/ImageAccessible.h
@@ -33,17 +33,17 @@ public:
   NS_IMETHOD DoAction(uint8_t index);
 
   // nsIAccessibleImage
   NS_DECL_NSIACCESSIBLEIMAGE
 
   // Accessible
   virtual a11y::role NativeRole();
   virtual uint64_t NativeState();
-  virtual nsresult GetAttributesInternal(nsIPersistentProperties *aAttributes);
+  virtual already_AddRefed<nsIPersistentProperties> NativeAttributes() MOZ_OVERRIDE;
 
   // ActionAccessible
   virtual uint8_t ActionCount();
 
 protected:
   // Accessible
   virtual ENameValueFlag NativeName(nsString& aName) MOZ_OVERRIDE;
 
--- a/accessible/src/generic/OuterDocAccessible.cpp
+++ b/accessible/src/generic/OuterDocAccessible.cpp
@@ -62,29 +62,16 @@ OuterDocAccessible::ChildAtPoint(int32_t
   Accessible* child = GetChildAt(0);
   NS_ENSURE_TRUE(child, nullptr);
 
   if (aWhichChild == eDeepestChild)
     return child->ChildAtPoint(aX, aY, eDeepestChild);
   return child;
 }
 
-nsresult
-OuterDocAccessible::GetAttributesInternal(nsIPersistentProperties* aAttributes)
-{
-  nsAutoString tag;
-  aAttributes->GetStringProperty(NS_LITERAL_CSTRING("tag"), tag);
-  if (!tag.IsEmpty()) {
-    // We're overriding the ARIA attributes on an sub document, but we don't want to
-    // override the other attributes
-    return NS_OK;
-  }
-  return Accessible::GetAttributesInternal(aAttributes);
-}
-
 ////////////////////////////////////////////////////////////////////////////////
 // nsIAccessible
 
 uint8_t
 OuterDocAccessible::ActionCount()
 {
   // Internal frame, which is the doc's parent, should not have a click action.
   return 0;
--- a/accessible/src/generic/OuterDocAccessible.h
+++ b/accessible/src/generic/OuterDocAccessible.h
@@ -33,17 +33,16 @@ public:
   NS_IMETHOD GetActionDescription(uint8_t aIndex, nsAString& aDescription);
   NS_IMETHOD DoAction(uint8_t aIndex);
 
   // nsAccessNode
   virtual void Shutdown();
 
   // Accessible
   virtual mozilla::a11y::role NativeRole();
-  virtual nsresult GetAttributesInternal(nsIPersistentProperties *aAttributes);
   virtual Accessible* ChildAtPoint(int32_t aX, int32_t aY,
                                    EWhichChildAtPoint aWhichChild);
 
   virtual void InvalidateChildren();
   virtual bool AppendChild(Accessible* aAccessible);
   virtual bool RemoveChild(Accessible* aAccessible);
 
   // ActionAccessible
--- a/accessible/src/html/HTMLElementAccessibles.cpp
+++ b/accessible/src/html/HTMLElementAccessibles.cpp
@@ -84,20 +84,19 @@ HTMLOutputAccessible::RelationByType(uin
 }
 
 role
 HTMLOutputAccessible::NativeRole()
 {
   return roles::SECTION;
 }
 
-nsresult
-HTMLOutputAccessible::GetAttributesInternal(nsIPersistentProperties* aAttributes)
+already_AddRefed<nsIPersistentProperties>
+HTMLOutputAccessible::NativeAttributes()
 {
-  nsresult rv = AccessibleWrap::GetAttributesInternal(aAttributes);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::live,
+  nsCOMPtr<nsIPersistentProperties> attributes =
+    AccessibleWrap::NativeAttributes();
+  nsAccUtils::SetAccAttr(attributes, nsGkAtoms::live,
                          NS_LITERAL_STRING("polite"));
 
-  return NS_OK;
+  return attributes.forget();
 }
 
--- a/accessible/src/html/HTMLElementAccessibles.h
+++ b/accessible/src/html/HTMLElementAccessibles.h
@@ -72,16 +72,16 @@ public:
 
   HTMLOutputAccessible(nsIContent* aContent, DocAccessible* aDoc) :
     HyperTextAccessibleWrap(aContent, aDoc) {};
 
   NS_DECL_ISUPPORTS_INHERITED
 
   // Accessible
   virtual a11y::role NativeRole();
-  virtual nsresult GetAttributesInternal(nsIPersistentProperties* aAttributes);
+  virtual already_AddRefed<nsIPersistentProperties> NativeAttributes() MOZ_OVERRIDE;
   virtual Relation RelationByType(uint32_t aType);
 };
 
 } // namespace a11y
 } // namespace mozilla
 
 #endif
--- a/accessible/src/html/HTMLFormControlAccessible.cpp
+++ b/accessible/src/html/HTMLFormControlAccessible.cpp
@@ -670,26 +670,26 @@ HTMLLegendAccessible::NativeRole()
 ////////////////////////////////////////////////////////////////////////////////
 
 HTMLFigureAccessible::
   HTMLFigureAccessible(nsIContent* aContent, DocAccessible* aDoc) :
   HyperTextAccessibleWrap(aContent, aDoc)
 {
 }
 
-nsresult
-HTMLFigureAccessible::GetAttributesInternal(nsIPersistentProperties* aAttributes)
+already_AddRefed<nsIPersistentProperties>
+HTMLFigureAccessible::NativeAttributes()
 {
-  nsresult rv = HyperTextAccessibleWrap::GetAttributesInternal(aAttributes);
-  NS_ENSURE_SUCCESS(rv, rv);
+  nsCOMPtr<nsIPersistentProperties> attributes =
+    HyperTextAccessibleWrap::NativeAttributes();
 
   // Expose figure xml-role.
-  nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::xmlroles,
+  nsAccUtils::SetAccAttr(attributes, nsGkAtoms::xmlroles,
                          NS_LITERAL_STRING("figure"));
-  return NS_OK;
+  return attributes.forget();
 }
 
 role
 HTMLFigureAccessible::NativeRole()
 {
   return roles::FIGURE;
 }
 
--- a/accessible/src/html/HTMLFormControlAccessible.h
+++ b/accessible/src/html/HTMLFormControlAccessible.h
@@ -184,17 +184,17 @@ public:
  * Accessible for HTML5 figure element.
  */
 class HTMLFigureAccessible : public HyperTextAccessibleWrap
 {
 public:
   HTMLFigureAccessible(nsIContent* aContent, DocAccessible* aDoc);
 
   // Accessible
-  virtual nsresult GetAttributesInternal(nsIPersistentProperties* aAttributes);
+  virtual already_AddRefed<nsIPersistentProperties> NativeAttributes() MOZ_OVERRIDE;
   virtual mozilla::a11y::role NativeRole();
   virtual Relation RelationByType(uint32_t aType);
 
 protected:
   // Accessible
   virtual ENameValueFlag NativeName(nsString& aName) MOZ_OVERRIDE;
 
   // HTMLLegendAccessible
--- a/accessible/src/html/HTMLTableAccessible.cpp
+++ b/accessible/src/html/HTMLTableAccessible.cpp
@@ -88,37 +88,35 @@ HTMLTableCellAccessible::NativeState()
 }
 
 uint64_t
 HTMLTableCellAccessible::NativeInteractiveState() const
 {
   return HyperTextAccessibleWrap::NativeInteractiveState() | states::SELECTABLE;
 }
 
-nsresult
-HTMLTableCellAccessible::GetAttributesInternal(nsIPersistentProperties* aAttributes)
+already_AddRefed<nsIPersistentProperties>
+HTMLTableCellAccessible::NativeAttributes()
 {
-  if (IsDefunct())
-    return NS_ERROR_FAILURE;
-
-  nsresult rv = HyperTextAccessibleWrap::GetAttributesInternal(aAttributes);
-  NS_ENSURE_SUCCESS(rv, rv);
+  nsCOMPtr<nsIPersistentProperties> attributes =
+    HyperTextAccessibleWrap::NativeAttributes();
 
   // table-cell-index attribute
   TableAccessible* table = Table();
   if (!table)
-    return NS_OK;
+    return attributes.forget();
 
   int32_t rowIdx = -1, colIdx = -1;
-  rv = GetCellIndexes(rowIdx, colIdx);
-  NS_ENSURE_SUCCESS(rv, rv);
+  nsresult rv = GetCellIndexes(rowIdx, colIdx);
+  if (NS_FAILED(rv))
+    return attributes.forget();
 
   nsAutoString stringIdx;
   stringIdx.AppendInt(table->CellIndexAt(rowIdx, colIdx));
-  nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::tableCellIndex, stringIdx);
+  nsAccUtils::SetAccAttr(attributes, nsGkAtoms::tableCellIndex, stringIdx);
 
   // abbr attribute
 
   // Pick up object attribute from abbr DOM element (a child of the cell) or
   // from abbr DOM attribute.
   nsAutoString abbrText;
   if (ChildCount() == 1) {
     Accessible* abbr = FirstChild();
@@ -127,25 +125,25 @@ HTMLTableCellAccessible::GetAttributesIn
         AppendTextEquivFromTextContent(abbr->GetContent()->GetFirstChild(),
                                        &abbrText);
     }
   }
   if (abbrText.IsEmpty())
     mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::abbr, abbrText);
 
   if (!abbrText.IsEmpty())
-    nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::abbr, abbrText);
+    nsAccUtils::SetAccAttr(attributes, nsGkAtoms::abbr, abbrText);
 
   // axis attribute
   nsAutoString axisText;
   mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::axis, axisText);
   if (!axisText.IsEmpty())
-    nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::axis, axisText);
+    nsAccUtils::SetAccAttr(attributes, nsGkAtoms::axis, axisText);
 
-  return NS_OK;
+  return attributes.forget();
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // HTMLTableCellAccessible: nsIAccessibleTableCell implementation
 
 TableAccessible*
 HTMLTableCellAccessible::Table() const
 {
@@ -403,29 +401,28 @@ HTMLTableAccessible::NativeName(nsString
     }
   }
 
   // If no caption then use summary as a name.
   mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::summary, aName);
   return eNameOK;
 }
 
-nsresult
-HTMLTableAccessible::GetAttributesInternal(nsIPersistentProperties* aAttributes)
+already_AddRefed<nsIPersistentProperties>
+HTMLTableAccessible::NativeAttributes()
 {
-  nsresult rv = AccessibleWrap::GetAttributesInternal(aAttributes);
-  NS_ENSURE_SUCCESS(rv, rv);
-
+  nsCOMPtr<nsIPersistentProperties> attributes =
+    AccessibleWrap::NativeAttributes();
   if (IsProbablyLayoutTable()) {
-    nsAutoString oldValueUnused;
-    aAttributes->SetStringProperty(NS_LITERAL_CSTRING("layout-guess"),
-                                   NS_LITERAL_STRING("true"), oldValueUnused);
+    nsAutoString unused;
+    attributes->SetStringProperty(NS_LITERAL_CSTRING("layout-guess"),
+                                  NS_LITERAL_STRING("true"), unused);
   }
 
-  return NS_OK;
+  return attributes.forget();
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // HTMLTableAccessible: nsIAccessible implementation
 
 Relation
 HTMLTableAccessible::RelationByType(uint32_t aType)
 {
--- a/accessible/src/html/HTMLTableAccessible.h
+++ b/accessible/src/html/HTMLTableAccessible.h
@@ -37,17 +37,17 @@ public:
   NS_FORWARD_NSIACCESSIBLETABLECELL(xpcAccessibleTableCell::)
 
   // Accessible
   virtual TableCellAccessible* AsTableCell() { return this; }
   virtual void Shutdown();
   virtual a11y::role NativeRole();
   virtual uint64_t NativeState();
   virtual uint64_t NativeInteractiveState() const;
-  virtual nsresult GetAttributesInternal(nsIPersistentProperties *aAttributes);
+  virtual already_AddRefed<nsIPersistentProperties> NativeAttributes() MOZ_OVERRIDE;
 
   // TableCellAccessible
   virtual TableAccessible* Table() const MOZ_OVERRIDE;
   virtual uint32_t ColIdx() const MOZ_OVERRIDE;
   virtual uint32_t RowIdx() const MOZ_OVERRIDE;
   virtual uint32_t ColExtent() const MOZ_OVERRIDE;
   virtual uint32_t RowExtent() const MOZ_OVERRIDE;
   virtual void ColHeaderCells(nsTArray<Accessible*>* aCells) MOZ_OVERRIDE;
@@ -140,17 +140,17 @@ public:
   // nsAccessNode
   virtual void Shutdown();
 
   // Accessible
   virtual TableAccessible* AsTable() { return this; }
   virtual void Description(nsString& aDescription);
   virtual a11y::role NativeRole();
   virtual uint64_t NativeState();
-  virtual nsresult GetAttributesInternal(nsIPersistentProperties *aAttributes);
+  virtual already_AddRefed<nsIPersistentProperties> NativeAttributes() MOZ_OVERRIDE;
   virtual Relation RelationByType(uint32_t aRelationType);
 
   // HTMLTableAccessible
 
   /**
    * Retun cell element at the given row and column index.
    */
   nsresult GetCellAt(int32_t aRowIndex, int32_t aColIndex,
--- a/accessible/src/mac/mozAccessible.mm
+++ b/accessible/src/mac/mozAccessible.mm
@@ -434,21 +434,20 @@ GetClosestInterestingAccessible(id anObj
 
 - (NSString*)subrole
 {
   if (!mGeckoAccessible)
     return nil;
 
   // XXX maybe we should cache the subrole.
   nsAutoString xmlRoles;
-  nsCOMPtr<nsIPersistentProperties> attributes;
 
   // XXX we don't need all the attributes (see bug 771113)
-  nsresult rv = mGeckoAccessible->GetAttributes(getter_AddRefs(attributes));
-  if (NS_SUCCEEDED(rv) && attributes)
+  nsCOMPtr<nsIPersistentProperties> attributes = mGeckoAccessible->Attributes();
+  if (attributes)
     nsAccUtils::GetAccAttr(attributes, nsGkAtoms::xmlroles, xmlRoles);
 
   nsWhitespaceTokenizer tokenizer(xmlRoles);
 
   while (tokenizer.hasMoreTokens()) {
     const nsDependentSubstring token(tokenizer.nextToken());
 
     if (token.EqualsLiteral("banner"))
--- a/accessible/src/msaa/AccessibleWrap.cpp
+++ b/accessible/src/msaa/AccessibleWrap.cpp
@@ -1435,21 +1435,17 @@ AccessibleWrap::get_attributes(BSTR *aAt
   // The format is name:value;name:value; with \ for escaping these
   // characters ":;=,\".
 __try {
   *aAttributes = NULL;
 
   if (IsDefunct())
     return CO_E_OBJNOTCONNECTED;
 
-  nsCOMPtr<nsIPersistentProperties> attributes;
-  nsresult rv = GetAttributes(getter_AddRefs(attributes));
-  if (NS_FAILED(rv))
-    return GetHRESULT(rv);
-
+  nsCOMPtr<nsIPersistentProperties> attributes = Attributes();
   return ConvertToIA2Attributes(attributes, aAttributes);
 
 } __except(nsAccessNodeWrap::FilterA11yExceptions(::GetExceptionCode(), GetExceptionInformation())) { }
   return E_FAIL;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // IDispatch
--- a/accessible/src/msaa/ApplicationAccessibleWrap.cpp
+++ b/accessible/src/msaa/ApplicationAccessibleWrap.cpp
@@ -16,39 +16,34 @@
 using namespace mozilla;
 using namespace mozilla::a11y;
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsISupports
 NS_IMPL_ISUPPORTS_INHERITED0(ApplicationAccessibleWrap,
                              ApplicationAccessible)
 
-NS_IMETHODIMP
-ApplicationAccessibleWrap::GetAttributes(nsIPersistentProperties** aAttributes)
+already_AddRefed<nsIPersistentProperties>
+ApplicationAccessibleWrap::NativeAttributes()
 {
-  NS_ENSURE_ARG_POINTER(aAttributes);
-  *aAttributes = nullptr;
-
   nsCOMPtr<nsIPersistentProperties> attributes =
     do_CreateInstance(NS_PERSISTENTPROPERTIES_CONTRACTID);
-  NS_ENSURE_STATE(attributes);
 
   nsCOMPtr<nsIGfxInfo> gfxInfo = do_GetService("@mozilla.org/gfx/info;1");
   if (gfxInfo) {
     bool isD2DEnabled = false;
     gfxInfo->GetD2DEnabled(&isD2DEnabled);
     nsAutoString unused;
     attributes->SetStringProperty(
       NS_LITERAL_CSTRING("D2D"),
       isD2DEnabled ? NS_LITERAL_STRING("true") : NS_LITERAL_STRING("false"),
         unused);
   }
 
-  attributes.swap(*aAttributes);
-  return NS_OK;
+  return attributes.forget();
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // IUnknown
 
 STDMETHODIMP
 ApplicationAccessibleWrap::QueryInterface(REFIID iid, void** ppv)
 {
--- a/accessible/src/msaa/ApplicationAccessibleWrap.h
+++ b/accessible/src/msaa/ApplicationAccessibleWrap.h
@@ -17,18 +17,18 @@ namespace a11y {
  
 class ApplicationAccessibleWrap: public ApplicationAccessible,
                                  public IAccessibleApplication
 {
 public:
   // nsISupporst
   NS_DECL_ISUPPORTS_INHERITED
 
-  // nsIAccessible
-  NS_IMETHOD GetAttributes(nsIPersistentProperties** aAttributes);
+  // nsAccessible
+  virtual already_AddRefed<nsIPersistentProperties> NativeAttributes() MOZ_OVERRIDE;
 
   // IUnknown
   STDMETHODIMP QueryInterface(REFIID, void**);
 
   // IAccessibleApplication
   virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_appName(
             /* [retval][out] */ BSTR *name);
 
--- a/accessible/src/windows/uia/uiaRawElmProvider.cpp
+++ b/accessible/src/windows/uia/uiaRawElmProvider.cpp
@@ -183,18 +183,17 @@ uiaRawElmProvider::GetPropertyValue(PROP
 
       break;
     }
     
     //ARIA Role / shortcut
     case UIA_AriaRolePropertyId: {
       nsAutoString xmlRoles;
 
-      nsCOMPtr<nsIPersistentProperties> attributes;
-      mAcc->GetAttributes(getter_AddRefs(attributes));
+      nsCOMPtr<nsIPersistentProperties> attributes = mAcc->Attributes();
       attributes->GetStringProperty(NS_LITERAL_CSTRING("xml-roles"), xmlRoles);
 
       if(!xmlRoles.IsEmpty()) {
         aPropertyValue->vt = VT_BSTR;
         aPropertyValue->bstrVal = ::SysAllocString(xmlRoles.get());
         return S_OK;
       }
 
--- a/accessible/src/xul/XULListboxAccessible.cpp
+++ b/accessible/src/xul/XULListboxAccessible.cpp
@@ -852,27 +852,25 @@ XULListCellAccessible::Shutdown()
 }
 
 role
 XULListCellAccessible::NativeRole()
 {
   return roles::CELL;
 }
 
-nsresult
-XULListCellAccessible::GetAttributesInternal(nsIPersistentProperties* aAttributes)
+already_AddRefed<nsIPersistentProperties>
+XULListCellAccessible::NativeAttributes()
 {
-  NS_ENSURE_ARG_POINTER(aAttributes);
-
-  if (IsDefunct())
-    return NS_ERROR_FAILURE;
+  nsCOMPtr<nsIPersistentProperties> attributes =
+    HyperTextAccessibleWrap::NativeAttributes();
 
   // "table-cell-index" attribute
   TableAccessible* table = Table();
-  NS_ENSURE_STATE(table); // we expect to be in a listbox (table)
+  if (!table) // we expect to be in a listbox (table)
+    return attributes.forget();
 
   nsAutoString stringIdx;
   stringIdx.AppendInt(table->CellIndexAt(RowIdx(), ColIdx()));
-  nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::tableCellIndex,
-                         stringIdx);
+  nsAccUtils::SetAccAttr(attributes, nsGkAtoms::tableCellIndex, stringIdx);
 
-  return NS_OK;
+  return attributes.forget();
 }
--- a/accessible/src/xul/XULListboxAccessible.h
+++ b/accessible/src/xul/XULListboxAccessible.h
@@ -169,17 +169,17 @@ public:
   NS_DECL_ISUPPORTS_INHERITED
 
   // nsIAccessibleTableCell
   NS_FORWARD_NSIACCESSIBLETABLECELL(xpcAccessibleTableCell::)
 
   // Accessible
   virtual TableCellAccessible* AsTableCell() { return this; }
   virtual void Shutdown();
-  virtual nsresult GetAttributesInternal(nsIPersistentProperties *aAttributes);
+  virtual already_AddRefed<nsIPersistentProperties> NativeAttributes() MOZ_OVERRIDE;
   virtual a11y::role NativeRole();
 
   // TableCellAccessible
   virtual TableAccessible* Table() const MOZ_OVERRIDE;
   virtual uint32_t ColIdx() const MOZ_OVERRIDE;
   virtual uint32_t RowIdx() const MOZ_OVERRIDE;
   virtual void ColHeaderCells(nsTArray<Accessible*>* aHeaderCells) MOZ_OVERRIDE;
   virtual bool Selected() MOZ_OVERRIDE;
--- a/accessible/src/xul/XULTreeGridAccessible.cpp
+++ b/accessible/src/xul/XULTreeGridAccessible.cpp
@@ -722,41 +722,39 @@ XULTreeGridCellAccessible::Init()
     mTreeView->GetCellValue(mRow, mColumn, mCachedTextEquiv);
   else
     mTreeView->GetCellText(mRow, mColumn, mCachedTextEquiv);
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // XULTreeGridCellAccessible: Accessible public implementation
 
-nsresult
-XULTreeGridCellAccessible::GetAttributesInternal(nsIPersistentProperties* aAttributes)
+already_AddRefed<nsIPersistentProperties>
+XULTreeGridCellAccessible::NativeAttributes()
 {
-  NS_ENSURE_ARG_POINTER(aAttributes);
-
-  if (IsDefunct())
-    return NS_ERROR_FAILURE;
+  nsCOMPtr<nsIPersistentProperties> attributes =
+    do_CreateInstance(NS_PERSISTENTPROPERTIES_CONTRACTID);
 
   // "table-cell-index" attribute
   TableAccessible* table = Table();
   if (!table)
-    return NS_ERROR_FAILURE;
+    return attributes.forget();
 
   nsAutoString stringIdx;
   stringIdx.AppendInt(table->CellIndexAt(mRow, ColIdx()));
-  nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::tableCellIndex, stringIdx);
+  nsAccUtils::SetAccAttr(attributes, nsGkAtoms::tableCellIndex, stringIdx);
 
   // "cycles" attribute
   bool isCycler = false;
   nsresult rv = mColumn->GetCycler(&isCycler);
   if (NS_SUCCEEDED(rv) && isCycler)
-    nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::cycles,
+    nsAccUtils::SetAccAttr(attributes, nsGkAtoms::cycles,
                            NS_LITERAL_STRING("true"));
 
-  return NS_OK;
+  return attributes.forget();
 }
 
 role
 XULTreeGridCellAccessible::NativeRole()
 {
   return roles::GRID_CELL;
 }
 
--- a/accessible/src/xul/XULTreeGridAccessible.h
+++ b/accessible/src/xul/XULTreeGridAccessible.h
@@ -153,17 +153,17 @@ public:
   // nsAccessNode
   virtual void Init();
 
   // Accessible
   virtual TableCellAccessible* AsTableCell() { return this; }
   virtual void Shutdown();
   virtual ENameValueFlag Name(nsString& aName);
   virtual Accessible* FocusedChild();
-  virtual nsresult GetAttributesInternal(nsIPersistentProperties* aAttributes);
+  virtual already_AddRefed<nsIPersistentProperties> NativeAttributes() MOZ_OVERRIDE;
   virtual int32_t IndexInParent() const;
   virtual Relation RelationByType(uint32_t aType);
   virtual a11y::role NativeRole();
   virtual uint64_t NativeState();
   virtual uint64_t NativeInteractiveState() const;
 
   // ActionAccessible
   virtual uint8_t ActionCount();
--- a/accessible/tests/mochitest/attributes/test_obj.html
+++ b/accessible/tests/mochitest/attributes/test_obj.html
@@ -33,18 +33,22 @@ https://bugzilla.mozilla.org/show_bug.cg
       testAttrs("dropeffect", {"dropeffect" : "copy"}, true);
       testAttrs("grabbed", {"grabbed" : "true"}, true);
       testAttrs("hidden", {"hidden" : "true"}, true);
       testAttrs("sortAscending", {"sort" : "ascending"}, true);
       testAttrs("sortDescending", {"sort" : "descending"}, true);
       testAttrs("sortNone", {"sort" : "none"}, true);
       testAttrs("sortOther", {"sort" : "other"}, true);
 
+      // inherited attributes by subdocuments
+      var subdoc = getAccessible("iframe").firstChild;
+      testAttrs(subdoc, {"busy" : "true"}, true);
+
       // live object attribute
-      
+
       // HTML
       testAttrs("output", {"live" : "polite"}, true);
 
       // ARIA
       testAttrs("live", {"live" : "polite"}, true);
       testAttrs("live2", {"live" : "polite"}, true);
       testAbsentAttrs("live3", {"live" : ""});
       testAttrs("log", {"live" : "polite"}, true);
@@ -167,16 +171,20 @@ https://bugzilla.mozilla.org/show_bug.cg
   <div id="dropeffect" aria-dropeffect="copy"></div>
   <div id="grabbed" aria-grabbed="true"></div>
   <div id="hidden" aria-hidden="true"></div>
   <div id="sortAscending" role="columnheader" aria-sort="ascending"></div>
   <div id="sortDescending" role="columnheader" aria-sort="descending"></div>
   <div id="sortNone" role="columnheader" aria-sort="none"></div>
   <div id="sortOther" role="columnheader" aria-sort="other"></div>
 
+  <!-- inherited from iframe -->
+  <iframe id="iframe" src="data:text/html,<html><body></body></html>"
+          aria-busy="true"></iframe>
+
   <!-- html -->
   <output id="output"></output>
 
   <!-- back to aria -->
   <div id="live" aria-live="polite">excuse <div id="liveChild">me</div></div>
   <div id="live2" role="marquee" aria-live="polite">excuse <div id="live2Child">me</div></div>
   <div id="live3" role="region">excuse</div>
   <div id="log" role="log">excuse <div id="logChild">me</div></div>
--- a/b2g/components/YoutubeProtocolHandler.js
+++ b/b2g/components/YoutubeProtocolHandler.js
@@ -70,37 +70,44 @@ YoutubeProtocolHandler.prototype = {
       if (pos == -1) {
         return;
       }
       let streams = decodeURIComponent(xhr.responseText
                                        .substring(pos + key.length)).split(",");
       let uri;
       let mimeType;
 
-      // Recognized mime types, ordered from the less usable to the most usable.
-      let recognizedTypes = ["video/webm"];
+      // itag is an undocumented value which maps to resolution and mimetype
+      // see https://en.wikipedia.org/wiki/YouTube#Quality_and_codecs
+      // Ordered from least to most preferred
+      let recognizedItags = [
+        "17", // 144p 3GP
+        "36", // 240p 3GP
+        "43", // 360p WebM
 #ifdef MOZ_WIDGET_GONK
-      recognizedTypes.push("video/mp4");
+        "18", // 360p H.264
 #endif
+      ];
 
-      let bestType = -1;
+      let bestItag = -1;
 
       let extras = { }
 
       streams.forEach(function(aStream) {
         let params = extractParameters(aStream);
         let url = params["url"];
         let type = params["type"] ? params["type"].split(";")[0] : null;
+        let itag = params["itag"];
 
         let index;
-        if (url && type && ((index = recognizedTypes.indexOf(type)) != -1) &&
-            index > bestType) {
+        if (url && type && ((index = recognizedItags.indexOf(itag)) != -1) &&
+            index > bestItag) {
           uri = url + '&signature=' + (params["sig"] ? params['sig'] : '');
           mimeType = type;
-          bestType = index;
+          bestItag = index;
         }
         for (let param in params) {
           if (["thumbnail_url", "length_seconds", "title"].indexOf(param) != -1) {
             extras[param] = decodeURIComponent(params[param]);
           }
         }
       });
 
--- a/browser/base/content/browser.xul
+++ b/browser/base/content/browser.xul
@@ -1073,17 +1073,18 @@
       </toolbar>
       <deck id="devtools-sidebar-deck" flex="1"/>
     </vbox>
     <splitter id="social-sidebar-splitter"
               class="chromeclass-extrachrome sidebar-splitter"
               observes="socialSidebarBroadcaster"/>
     <vbox id="social-sidebar-box"
           class="chromeclass-extrachrome"
-          observes="socialSidebarBroadcaster">
+          observes="socialSidebarBroadcaster"
+          persist="width">
       <browser id="social-sidebar-browser"
                type="content"
                disableglobalhistory="true"
                flex="1"
                style="min-width: 14em; width: 18em; max-width: 36em;"/>
     </vbox>
     <vbox id="browser-border-end" hidden="true" layer="true"/>
   </hbox>
--- a/build/automation.py.in
+++ b/build/automation.py.in
@@ -443,17 +443,17 @@ user_pref("extensions.webservice.discove
 // Make sure AddonRepository won't hit the network
 user_pref("extensions.getAddons.maxResults", 0);
 user_pref("extensions.getAddons.get.url", "http://%(server)s/extensions-dummy/repositoryGetURL");
 user_pref("extensions.getAddons.getWithPerformance.url", "http://%(server)s/extensions-dummy/repositoryGetWithPerformanceURL");
 user_pref("extensions.getAddons.search.browseURL", "http://%(server)s/extensions-dummy/repositoryBrowseURL");
 user_pref("extensions.getAddons.search.url", "http://%(server)s/extensions-dummy/repositorySearchURL");
 
 // Make enablePrivilege continue to work for test code. :-(
-user_pref("security.enablePrivilege.enable_for_tests", true);
+user_pref("security.turn_off_all_security_so_that_viruses_can_take_over_this_computer", true);
 
 // Get network events.
 user_pref("network.activity.blipIntervalMilliseconds", 250);
 """ % { "server" : self.webServer + ":" + str(self.httpPort) }
     prefs.append(part)
 
     if useServerLocations:
       # We need to proxy every server but the primary one.
--- a/caps/src/nsSecurityManagerFactory.cpp
+++ b/caps/src/nsSecurityManagerFactory.cpp
@@ -108,17 +108,17 @@ nsSecurityNameSet::InitializeNameSet(nsI
     }
 
     // We hide enablePrivilege behind a pref because it has been altered in a
     // way that makes it fundamentally insecure to use in production. Mozilla
     // uses this pref during automated testing to support legacy test code that
     // uses enablePrivilege. If you're not doing test automation, you _must_ not
     // flip this pref, or you will be exposing all your users to security
     // vulnerabilities.
-    if (!Preferences::GetBool("security.enablePrivilege.enable_for_tests"))
+    if (!Preferences::GetBool("security.turn_off_all_security_so_that_viruses_can_take_over_this_computer"))
         return NS_OK;
 
     /* Define PrivilegeManager object with the necessary "static" methods. */
     obj = JS_DefineObject(cx, securityObj, "PrivilegeManager", objectClass,
                           nullptr, 0);
     if (obj == nullptr)
         return NS_ERROR_FAILURE;
 
--- a/configure.in
+++ b/configure.in
@@ -7566,17 +7566,17 @@ dnl Omnijar packaging is compatible with
 dnl In unpackaged builds, omnijar looks for files as if
 dnl things were flat packaged. After packaging, all files
 dnl are loaded from a single jar. MOZ_CHROME_FILE_FORMAT
 dnl is set to flat since putting files into jars is only
 dnl done during packaging with omnijar.
 if test "$MOZ_CHROME_FILE_FORMAT" = "omni"; then
     MOZ_OMNIJAR=1
     AC_DEFINE(MOZ_OMNIJAR)
-    if test "$OS_ARCH" = "WINNT" -o "$OS_ARCH" = "OS2" -o "$OS_TARGET" = "Android"; then
+    if test "$OS_ARCH" = "WINNT" -o "$OS_ARCH" = "OS2" -o "$MOZ_WIDGET_TOOLKIT" = "android"; then
         MOZ_CHROME_FILE_FORMAT=flat
     else
         MOZ_CHROME_FILE_FORMAT=symlink
     fi
 elif test "$MOZ_CHROME_FILE_FORMAT" = "jar"; then
     AC_DEFINE(MOZ_CHROME_FILE_FORMAT_JAR)
 fi
 
--- a/content/base/public/nsContentUtils.h
+++ b/content/base/public/nsContentUtils.h
@@ -479,16 +479,20 @@ public:
    * Get the cache security manager service. Can return null if the layout
    * module has been shut down.
    */
   static nsIScriptSecurityManager* GetSecurityManager()
   {
     return sSecurityManager;
   }
 
+  // Returns the subject principal. Guaranteed to return non-null. May only
+  // be called when nsContentUtils is initialized.
+  static nsIPrincipal* GetSubjectPrincipal();
+
   static nsresult GenerateStateKey(nsIContent* aContent,
                                    const nsIDocument* aDocument,
                                    nsIStatefulFrame::SpecialStateID aID,
                                    nsACString& aKey);
 
   /**
    * Create a new nsIURI from aSpec, using aBaseURI as the base.  The
    * origin charset of the new nsIURI will be the document charset of
--- a/content/base/src/nsContentUtils.cpp
+++ b/content/base/src/nsContentUtils.cpp
@@ -2349,16 +2349,30 @@ nsContentUtils::GenerateStateKey(nsICont
       parent = content->GetNodeParent();
     }
   }
 
   return NS_OK;
 }
 
 // static
+nsIPrincipal*
+nsContentUtils::GetSubjectPrincipal()
+{
+  nsCOMPtr<nsIPrincipal> subject;
+  sSecurityManager->GetSubjectPrincipal(getter_AddRefs(subject));
+
+  // When the ssm says the subject is null, that means system principal.
+  if (!subject)
+    sSecurityManager->GetSystemPrincipal(getter_AddRefs(subject));
+
+  return subject;
+}
+
+// static
 nsresult
 nsContentUtils::NewURIWithDocumentCharset(nsIURI** aResult,
                                           const nsAString& aSpec,
                                           nsIDocument* aDocument,
                                           nsIURI* aBaseURI)
 {
   return NS_NewURI(aResult, aSpec,
                    aDocument ? aDocument->GetDocumentCharacterSet().get() : nullptr,
--- a/content/media/test/manifest.js
+++ b/content/media/test/manifest.js
@@ -5,39 +5,39 @@
 // These are small test files, good for just seeing if something loads. We
 // really only need one test file per backend here.
 var gSmallTests = [
   { name:"small-shot.ogg", type:"audio/ogg", duration:0.276 },
   { name:"r11025_s16_c1.wav", type:"audio/x-wav", duration:1.0 },
   { name:"320x240.ogv", type:"video/ogg", width:320, height:240, duration:0.266 },
   { name:"seek.webm", type:"video/webm", width:320, height:240, duration:3.966 },
   { name:"detodos.opus", type:"audio/ogg; codecs=opus", duration:2.9135 },
-  { name:"gizmo.mp4", type:"video/mp4", duration:5.0 },
+  { name:"gizmo.mp4", type:"video/mp4", duration:5.56 },
   { name:"bogus.duh", type:"bogus/duh" }
 ];
 
 // Used by test_progress to ensure we get the correct progress information
 // during resource download.
 var gProgressTests = [
   { name:"r11025_u8_c1.wav", type:"audio/x-wav", duration:1.0, size:11069 },
   { name:"big.wav", type:"audio/x-wav", duration:9.278981, size:102444 },
   { name:"seek.ogv", type:"video/ogg", duration:3.966, size:285310 },
   { name:"320x240.ogv", type:"video/ogg", width:320, height:240, duration:0.266, size:28942 },
   { name:"seek.webm", type:"video/webm", duration:3.966, size:215529 },
-  { name:"gizmo.mp4", type:"video/mp4", duration:5.0, size:383631 },
+  { name:"gizmo.mp4", type:"video/mp4", duration:5.56, size:383631 },
   { name:"bogus.duh", type:"bogus/duh" }
 ];
 
 // Used by test_played.html
 var gPlayedTests = [
   { name:"big.wav", type:"audio/x-wav", duration:9.0 },
   { name:"sound.ogg", type:"audio/ogg", duration:4.0 },
   { name:"seek.ogv", type:"video/ogg", duration:3.966 },
   { name:"seek.webm", type:"video/webm", duration:3.966 },
-  { name:"gizmo.mp4", type:"video/mp4", duration:5.0 },
+  { name:"gizmo.mp4", type:"video/mp4", duration:5.56 },
 ];
 
 // Used by test_mozLoadFrom.  Need one test file per decoder backend, plus
 // anything for testing clone-specific bugs.
 var cloneKey = Math.floor(Math.random()*100000000);
 var gCloneTests = gSmallTests.concat([
   // Actual duration is ~200ms, we have Content-Duration lie about it.
   { name:"bug520908.ogv", type:"video/ogg", duration:9000 },
@@ -145,17 +145,17 @@ var gPlayTests = [
   // A really short, low sample rate, single channel file. This tests whether
   // we can handle playing files when only push very little audio data to the
   // hardware.
   { name:"spacestorm-1000Hz-100ms.ogg", type:"audio/ogg", duration:0.099 },
 
   // Opus data in an ogg container
   { name:"detodos.opus", type:"audio/ogg; codecs=opus", duration:2.9135 },
 
-  { name:"gizmo.mp4", type:"video/mp4", duration:5.0 },
+  { name:"gizmo.mp4", type:"video/mp4", duration:5.56 },
 
   // Invalid file
   { name:"bogus.duh", type:"bogus/duh", duration:Number.NaN }
 ];
 
 // A file for each type we can support.
 var gSnifferTests = [
   { name:"big.wav", type:"audio/x-wav", duration:9.278981, size:102444 },
--- a/content/xtf/src/nsXTFWeakTearoff.cpp
+++ b/content/xtf/src/nsXTFWeakTearoff.cpp
@@ -118,17 +118,17 @@ nsXTFWeakTearoff::CallMethod(uint16_t me
   else {
     fullPars = new nsXPTCVariant[paramCount];
     if (!fullPars)
       return NS_ERROR_OUT_OF_MEMORY;
   }
 
   for (int i=0; i<paramCount; ++i) {
     const nsXPTParamInfo& paramInfo = info->params[i];
-    uint8 flags = paramInfo.IsOut() ? nsXPTCVariant::PTR_IS_DATA : 0;
+    uint8_t flags = paramInfo.IsOut() ? nsXPTCVariant::PTR_IS_DATA : 0;
     fullPars[i].Init(params[i], paramInfo.GetType(), flags);
   }
   
   // make the call:
   nsresult rv = NS_InvokeByIndex(mObj, methodIndex, paramCount, fullPars);
   if (fullPars)
     delete []fullPars;
   return rv;
--- a/docshell/shistory/src/nsSHistory.cpp
+++ b/docshell/shistory/src/nsSHistory.cpp
@@ -282,17 +282,17 @@ nsSHistory::CalcMaxTotalViewers()
   // 1024 Mb       8
   // 2048 Mb       8
   // 4096 Mb       8
   uint64_t bytes = PR_GetPhysicalMemorySize();
 
   if (bytes == 0)
     return 0;
 
-  // Conversion from unsigned int64 to double doesn't work on all platforms.
+  // Conversion from unsigned int64_t to double doesn't work on all platforms.
   // We need to truncate the value at INT64_MAX to make sure we don't
   // overflow.
   if (bytes > INT64_MAX)
     bytes = INT64_MAX;
 
   uint64_t kbytes;
   LL_SHR(kbytes, bytes, 10);
 
--- a/dom/activities/src/ActivitiesService.jsm
+++ b/dom/activities/src/ActivitiesService.jsm
@@ -81,41 +81,45 @@ ActivitiesDb.prototype = {
     ["manifest", "name"].forEach(function(aProp) {
       let data = converter.convertToByteArray(aObject[aProp], {});
       hasher.update(data, data.length);
     });
 
     return hasher.finish(true);
   },
 
-  add: function actdb_add(aObject, aSuccess, aError) {
+  // Add all the activities carried in the |aObjects| array.
+  add: function actdb_add(aObjects, aSuccess, aError) {
     this.newTxn("readwrite", function (txn, store) {
-      let object = {
-        manifest: aObject.manifest,
-        name: aObject.name,
-        title: aObject.title || "",
-        icon: aObject.icon || "",
-        description: aObject.description
-      };
-      object.id = this.createId(object);
-      debug("Going to add " + JSON.stringify(object));
-
-      store.put(object);
+      aObjects.forEach(function (aObject) {
+        let object = {
+          manifest: aObject.manifest,
+          name: aObject.name,
+          title: aObject.title || "",
+          icon: aObject.icon || "",
+          description: aObject.description
+        };
+        object.id = this.createId(object);
+        debug("Going to add " + JSON.stringify(object));
+        store.put(object);
+      }, this);
     }.bind(this), aSuccess, aError);
   },
 
-  // we want to remove all activities for (manifest, name)
-  remove: function actdb_remove(aObject) {
+  // Remove all the activities carried in the |aObjects| array.
+  remove: function actdb_remove(aObjects) {
     this.newTxn("readwrite", function (txn, store) {
-      let object = {
-        manifest: aObject.manifest,
-        name: aObject.name
-      };
-      debug("Going to remove " + JSON.stringify(object));
-      store.delete(this.createId(object));
+      aObjects.forEach(function (aObject) {
+        let object = {
+          manifest: aObject.manifest,
+          name: aObject.name
+        };
+        debug("Going to remove " + JSON.stringify(object));
+        store.delete(this.createId(object));
+      }, this);
     }.bind(this), function() {}, function() {});
   },
 
   find: function actdb_find(aObject, aSuccess, aError, aMatch) {
     debug("Looking for " + aObject.options.name);
 
     this.newTxn("readonly", function (txn, store) {
       let index = store.index("name");
@@ -302,23 +306,24 @@ let Activities = {
         break;
       case "Activity:PostError":
         caller.mm.sendAsyncMessage("Activity:FireError", msg);
         Services.obs.notifyObservers(null, "activity-done", obsData);
         delete this.callers[msg.id];
         break;
 
       case "Activities:Register":
-        this.db.add(msg, function onSuccess(aEvent) {
-          mm.sendAsyncMessage("Activities:Register:OK", msg);
-        },
-        function onError(aEvent) {
-          msg.error = "REGISTER_ERROR";
-          mm.sendAsyncMessage("Activities:Register:KO", msg);
-        });
+        this.db.add(msg,
+          function onSuccess(aEvent) {
+            mm.sendAsyncMessage("Activities:Register:OK", null);
+          },
+          function onError(aEvent) {
+            msg.error = "REGISTER_ERROR";
+            mm.sendAsyncMessage("Activities:Register:KO", msg);
+          });
         break;
       case "Activities:Unregister":
         this.db.remove(msg);
         break;
     }
   }
 }
 
--- a/dom/activities/src/ActivityProxy.js
+++ b/dom/activities/src/ActivityProxy.js
@@ -75,21 +75,26 @@ ActivityProxy.prototype = {
         Services.DOMRequest.fireSuccess(this.activity,
                                         ObjectWrapper.wrap(msg.result, this.window));
         break;
       case "Activity:FireError":
         debug("FireError");
         Services.DOMRequest.fireError(this.activity, msg.error);
         break;
     }
+    // We can only get one FireSuccess / FireError message, so cleanup as soon as possible.
+    this.cleanup();
   },
 
   cleanup: function actProxy_cleanup() {
     debug("cleanup");
-    cpmm.removeMessageListener("Activity:FireSuccess", this);
-    cpmm.removeMessageListener("Activity:FireError", this);
+    if (!this.cleanedUp) {
+      cpmm.removeMessageListener("Activity:FireSuccess", this);
+      cpmm.removeMessageListener("Activity:FireError", this);
+    }
+    this.cleanedUp = true;
   },
 
   classID: Components.ID("{ba9bd5cb-76a0-4ecf-a7b3-d2f7c43c5949}"),
   QueryInterface: XPCOMUtils.generateQI([Ci.nsIActivityProxy])
 }
 
 const NSGetFactory = XPCOMUtils.generateNSGetFactory([ActivityProxy]);
--- a/dom/apps/src/Webapps.js
+++ b/dom/apps/src/Webapps.js
@@ -349,20 +349,20 @@ function createApplicationObject(aWindow
 function WebappsApplication() {
   this.wrappedJSObject = this;
 }
 
 WebappsApplication.prototype = {
   __proto__: DOMRequestIpcHelper.prototype,
 
   init: function(aWindow, aApp) {
+    this._window = aWindow;
     this.origin = aApp.origin;
-    this.manifest = ObjectWrapper.wrap(aApp.manifest, aWindow);
-    this.updateManifest = aApp.updateManifest ? ObjectWrapper.wrap(aApp.updateManifest, aWindow)
-                                              : null;
+    this._manifest = aApp.manifest;
+    this._updateManifest = aApp.updateManifest;
     this.manifestURL = aApp.manifestURL;
     this.receipts = aApp.receipts;
     this.installOrigin = aApp.installOrigin;
     this.installTime = aApp.installTime;
     this.installState = aApp.installState || "installed";
     this.removable = aApp.removable;
     this.lastUpdateCheck = aApp.lastUpdateCheck ? aApp.lastUpdateCheck
                                                 : Date.now();
@@ -386,16 +386,25 @@ WebappsApplication.prototype = {
                               "Webapps:CheckForUpdate:Return:OK",
                               "Webapps:CheckForUpdate:Return:KO",
                               "Webapps:PackageEvent"]);
     cpmm.sendAsyncMessage("Webapps:RegisterForMessages",
                           ["Webapps:Uninstall:Return:OK", "Webapps:OfflineCache",
                            "Webapps:PackageEvent"]);
   },
 
+  get manifest() {
+    return this.manifest = ObjectWrapper.wrap(this._manifest, this._window);
+  },
+
+  get updateManifest() {
+    return this.updateManifest = this._updateManifest ? ObjectWrapper.wrap(this._updateManifest, this._window)
+                                                      : null;
+  },
+
   set onprogress(aCallback) {
     this._onprogress = aCallback;
   },
 
   get onprogress() {
     return this._onprogress;
   },
 
--- a/dom/apps/src/Webapps.jsm
+++ b/dom/apps/src/Webapps.jsm
@@ -248,17 +248,17 @@ let DOMApplicationRegistry = {
       }
     }
     this.registerAppsHandlers();
 #endif
     }).bind(this));
   },
 
 #ifdef MOZ_SYS_MSG
-  // aEntryPoint is either the entry_point name or the null, in which case we
+  // |aEntryPoint| is either the entry_point name or the null in which case we
   // use the root of the manifest.
   _registerSystemMessagesForEntryPoint: function(aManifest, aApp, aEntryPoint) {
     let root = aManifest;
     if (aEntryPoint && aManifest.entry_points[aEntryPoint]) {
       root = aManifest.entry_points[aEntryPoint];
     }
 
     if (!root.messages || !Array.isArray(root.messages) ||
@@ -289,113 +289,144 @@ let DOMApplicationRegistry = {
       return;
     }
 
     for (let entryPoint in aManifest.entry_points) {
       this._registerSystemMessagesForEntryPoint(aManifest, aApp, entryPoint);
     }
   },
 
-  // aEntryPoint is either the entry_point name or the null, in which case we
+  // |aEntryPoint| is either the entry_point name or the null in which case we
   // use the root of the manifest.
-  _registerActivitiesForEntryPoint: function(aManifest, aApp, aEntryPoint) {
+  _createActivitiesToRegister: function(aManifest, aApp, aEntryPoint) {
+    let activitiesToRegister = [];
     let root = aManifest;
     if (aEntryPoint && aManifest.entry_points[aEntryPoint]) {
       root = aManifest.entry_points[aEntryPoint];
     }
 
     if (!root.activities) {
-      return;
+      return activitiesToRegister;
     }
 
     let manifest = new ManifestHelper(aManifest, aApp.origin);
     for (let activity in root.activities) {
       let description = root.activities[activity];
       if (!description.href) {
         description.href = manifest.launch_path;
       }
       description.href = manifest.resolveFromOrigin(description.href);
-      let json = {
-        "manifest": aApp.manifestURL,
-        "name": activity,
-        "title": manifest.name,
-        "icon": manifest.iconURLForSize(128),
-        "description": description
-      }
-      this.activitiesToRegister++;
-      cpmm.sendAsyncMessage("Activities:Register", json);
+      activitiesToRegister.push({ "manifest": aApp.manifestURL,
+                                  "name": activity,
+                                  "title": manifest.name,
+                                  "icon": manifest.iconURLForSize(128),
+                                  "description": description });
 
       let launchPath =
         Services.io.newURI(manifest.resolveFromOrigin(description.href), null, null);
       let manifestURL = Services.io.newURI(aApp.manifestURL, null, null);
       msgmgr.registerPage("activity", launchPath, manifestURL);
     }
+    return activitiesToRegister;
   },
 
-  _registerActivities: function(aManifest, aApp) {
-    this._registerActivitiesForEntryPoint(aManifest, aApp, null);
+  // |aAppsToRegister| contains an array of apps to be registered, where
+  // each element is an object in the format of {manifest: foo, app: bar}.
+  _registerActivitiesForApps: function(aAppsToRegister) {
+    // Collect the activities to be registered for root and entry_points.
+    let activitiesToRegister = [];
+    aAppsToRegister.forEach(function (aApp) {
+      let manifest = aApp.manifest;
+      let app = aApp.app;
+      activitiesToRegister.push.apply(activitiesToRegister,
+        this._createActivitiesToRegister(manifest, app, null));
 
-    if (!aManifest.entry_points) {
-      return;
-    }
+      if (!manifest.entry_points) {
+        return;
+      }
 
-    for (let entryPoint in aManifest.entry_points) {
-      this._registerActivitiesForEntryPoint(aManifest, aApp, entryPoint);
-    }
+      for (let entryPoint in manifest.entry_points) {
+        activitiesToRegister.push.apply(activitiesToRegister,
+          this._createActivitiesToRegister(manifest, app, entryPoint));
+      }
+    }, this);
+
+    // Send the array carrying all the activities to be registered.
+    cpmm.sendAsyncMessage("Activities:Register", activitiesToRegister);
   },
 
-  _unregisterActivitiesForEntryPoint: function(aManifest, aApp, aEntryPoint) {
+  // Better to directly use |_registerActivitiesForApps()| if we have
+  // multiple apps to be registered for activities.
+  _registerActivities: function(aManifest, aApp) {
+    this._registerActivitiesForApps([{ manifest: aManifest, app: aApp }]);
+  },
+
+  // |aEntryPoint| is either the entry_point name or the null in which case we
+  // use the root of the manifest.
+  _createActivitiesToUnregister: function(aManifest, aApp, aEntryPoint) {
+    let activitiesToUnregister = [];
     let root = aManifest;
     if (aEntryPoint && aManifest.entry_points[aEntryPoint]) {
       root = aManifest.entry_points[aEntryPoint];
     }
 
     if (!root.activities) {
-      return;
+      return activitiesToUnregister;
     }
 
     for (let activity in root.activities) {
       let description = root.activities[activity];
-      let json = {
-        "manifest": aApp.manifestURL,
-        "name": activity
-      }
-      cpmm.sendAsyncMessage("Activities:Unregister", json);
+      activitiesToUnregister.push({ "manifest": aApp.manifestURL,
+                                    "name": activity });
     }
+    return activitiesToUnregister;
   },
 
-  _unregisterActivities: function(aManifest, aApp) {
-    this._unregisterActivitiesForEntryPoint(aManifest, aApp, null);
+  // |aAppsToUnregister| contains an array of apps to be unregistered, where
+  // each element is an object in the format of {manifest: foo, app: bar}.
+  _unregisterActivitiesForApps: function(aAppsToUnregister) {
+    // Collect the activities to be unregistered for root and entry_points.
+    let activitiesToUnregister = [];
+    aAppsToUnregister.forEach(function (aApp) {
+      let manifest = aApp.manifest;
+      let app = aApp.app;
+      activitiesToUnregister.push.apply(activitiesToUnregister,
+        this._createActivitiesToUnregister(manifest, app, null));
 
-    if (!aManifest.entry_points) {
-      return;
-    }
+      if (!manifest.entry_points) {
+        return;
+      }
 
-    for (let entryPoint in aManifest.entry_points) {
-      this._unregisterActivitiesForEntryPoint(aManifest, aApp, entryPoint);
-    }
+      for (let entryPoint in manifest.entry_points) {
+        activitiesToUnregister.push.apply(activitiesToUnregister,
+          this._createActivitiesToUnregister(manifest, app, entryPoint));
+      }
+    }, this);
+
+    // Send the array carrying all the activities to be unregistered.
+    cpmm.sendAsyncMessage("Activities:Unregister", activitiesToUnregister);
   },
 
-  _initRegisterActivities: function() {
-    this.activitiesToRegister = 0;
-    this.activitiesRegistered = 0;
-    this.allActivitiesSent = false;
+  // Better to directly use |_unregisterActivitiesForApps()| if we have
+  // multiple apps to be unregistered for activities.
+  _unregisterActivities: function(aManifest, aApp) {
+    this._unregisterActivitiesForApps([{ manifest: aManifest, app: aApp }]);
   },
 
   _processManifestForIds: function(aIds) {
-    this._initRegisterActivities();
     this._readManifests(aIds, (function registerManifests(aResults) {
+      let appsToRegister = [];
       aResults.forEach(function registerManifest(aResult) {
         let app = this.webapps[aResult.id];
         let manifest = aResult.manifest;
         app.name = manifest.name;
         this._registerSystemMessages(manifest, app);
-        this._registerActivities(manifest, app);
+        appsToRegister.push({ manifest: manifest, app: app });
       }, this);
-      this.allActivitiesSent = true;
+      this._registerActivitiesForApps(appsToRegister);
     }).bind(this));
   },
 #endif
 
   observe: function(aSubject, aTopic, aData) {
     if (aTopic == "xpcom-shutdown") {
       this.messages.forEach((function(msgName) {
         ppmm.removeMessageListener(msgName, this);
@@ -540,21 +571,17 @@ let DOMApplicationRegistry = {
         break;
       case "Webapps:CheckForUpdate":
         this.checkForUpdate(msg, mm);
         break;
       case "Webapps::ApplyDownload":
         this.ApplyDownload(msg.manifestURL);
         break;
       case "Activities:Register:OK":
-        this.activitiesRegistered++;
-        if (this.allActivitiesSent &&
-            this.activitiesRegistered === this.activitiesToRegister) {
-          this.notifyAppsRegistryReady();
-        }
+        this.notifyAppsRegistryReady();
         break;
       case "child-process-shutdown":
         this.removeMessageListener(mm);
         break;
     }
   },
 
   // Some messages can be listened by several content processes:
@@ -783,22 +810,20 @@ let DOMApplicationRegistry = {
 
     function updateHostedApp(aManifest) {
       debug("updateHostedApp");
       let id = this._appId(app.origin);
 
       // Update the web apps' registration.
       this.notifyAppsRegistryStart();
 #ifdef MOZ_SYS_MSG
-      this._initRegisterActivities();
       this._readManifests([{ id: id }], (function unregisterManifest(aResult) {
         this._unregisterActivities(aResult[0].manifest, app);
         this._registerSystemMessages(aManifest, app);
         this._registerActivities(aManifest, app);
-        this.allActivitiesSent = true;
       }).bind(this));
 #else
       // Nothing else to do but notifying we're ready.
       this.notifyAppsRegistryReady();
 #endif
 
       // Store the new manifest.
       let dir = FileUtils.getDir(DIRECTORY_NAME, ["webapps", id], true, true);
@@ -996,20 +1021,18 @@ let DOMApplicationRegistry = {
         this.broadcastMessage("Webapps:Install:Return:OK", aData);
         Services.obs.notifyObservers(this, "webapps-sync-install", appNote);
         this.broadcastMessage("Webapps:AddApp", { id: id, app: appObject });
       }).bind(this));
 
     if (!aData.isPackage) {
       this.notifyAppsRegistryStart();
 #ifdef MOZ_SYS_MSG
-      this._initRegisterActivities();
       this._registerSystemMessages(app.manifest, app);
       this._registerActivities(app.manifest, app);
-      this.allActivitiesSent = true;
 #else
       // Nothing else to do but notifying we're ready.
       this.notifyAppsRegistryReady();
 #endif
     }
 
     this.startOfflineCacheDownload(manifest, appObject, aProfileDir, aOfflineCacheObserver);
     if (manifest.package_path) {
--- a/dom/base/nsJSEnvironment.cpp
+++ b/dom/base/nsJSEnvironment.cpp
@@ -928,17 +928,16 @@ nsJSContext::LeaveModalState()
 #define JS_OPTIONS_DOT_STR "javascript.options."
 
 static const char js_options_dot_str[]   = JS_OPTIONS_DOT_STR;
 static const char js_strict_option_str[] = JS_OPTIONS_DOT_STR "strict";
 #ifdef DEBUG
 static const char js_strict_debug_option_str[] = JS_OPTIONS_DOT_STR "strict.debug";
 #endif
 static const char js_werror_option_str[] = JS_OPTIONS_DOT_STR "werror";
-static const char js_relimit_option_str[]= JS_OPTIONS_DOT_STR "relimit";
 #ifdef JS_GC_ZEAL
 static const char js_zeal_option_str[]        = JS_OPTIONS_DOT_STR "gczeal";
 static const char js_zeal_frequency_str[]     = JS_OPTIONS_DOT_STR "gczeal.frequency";
 #endif
 static const char js_methodjit_content_str[]  = JS_OPTIONS_DOT_STR "methodjit.content";
 static const char js_methodjit_chrome_str[]   = JS_OPTIONS_DOT_STR "methodjit.chrome";
 static const char js_methodjit_always_str[]   = JS_OPTIONS_DOT_STR "methodjit_always";
 static const char js_typeinfer_str[]          = JS_OPTIONS_DOT_STR "typeinference";
@@ -1048,22 +1047,16 @@ nsJSContext::JSOptionChangedCallback(con
 #endif
 
   bool werror = Preferences::GetBool(js_werror_option_str);
   if (werror)
     newDefaultJSOptions |= JSOPTION_WERROR;
   else
     newDefaultJSOptions &= ~JSOPTION_WERROR;
 
-  bool relimit = Preferences::GetBool(js_relimit_option_str);
-  if (relimit)
-    newDefaultJSOptions |= JSOPTION_RELIMIT;
-  else
-    newDefaultJSOptions &= ~JSOPTION_RELIMIT;
-
   ::JS_SetOptions(context->mContext,
                   newDefaultJSOptions & (JSRUNOPTION_MASK | JSOPTION_ALLOW_XML));
 
   // Save the new defaults for the next page load (InitContext).
   context->mDefaultJSOptions = newDefaultJSOptions;
 
   JSRuntime *rt = JS_GetRuntime(context->mContext);
   JS_SetJitHardening(rt, useHardening);
--- a/dom/base/nsLocation.cpp
+++ b/dom/base/nsLocation.cpp
@@ -1,16 +1,17 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set ts=2 sw=2 et tw=80: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsLocation.h"
 #include "nsIScriptSecurityManager.h"
+#include "nsIScriptObjectPrincipal.h"
 #include "nsIScriptContext.h"
 #include "nsIDocShell.h"
 #include "nsIDocShellLoadInfo.h"
 #include "nsIWebNavigation.h"
 #include "nsCDefaultURIFixup.h"
 #include "nsIURIFixup.h"
 #include "nsIURL.h"
 #include "nsIJARURI.h"
@@ -99,16 +100,18 @@ GetDocumentCharacterSetForURI(const nsAS
   }
 
   return NS_OK;
 }
 
 nsLocation::nsLocation(nsIDocShell *aDocShell)
 {
   mDocShell = do_GetWeakReference(aDocShell);
+  nsCOMPtr<nsIDOMWindow> outer = do_GetInterface(aDocShell);
+  mOuter = do_GetWeakReference(outer);
 }
 
 nsLocation::~nsLocation()
 {
 }
 
 DOMCI_DATA(Location, nsLocation)
 
@@ -233,17 +236,17 @@ nsLocation::CheckURL(nsIURI* aURI, nsIDo
 
     if (urisEqual) {
       sourceURI = docCurrentURI;
     }
     else {
       sourceURI = principalURI;
     }
 
-    owner = do_QueryInterface(doc ? doc->NodePrincipal() : secMan->GetCxSubjectPrincipal(cx));
+    owner = do_QueryInterface(secMan->GetCxSubjectPrincipal(cx));
   }
 
   // Create load info
   nsCOMPtr<nsIDocShellLoadInfo> loadInfo;
   docShell->CreateLoadInfo(getter_AddRefs(loadInfo));
   NS_ENSURE_TRUE(loadInfo, NS_ERROR_FAILURE);
 
   loadInfo->SetOwner(owner);
@@ -332,16 +335,19 @@ nsLocation::SetURI(nsIURI* aURI, bool aR
   }
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsLocation::GetHash(nsAString& aHash)
 {
+  if (!CallerSubsumes())
+    return NS_ERROR_DOM_SECURITY_ERR;
+
   aHash.SetLength(0);
 
   nsCOMPtr<nsIURI> uri;
   nsresult rv = GetURI(getter_AddRefs(uri));
   if (NS_FAILED(rv) || !uri) {
     return rv;
   }
 
@@ -404,16 +410,19 @@ nsLocation::SetHash(const nsAString& aHa
   }
 
   return rv;
 }
 
 NS_IMETHODIMP
 nsLocation::GetHost(nsAString& aHost)
 {
+  if (!CallerSubsumes())
+    return NS_ERROR_DOM_SECURITY_ERR;
+
   aHost.Truncate();
 
   nsCOMPtr<nsIURI> uri;
   nsresult result;
 
   result = GetURI(getter_AddRefs(uri), true);
 
   if (uri) {
@@ -427,32 +436,38 @@ nsLocation::GetHost(nsAString& aHost)
   }
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsLocation::SetHost(const nsAString& aHost)
 {
+  if (!CallerSubsumes())
+    return NS_ERROR_DOM_SECURITY_ERR;
+
   nsCOMPtr<nsIURI> uri;
   nsresult rv = GetWritableURI(getter_AddRefs(uri));
 
   if (uri) {
     rv = uri->SetHostPort(NS_ConvertUTF16toUTF8(aHost));
     if (NS_SUCCEEDED(rv)) {
       SetURI(uri);
     }
   }
 
   return rv;
 }
 
 NS_IMETHODIMP
 nsLocation::GetHostname(nsAString& aHostname)
 {
+  if (!CallerSubsumes())
+    return NS_ERROR_DOM_SECURITY_ERR;
+
   aHostname.Truncate();
 
   nsCOMPtr<nsIURI> uri;
   nsresult result;
 
   result = GetURI(getter_AddRefs(uri), true);
 
   if (uri) {
@@ -466,32 +481,38 @@ nsLocation::GetHostname(nsAString& aHost
   }
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsLocation::SetHostname(const nsAString& aHostname)
 {
+  if (!CallerSubsumes())
+    return NS_ERROR_DOM_SECURITY_ERR;
+
   nsCOMPtr<nsIURI> uri;
   nsresult rv = GetWritableURI(getter_AddRefs(uri));
 
   if (uri) {
     rv = uri->SetHost(NS_ConvertUTF16toUTF8(aHostname));
     if (NS_SUCCEEDED(rv)) {
       SetURI(uri);
     }
   }
 
   return rv;
 }
 
 NS_IMETHODIMP
 nsLocation::GetHref(nsAString& aHref)
 {
+  if (!CallerSubsumes())
+    return NS_ERROR_DOM_SECURITY_ERR;
+
   aHref.Truncate();
 
   nsCOMPtr<nsIURI> uri;
   nsresult result;
 
   result = GetURI(getter_AddRefs(uri));
 
   if (uri) {
@@ -641,16 +662,19 @@ nsLocation::SetHrefWithBase(const nsAStr
   }
 
   return result;
 }
 
 NS_IMETHODIMP
 nsLocation::GetPathname(nsAString& aPathname)
 {
+  if (!CallerSubsumes())
+    return NS_ERROR_DOM_SECURITY_ERR;
+
   aPathname.Truncate();
 
   nsCOMPtr<nsIURI> uri;
   nsresult result = NS_OK;
 
   result = GetURI(getter_AddRefs(uri));
 
   nsCOMPtr<nsIURL> url(do_QueryInterface(uri));
@@ -665,32 +689,38 @@ nsLocation::GetPathname(nsAString& aPath
   }
 
   return result;
 }
 
 NS_IMETHODIMP
 nsLocation::SetPathname(const nsAString& aPathname)
 {
+  if (!CallerSubsumes())
+    return NS_ERROR_DOM_SECURITY_ERR;
+
   nsCOMPtr<nsIURI> uri;
   nsresult rv = GetWritableURI(getter_AddRefs(uri));
 
   if (uri) {
     rv = uri->SetPath(NS_ConvertUTF16toUTF8(aPathname));
     if (NS_SUCCEEDED(rv)) {
       SetURI(uri);
     }
   }
 
   return rv;
 }
 
 NS_IMETHODIMP
 nsLocation::GetPort(nsAString& aPort)
 {
+  if (!CallerSubsumes())
+    return NS_ERROR_DOM_SECURITY_ERR;
+
   aPort.SetLength(0);
 
   nsCOMPtr<nsIURI> uri;
   nsresult result = NS_OK;
 
   result = GetURI(getter_AddRefs(uri), true);
 
   if (uri) {
@@ -708,16 +738,19 @@ nsLocation::GetPort(nsAString& aPort)
   }
 
   return result;
 }
 
 NS_IMETHODIMP
 nsLocation::SetPort(const nsAString& aPort)
 {
+  if (!CallerSubsumes())
+    return NS_ERROR_DOM_SECURITY_ERR;
+
   nsCOMPtr<nsIURI> uri;
   nsresult rv = GetWritableURI(getter_AddRefs(uri));
 
   if (uri) {
     // perhaps use nsReadingIterators at some point?
     NS_ConvertUTF16toUTF8 portStr(aPort);
     const char *buf = portStr.get();
     int32_t port = -1;
@@ -738,16 +771,19 @@ nsLocation::SetPort(const nsAString& aPo
   }
 
   return rv;
 }
 
 NS_IMETHODIMP
 nsLocation::GetProtocol(nsAString& aProtocol)
 {
+  if (!CallerSubsumes())
+    return NS_ERROR_DOM_SECURITY_ERR;
+
   aProtocol.SetLength(0);
 
   nsCOMPtr<nsIURI> uri;
   nsresult result = NS_OK;
 
   result = GetURI(getter_AddRefs(uri));
 
   if (uri) {
@@ -762,32 +798,38 @@ nsLocation::GetProtocol(nsAString& aProt
   }
 
   return result;
 }
 
 NS_IMETHODIMP
 nsLocation::SetProtocol(const nsAString& aProtocol)
 {
+  if (!CallerSubsumes())
+    return NS_ERROR_DOM_SECURITY_ERR;
+
   nsCOMPtr<nsIURI> uri;
   nsresult rv = GetWritableURI(getter_AddRefs(uri));
 
   if (uri) {
     rv = uri->SetScheme(NS_ConvertUTF16toUTF8(aProtocol));
     if (NS_SUCCEEDED(rv)) {
       SetURI(uri);
     }
   }
 
   return rv;
 }
 
 NS_IMETHODIMP
 nsLocation::GetSearch(nsAString& aSearch)
 {
+  if (!CallerSubsumes())
+    return NS_ERROR_DOM_SECURITY_ERR;
+
   aSearch.SetLength(0);
 
   nsCOMPtr<nsIURI> uri;
   nsresult result = NS_OK;
 
   result = GetURI(getter_AddRefs(uri));
 
   nsCOMPtr<nsIURL> url(do_QueryInterface(uri));
@@ -804,16 +846,19 @@ nsLocation::GetSearch(nsAString& aSearch
   }
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsLocation::SetSearch(const nsAString& aSearch)
 {
+  if (!CallerSubsumes())
+    return NS_ERROR_DOM_SECURITY_ERR;
+
   nsCOMPtr<nsIURI> uri;
   nsresult rv = GetWritableURI(getter_AddRefs(uri));
 
   nsCOMPtr<nsIURL> url(do_QueryInterface(uri));
   if (url) {
     rv = url->SetQuery(NS_ConvertUTF16toUTF8(aSearch));
     if (NS_SUCCEEDED(rv)) {
       SetURI(uri);
@@ -821,16 +866,19 @@ nsLocation::SetSearch(const nsAString& a
   }
 
   return rv;
 }
 
 NS_IMETHODIMP
 nsLocation::Reload(bool aForceget)
 {
+  if (!CallerSubsumes())
+    return NS_ERROR_DOM_SECURITY_ERR;
+
   nsresult rv;
   nsCOMPtr<nsIDocShell> docShell(do_QueryReferent(mDocShell));
   nsCOMPtr<nsIWebNavigation> webNav(do_QueryInterface(docShell));
   nsCOMPtr<nsPIDOMWindow> window(do_GetInterface(docShell));
 
   if (window && window->IsHandlingResizeEvent()) {
     // location.reload() was called on a window that is handling a
     // resize event. Sites do this since Netscape 4.x needed it, but
@@ -901,16 +949,19 @@ nsLocation::Replace(const nsAString& aUr
   NS_ENSURE_SUCCESS(rv, rv);
 
   return SetHrefWithBase(aUrl, oldUri, true);
 }
 
 NS_IMETHODIMP
 nsLocation::Assign(const nsAString& aUrl)
 {
+  if (!CallerSubsumes())
+    return NS_ERROR_DOM_SECURITY_ERR;
+
   nsAutoString oldHref;
   nsresult result = NS_OK;
 
   result = GetHref(oldHref);
 
   if (NS_SUCCEEDED(result)) {
     nsCOMPtr<nsIURI> oldUri;
 
@@ -922,16 +973,17 @@ nsLocation::Assign(const nsAString& aUrl
   }
 
   return result;
 }
 
 NS_IMETHODIMP
 nsLocation::ToString(nsAString& aReturn)
 {
+  // NB: GetHref checks CallerSubsumes().
   return GetHref(aReturn);
 }
 
 nsresult
 nsLocation::GetSourceDocument(JSContext* cx, nsIDocument** aDocument)
 {
   // XXX Code duplicated from nsHTMLDocument
   // XXX Tom said this reminded him of the "Six Degrees of
@@ -971,8 +1023,22 @@ nsLocation::GetSourceBaseURL(JSContext* 
   if (doc) {
     *sourceURL = doc->GetBaseURI().get();
   } else {
     *sourceURL = nullptr;
   }
 
   return rv;
 }
+
+bool
+nsLocation::CallerSubsumes()
+{
+  // Get the principal associated with the location object.
+  nsCOMPtr<nsIDOMWindow> outer = do_QueryReferent(mOuter);
+  if (NS_UNLIKELY(!outer))
+    return false;
+  nsCOMPtr<nsIScriptObjectPrincipal> sop = do_QueryInterface(outer);
+  bool subsumes = false;
+  nsresult rv = nsContentUtils::GetSubjectPrincipal()->Subsumes(sop->GetPrincipal(), &subsumes);
+  NS_ENSURE_SUCCESS(rv, false);
+  return subsumes;
+}
--- a/dom/base/nsLocation.h
+++ b/dom/base/nsLocation.h
@@ -47,15 +47,17 @@ protected:
                            bool aReplace);
   nsresult SetHrefWithContext(JSContext* cx, const nsAString& aHref,
                               bool aReplace);
 
   nsresult GetSourceBaseURL(JSContext* cx, nsIURI** sourceURL);
   nsresult GetSourceDocument(JSContext* cx, nsIDocument** aDocument);
 
   nsresult CheckURL(nsIURI *url, nsIDocShellLoadInfo** aLoadInfo);
+  bool CallerSubsumes();
 
   nsString mCachedHash;
   nsWeakPtr mDocShell;
+  nsWeakPtr mOuter;
 };
 
 #endif // nsLocation_h__
 
--- a/dom/base/nsStructuredCloneContainer.cpp
+++ b/dom/base/nsStructuredCloneContainer.cpp
@@ -153,17 +153,17 @@ nsStructuredCloneContainer::GetDataAsBas
 
 nsresult
 nsStructuredCloneContainer::GetSerializedNBytes(uint64_t *aSize)
 {
   NS_ENSURE_STATE(mData);
   NS_ENSURE_ARG_POINTER(aSize);
 
   // mSize is a size_t, while aSize is a uint64_t.  We rely on an implicit cast
-  // here so that we'll get a compile error if a size_t-to-uint64 cast is
+  // here so that we'll get a compile error if a size_t-to-uint64_t cast is
   // narrowing.
   *aSize = mSize;
 
   return NS_OK;
 }
 
 nsresult
 nsStructuredCloneContainer::GetFormatVersion(uint32_t *aFormatVersion)
--- a/dom/bluetooth/BluetoothAdapter.cpp
+++ b/dom/bluetooth/BluetoothAdapter.cpp
@@ -15,16 +15,17 @@
 #include "GeneratedEvents.h"
 
 #include "nsContentUtils.h"
 #include "nsDOMClassInfo.h"
 #include "nsDOMEvent.h"
 #include "nsIDOMBluetoothDeviceAddressEvent.h"
 #include "nsIDOMBluetoothDeviceEvent.h"
 #include "nsIDOMDOMRequest.h"
+#include "nsTArrayHelpers.h"
 #include "nsThreadUtils.h"
 #include "nsXPCOMCIDInternal.h"
 
 #include "mozilla/dom/bluetooth/BluetoothTypes.h"
 #include "mozilla/dom/ContentChild.h"
 #include "mozilla/LazyIdleThread.h"
 #include "mozilla/Util.h"
 
@@ -97,18 +98,17 @@ public:
 
     nsresult rv;
     nsIScriptContext* sc = mAdapterPtr->GetContextForEventHandlers(&rv);
     if (!sc) {
       NS_WARNING("Cannot create script context!");
       return false;
     }
 
-    rv = BluetoothDeviceArrayToJSArray(sc->GetNativeContext(),
-                                       sc->GetNativeGlobal(), devices, &JsDevices);
+    rv = nsTArrayToJSArray(sc->GetNativeContext(), devices, &JsDevices);
 
     if (JsDevices) {
       aValue->setObject(*JsDevices);
     }
     else {
       NS_WARNING("Paird not yet set!");
       return false;
     }
@@ -206,34 +206,33 @@ BluetoothAdapter::SetPropertyByValue(con
   } else if (name.EqualsLiteral("Class")) {
     mClass = value.get_uint32_t();
   } else if (name.EqualsLiteral("UUIDs")) {
     mUuids = value.get_ArrayOfnsString();
     nsresult rv;
     nsIScriptContext* sc = GetContextForEventHandlers(&rv);
     if (sc) {
       rv =
-        StringArrayToJSArray(sc->GetNativeContext(),
-                             sc->GetNativeGlobal(), mUuids, &mJsUuids);
+        nsTArrayToJSArray(sc->GetNativeContext(), mUuids, &mJsUuids);
       if (NS_FAILED(rv)) {
         NS_WARNING("Cannot set JS UUIDs object!");
         return;
       }
       Root();
     } else {
       NS_WARNING("Could not get context!");
     }
   } else if (name.EqualsLiteral("Devices")) {
     mDeviceAddresses = value.get_ArrayOfnsString();
     nsresult rv;
     nsIScriptContext* sc = GetContextForEventHandlers(&rv);
     if (sc) {
       rv =
-        StringArrayToJSArray(sc->GetNativeContext(),
-                             sc->GetNativeGlobal(), mDeviceAddresses, &mJsDeviceAddresses);
+        nsTArrayToJSArray(sc->GetNativeContext(), mDeviceAddresses,
+                          &mJsDeviceAddresses);
       if (NS_FAILED(rv)) {
         NS_WARNING("Cannot set JS Device Addresses object!");
         return;
       }
       Root();
     } else {
       NS_WARNING("Could not get context!");
     }
@@ -853,16 +852,51 @@ BluetoothAdapter::StopSendingFile(const 
 
   nsRefPtr<BluetoothVoidReplyRunnable> result = new BluetoothVoidReplyRunnable(req);
   bs->StopSendingFile(aDeviceAddress, result);
   req.forget(aRequest);
 
   return NS_OK;
 }
 
+nsresult
+BluetoothAdapter::ConfirmReceivingFile(const nsAString& aDeviceAddress,
+                                       bool aConfirmation,
+                                       nsIDOMDOMRequest** aRequest)
+{
+  BluetoothService* bs = BluetoothService::Get();
+  if (!bs) {
+    NS_WARNING("BluetoothService not available!");
+    return NS_ERROR_FAILURE;
+  }
+
+  nsCOMPtr<nsIDOMRequestService> rs =
+    do_GetService("@mozilla.org/dom/dom-request-service;1");
+
+  if (!rs) {
+    NS_WARNING("No DOMRequest Service!");
+    return NS_ERROR_FAILURE;
+  }
+
+  nsCOMPtr<nsIDOMDOMRequest> req;
+  nsresult rv = rs->CreateRequest(GetOwner(), getter_AddRefs(req));
+  if (NS_FAILED(rv)) {
+    NS_WARNING("Can't create DOMRequest!");
+    return NS_ERROR_FAILURE;
+  }
+
+  nsRefPtr<BluetoothVoidReplyRunnable> result =
+    new BluetoothVoidReplyRunnable(req);
+  bs->ConfirmReceivingFile(aDeviceAddress, aConfirmation, result);
+
+  req.forget(aRequest);
+
+  return NS_OK;
+}
+
 NS_IMPL_EVENT_HANDLER(BluetoothAdapter, propertychanged)
 NS_IMPL_EVENT_HANDLER(BluetoothAdapter, devicefound)
 NS_IMPL_EVENT_HANDLER(BluetoothAdapter, devicedisappeared)
 NS_IMPL_EVENT_HANDLER(BluetoothAdapter, devicecreated)
 NS_IMPL_EVENT_HANDLER(BluetoothAdapter, requestconfirmation)
 NS_IMPL_EVENT_HANDLER(BluetoothAdapter, requestpincode)
 NS_IMPL_EVENT_HANDLER(BluetoothAdapter, requestpasskey)
 NS_IMPL_EVENT_HANDLER(BluetoothAdapter, authorize)
--- a/dom/bluetooth/BluetoothDevice.cpp
+++ b/dom/bluetooth/BluetoothDevice.cpp
@@ -10,16 +10,17 @@
 #include "BluetoothReplyRunnable.h"
 #include "BluetoothService.h"
 #include "BluetoothUtils.h"
 #include "BluetoothServiceUuid.h"
 
 #include "nsIDOMDOMRequest.h"
 #include "nsDOMClassInfo.h"
 #include "nsContentUtils.h"
+#include "nsTArrayHelpers.h"
 #include "mozilla/dom/bluetooth/BluetoothTypes.h"
 
 USING_BLUETOOTH_NAMESPACE
 
 DOMCI_DATA(BluetoothDevice, BluetoothDevice)
 
 NS_IMPL_CYCLE_COLLECTION_CLASS(BluetoothDevice)
 
@@ -113,34 +114,32 @@ BluetoothDevice::SetPropertyByValue(cons
   } else if (name.EqualsLiteral("Paired")) {
     mPaired = value.get_bool();
   } else if (name.EqualsLiteral("UUIDs")) {
     mUuids = value.get_ArrayOfnsString();
     nsresult rv;
     nsIScriptContext* sc = GetContextForEventHandlers(&rv);
     if (sc) {
       rv =
-        StringArrayToJSArray(sc->GetNativeContext(),
-                             sc->GetNativeGlobal(), mUuids, &mJsUuids);
+        nsTArrayToJSArray(sc->GetNativeContext(), mUuids, &mJsUuids);
       if (NS_FAILED(rv)) {
         NS_WARNING("Cannot set JS UUIDs object!");
         return;
       }
       Root();
     } else {
       NS_WARNING("Could not get context!");
     }
   } else if (name.EqualsLiteral("Services")) {
     mServices = value.get_ArrayOfnsString();
     nsresult rv;
     nsIScriptContext* sc = GetContextForEventHandlers(&rv);
     if (sc) {
       rv =
-        StringArrayToJSArray(sc->GetNativeContext(),
-                             sc->GetNativeGlobal(), mServices, &mJsServices);
+        nsTArrayToJSArray(sc->GetNativeContext(), mServices, &mJsServices);
       if (NS_FAILED(rv)) {
         NS_WARNING("Cannot set JS Services object!");
         return;
       }
       Root();
     } else {
       NS_WARNING("Could not get context!");
     }
--- a/dom/bluetooth/BluetoothOppManager.cpp
+++ b/dom/bluetooth/BluetoothOppManager.cpp
@@ -95,16 +95,17 @@ BluetoothOppManager::BluetoothOppManager
                                            , mRemoteObexVersion(0)
                                            , mRemoteConnectionFlags(0)
                                            , mRemoteMaxPacketLength(0)
                                            , mAbortFlag(false)
                                            , mReadFileThread(nullptr)
                                            , mPacketLeftLength(0)
                                            , mReceiving(false)
                                            , mPutFinal(false)
+                                           , mWaitingForConfirmationFlag(false)
 {
   // FIXME / Bug 800249:
   //   mConnectedDeviceAddress is Bluetooth address of connected device,
   //   we will be able to get this value after bug 800249 lands. For now,
   //   just assign a fake value to it.
   mConnectedDeviceAddress.AssignASCII("00:00:00:00:00:00");
 }
 
@@ -210,16 +211,38 @@ BluetoothOppManager::StopSendingFile(Blu
     return false;
   }
 
   mAbortFlag = true;
 
   return true;
 }
 
+void
+BluetoothOppManager::ConfirmReceivingFile(bool aConfirm,
+                                          BluetoothReplyRunnable* aRunnable)
+{
+  if (!mWaitingForConfirmationFlag) {
+    NS_WARNING("We are not waiting for a confirmation now.");
+    return;
+  }
+
+  NS_ASSERTION(mPacketLeftLength == 0,
+               "Should not be in the middle of receiving a PUT packet.");
+
+  mWaitingForConfirmationFlag = false;
+  ReplyToPut(mPutFinal, aConfirm);
+
+  if (mPutFinal || !aConfirm) {
+    mReceiving = false;
+    FileTransferComplete(mConnectedDeviceAddress, aConfirm, true, sFileName,
+                         sSentFileLength, sContentType);
+  }
+}
+
 // Virtual function of class SocketConsumer
 void
 BluetoothOppManager::ReceiveSocketData(UnixSocketRawData* aMessage)
 {
   uint8_t opCode;
   int packetLength;
   int receivedLength = aMessage->mSize;
 
@@ -360,18 +383,18 @@ BluetoothOppManager::ReceiveSocketData(U
       if (!mReceiving) {
         MOZ_ASSERT(mPacketLeftLength == 0);
         ParseHeaders(&aMessage->mData[3], receivedLength - 3, &pktHeaders);
 
         pktHeaders.GetName(sFileName);
         pktHeaders.GetContentType(sContentType);
         pktHeaders.GetLength(&sFileLength);
 
-        ReceivingFileConfirmation(mConnectedDeviceAddress, sFileName, sFileLength, sContentType);
         mReceiving = true;
+        mWaitingForConfirmationFlag = true;
       }
 
       /*
        * A PUT request from remote devices may be divided into multiple parts.
        * In other words, one request may need to be received multiple times,
        * so here we keep a variable mPacketLeftLength to indicate if current
        * PUT request is done.
        */
@@ -383,22 +406,27 @@ BluetoothOppManager::ReceiveSocketData(U
         mPacketLeftLength = packetLength - receivedLength;
       } else {
         NS_ASSERTION(mPacketLeftLength >= receivedLength,
                      "Invalid packet length");
         mPacketLeftLength -= receivedLength;
       }
 
       if (mPacketLeftLength == 0) {
-        ReplyToPut(mPutFinal);
+        if (mWaitingForConfirmationFlag) {
+          ReceivingFileConfirmation(mConnectedDeviceAddress, sFileName,
+                                    sFileLength, sContentType);
+        } else {
+          ReplyToPut(mPutFinal, true);
 
-        if (mPutFinal) {
-          mReceiving = false;
-          FileTransferComplete(mConnectedDeviceAddress, true, true, sFileName,
-                               sSentFileLength, sContentType);
+          if (mPutFinal) {
+            mReceiving = false;
+            FileTransferComplete(mConnectedDeviceAddress, true, true, sFileName,
+                                 sSentFileLength, sContentType);
+          }
         }
       }
     }
   }
 }
 
 void
 BluetoothOppManager::SendConnectRequest()
@@ -564,29 +592,37 @@ BluetoothOppManager::ReplyToDisconnect()
   SetObexPacketInfo(req, ObexResponseCode::Success, index);
 
   UnixSocketRawData* s = new UnixSocketRawData(index);
   memcpy(s->mData, req, s->mSize);
   SendSocketData(s);
 }
 
 void
-BluetoothOppManager::ReplyToPut(bool aFinal)
+BluetoothOppManager::ReplyToPut(bool aFinal, bool aContinue)
 {
   if (!mConnected) return;
 
   // Section 3.3.2 "Disconnect", IrOBEX 1.2
   // [opcode:1][length:2][Headers:var]
   uint8_t req[255];
   int index = 3;
 
-  if (aFinal) {
-    SetObexPacketInfo(req, ObexResponseCode::Success, index);
+  if (aContinue) {
+    if (aFinal) {
+      SetObexPacketInfo(req, ObexResponseCode::Success, index);
+    } else {
+      SetObexPacketInfo(req, ObexResponseCode::Continue, index);
+    }
   } else {
-    SetObexPacketInfo(req, ObexResponseCode::Continue, index);
+    if (aFinal) {
+      SetObexPacketInfo(req, ObexResponseCode::Unauthorized, index);
+    } else {
+      SetObexPacketInfo(req, ObexResponseCode::Unauthorized & (~FINAL_BIT), index);
+    }
   }
 
   UnixSocketRawData* s = new UnixSocketRawData(index);
   memcpy(s->mData, req, s->mSize);
   SendSocketData(s);
 }
 
 void
--- a/dom/bluetooth/BluetoothOppManager.h
+++ b/dom/bluetooth/BluetoothOppManager.h
@@ -46,16 +46,17 @@ public:
   bool Connect(const nsAString& aDeviceObjectPath,
                BluetoothReplyRunnable* aRunnable);
   void Disconnect();
   bool Listen();
 
   bool SendFile(BlobParent* aBlob,
                 BluetoothReplyRunnable* aRunnable);
   bool StopSendingFile(BluetoothReplyRunnable* aRunnable);
+  void ConfirmReceivingFile(bool aConfirm, BluetoothReplyRunnable* aRunnable);
 
   void SendConnectRequest();
   void SendPutHeaderRequest(const nsAString& aFileName, int aFileSize);
   void SendPutRequest(uint8_t* aFileBody, int aFileBodyLength,
                       bool aFinal);
   void SendDisconnectRequest();
   void SendAbortRequest();
 
@@ -77,32 +78,33 @@ private:
                       uint32_t aProcessedLength,
                       uint32_t aFileLength);
   void ReceivingFileConfirmation(const nsString& aAddress,
                                  const nsString& aFileName,
                                  uint32_t aFileLength,
                                  const nsString& aContentType);
   void ReplyToConnect();
   void ReplyToDisconnect();
-  void ReplyToPut(bool aFinal);
+  void ReplyToPut(bool aFinal, bool aContinue);
   virtual void OnConnectSuccess() MOZ_OVERRIDE;
   virtual void OnConnectError() MOZ_OVERRIDE;
   virtual void OnDisconnect() MOZ_OVERRIDE;
 
   bool mConnected;
   int mConnectionId;
   int mLastCommand;
   uint8_t mRemoteObexVersion;
   uint8_t mRemoteConnectionFlags;
   int mRemoteMaxPacketLength;
   bool mAbortFlag;
   int mPacketLeftLength;
   nsString mConnectedDeviceAddress;
   bool mReceiving;
   bool mPutFinal;
+  bool mWaitingForConfirmationFlag;
 
   nsCOMPtr<nsIDOMBlob> mBlob;
   nsCOMPtr<nsIThread> mReadFileThread;
 };
 
 END_BLUETOOTH_NAMESPACE
 
 #endif
--- a/dom/bluetooth/BluetoothService.h
+++ b/dom/bluetooth/BluetoothService.h
@@ -285,16 +285,20 @@ public:
 
   virtual nsresult
   ListenSocketViaService(int aChannel,
                          BluetoothSocketType aType,
                          bool aAuth,
                          bool aEncrypt,
                          mozilla::ipc::UnixSocketConsumer* aConsumer) = 0;
 
+  virtual void
+  ConfirmReceivingFile(const nsAString& aDeviceAddress, bool aConfirm,
+                       BluetoothReplyRunnable* aRunnable) = 0;
+
   bool
   IsEnabled() const
   {
     return mEnabled;
   }
 
 protected:
   BluetoothService()
--- a/dom/bluetooth/BluetoothUtils.cpp
+++ b/dom/bluetooth/BluetoothUtils.cpp
@@ -13,103 +13,16 @@
 #include "mozilla/dom/bluetooth/BluetoothTypes.h"
 #include "nsContentUtils.h"
 #include "nsISystemMessagesInternal.h"
 #include "nsTArray.h"
 #include "nsString.h"
 
 USING_BLUETOOTH_NAMESPACE
 
-nsresult
-mozilla::dom::bluetooth::StringArrayToJSArray(JSContext* aCx, JSObject* aGlobal,
-                                              const nsTArray<nsString>& aSourceArray,
-                                              JSObject** aResultArray)
-{
-  NS_ASSERTION(aCx, "Null context!");
-  NS_ASSERTION(aGlobal, "Null global!");
-
-  JSAutoRequest ar(aCx);
-  JSAutoCompartment ac(aCx, aGlobal);
-
-  JSObject* arrayObj;
-
-  if (aSourceArray.IsEmpty()) {
-    arrayObj = JS_NewArrayObject(aCx, 0, nullptr);
-  } else {
-    uint32_t valLength = aSourceArray.Length();
-    mozilla::ScopedDeleteArray<jsval> valArray(new jsval[valLength]);
-    JS::AutoArrayRooter tvr(aCx, 0, valArray);
-    for (uint32_t index = 0; index < valLength; index++) {
-      JSString* s = JS_NewUCStringCopyN(aCx, aSourceArray[index].BeginReading(),
-                                        aSourceArray[index].Length());
-      if(!s) {
-        NS_WARNING("Memory allocation error!");
-        return NS_ERROR_OUT_OF_MEMORY;
-      }
-      valArray[index] = STRING_TO_JSVAL(s);
-      tvr.changeLength(index + 1);
-    }
-    arrayObj = JS_NewArrayObject(aCx, valLength, valArray);
-  }
-
-  if (!arrayObj) {
-    return NS_ERROR_OUT_OF_MEMORY;
-  }
-
-  // XXX This is not what Jonas wants. He wants it to be live.
-  // Followup at bug 717414
-  if (!JS_FreezeObject(aCx, arrayObj)) {
-    return NS_ERROR_FAILURE;
-  }
-
-  *aResultArray = arrayObj;
-  return NS_OK;
-}
-
-nsresult
-mozilla::dom::bluetooth::BluetoothDeviceArrayToJSArray(JSContext* aCx, JSObject* aGlobal,
-                                                       const nsTArray<nsRefPtr<BluetoothDevice> >& aSourceArray,
-                                                       JSObject** aResultArray)
-{
-  NS_ASSERTION(aCx, "Null context!");
-  NS_ASSERTION(aGlobal, "Null global!");
-
-  JSAutoRequest ar(aCx);
-  JSAutoCompartment ac(aCx, aGlobal);
-
-  JSObject* arrayObj;
-
-  if (aSourceArray.IsEmpty()) {
-    arrayObj = JS_NewArrayObject(aCx, 0, nullptr);
-  } else {
-    uint32_t valLength = aSourceArray.Length();
-    mozilla::ScopedDeleteArray<jsval> valArray(new jsval[valLength]);
-    JS::AutoArrayRooter tvr(aCx, 0, valArray);
-    for (uint32_t index = 0; index < valLength; index++) {
-      nsISupports* obj = aSourceArray[index]->ToISupports();
-      nsresult rv =
-        nsContentUtils::WrapNative(aCx, aGlobal, obj, &valArray[index]);
-      NS_ENSURE_SUCCESS(rv, rv);
-      tvr.changeLength(index + 1);
-    }
-    arrayObj = JS_NewArrayObject(aCx, valLength, valArray);
-  }
-
-  if (!arrayObj) {
-    return NS_ERROR_OUT_OF_MEMORY;
-  }
-
-  if (!JS_FreezeObject(aCx, arrayObj)) {
-    return NS_ERROR_FAILURE;
-  }
-
-  *aResultArray = arrayObj;
-  return NS_OK;
-}
-
 bool
 mozilla::dom::bluetooth::SetJsObject(JSContext* aContext,
                                      JSObject* aObj,
                                      const InfallibleTArray<BluetoothNamedValue>& aData)
 {
   for (uint32_t i = 0; i < aData.Length(); i++) {
     jsval v;
     if (aData[i].value().type() == BluetoothValue::TnsString) {
--- a/dom/bluetooth/BluetoothUtils.h
+++ b/dom/bluetooth/BluetoothUtils.h
@@ -12,26 +12,16 @@
 class JSContext;
 class JSObject;
 
 BEGIN_BLUETOOTH_NAMESPACE
 
 class BluetoothDevice;
 class BluetoothNamedValue;
 
-nsresult
-StringArrayToJSArray(JSContext* aCx, JSObject* aGlobal,
-                     const nsTArray<nsString>& aSourceArray,
-                     JSObject** aResultArray);
-
-nsresult
-BluetoothDeviceArrayToJSArray(JSContext* aCx, JSObject* aGlobal,
-                              const nsTArray<nsRefPtr<BluetoothDevice> >& aSourceArray,
-                              JSObject** aResultArray);
-
 bool
 SetJsObject(JSContext* aContext,
             JSObject* aObj,
             const InfallibleTArray<BluetoothNamedValue>& aData);
 
 nsString
 GetObjectPathFromAddress(const nsAString& aAdapterPath,
                          const nsAString& aDeviceAddress);
--- a/dom/bluetooth/ipc/BluetoothParent.cpp
+++ b/dom/bluetooth/ipc/BluetoothParent.cpp
@@ -216,16 +216,20 @@ BluetoothParent::RecvPBluetoothRequestCo
     case Request::TConnectRequest:
       return actor->DoRequest(aRequest.get_ConnectRequest());
     case Request::TDisconnectRequest:
       return actor->DoRequest(aRequest.get_DisconnectRequest());
     case Request::TSendFileRequest:
       return actor->DoRequest(aRequest.get_SendFileRequest());
     case Request::TStopSendingFileRequest:
       return actor->DoRequest(aRequest.get_StopSendingFileRequest());
+    case Request::TConfirmReceivingFileRequest:
+      return actor->DoRequest(aRequest.get_ConfirmReceivingFileRequest());
+    case Request::TDenyReceivingFileRequest:
+      return actor->DoRequest(aRequest.get_DenyReceivingFileRequest());
     default:
       MOZ_NOT_REACHED("Unknown type!");
       return false;
   }
 
   MOZ_NOT_REACHED("Should never get here!");
   return false;
 }
@@ -535,8 +539,32 @@ bool
 BluetoothRequestParent::DoRequest(const StopSendingFileRequest& aRequest)
 {
   MOZ_ASSERT(mService);
   MOZ_ASSERT(mRequestType == Request::TStopSendingFileRequest);
 
   return mService->StopSendingFile(aRequest.devicePath(),
                                    mReplyRunnable.get());
 }
+
+bool
+BluetoothRequestParent::DoRequest(const ConfirmReceivingFileRequest& aRequest)
+{
+  MOZ_ASSERT(mService);
+  MOZ_ASSERT(mRequestType == Request::TConfirmReceivingFileRequest);
+
+  mService->ConfirmReceivingFile(aRequest.devicePath(),
+                                 true,
+                                 mReplyRunnable.get());
+  return true;
+}
+
+bool
+BluetoothRequestParent::DoRequest(const DenyReceivingFileRequest& aRequest)
+{
+  MOZ_ASSERT(mService);
+  MOZ_ASSERT(mRequestType == Request::TDenyReceivingFileRequest);
+
+  mService->ConfirmReceivingFile(aRequest.devicePath(),
+                                 false,
+                                 mReplyRunnable.get());
+  return true;
+}
--- a/dom/bluetooth/ipc/BluetoothParent.h
+++ b/dom/bluetooth/ipc/BluetoothParent.h
@@ -172,13 +172,19 @@ protected:
   bool
   DoRequest(const DisconnectRequest& aRequest);
 
   bool
   DoRequest(const SendFileRequest& aRequest);
 
   bool
   DoRequest(const StopSendingFileRequest& aRequest);
+
+  bool
+  DoRequest(const ConfirmReceivingFileRequest& aRequest);
+
+  bool
+  DoRequest(const DenyReceivingFileRequest& aRequest);
 };
 
 END_BLUETOOTH_NAMESPACE
 
 #endif // mozilla_dom_bluetooth_ipc_bluetoothparent_h__
--- a/dom/bluetooth/ipc/BluetoothServiceChildProcess.cpp
+++ b/dom/bluetooth/ipc/BluetoothServiceChildProcess.cpp
@@ -340,16 +340,32 @@ BluetoothServiceChildProcess::StopSendin
   const nsAString& aDeviceAddress,
   BluetoothReplyRunnable* aRunnable)
 {
   SendRequest(aRunnable,
               StopSendingFileRequest(nsString(aDeviceAddress)));
   return true;
 }
 
+void
+BluetoothServiceChildProcess::ConfirmReceivingFile(
+  const nsAString& aDeviceAddress,
+  bool aConfirm,
+  BluetoothReplyRunnable* aRunnable)
+{
+  if(aConfirm) {
+    SendRequest(aRunnable,
+                ConfirmReceivingFileRequest(nsString(aDeviceAddress)));
+    return;
+  }
+  
+  SendRequest(aRunnable,
+              DenyReceivingFileRequest(nsString(aDeviceAddress)));
+}
+
 nsresult
 BluetoothServiceChildProcess::HandleStartup()
 {
   // Don't need to do anything here for startup since our Create function takes
   // care of the actor machinery.
   return NS_OK;
 }
 
--- a/dom/bluetooth/ipc/BluetoothServiceChildProcess.h
+++ b/dom/bluetooth/ipc/BluetoothServiceChildProcess.h
@@ -144,16 +144,20 @@ public:
            BlobParent* aBlobParent,
            BlobChild* aBlobChild,
            BluetoothReplyRunnable* aRunnable) MOZ_OVERRIDE;
 
   virtual bool
   StopSendingFile(const nsAString& aDeviceAddress,
                   BluetoothReplyRunnable* aRunnable) MOZ_OVERRIDE;
 
+  virtual void
+  ConfirmReceivingFile(const nsAString& aDeviceAddress,
+                       bool aConfirm,
+                       BluetoothReplyRunnable* aRunnable) MOZ_OVERRIDE;
 protected:
   BluetoothServiceChildProcess();
   virtual ~BluetoothServiceChildProcess();
 
   void
   NoteDeadActor();
 
   void
--- a/dom/bluetooth/ipc/PBluetooth.ipdl
+++ b/dom/bluetooth/ipc/PBluetooth.ipdl
@@ -116,16 +116,26 @@ struct SendFileRequest
   PBlob blob;
 };
 
 struct StopSendingFileRequest
 {
   nsString devicePath;
 };
 
+struct ConfirmReceivingFileRequest
+{
+  nsString devicePath;
+};
+
+struct DenyReceivingFileRequest
+{
+  nsString devicePath;
+};
+
 union Request
 {
   DefaultAdapterPathRequest;
   SetPropertyRequest;
   GetPropertyRequest;
   StartDiscoveryRequest;
   StopDiscoveryRequest;
   PairRequest;
@@ -136,16 +146,18 @@ union Request
   DenyPairingConfirmationRequest;
   ConfirmAuthorizationRequest;
   DenyAuthorizationRequest;
   DevicePropertiesRequest;
   ConnectRequest;
   DisconnectRequest;
   SendFileRequest;
   StopSendingFileRequest;
+  ConfirmReceivingFileRequest;
+  DenyReceivingFileRequest;
 };
 
 protocol PBluetooth
 {
   manager PContent;
   manages PBluetoothRequest;
 
   /**
--- a/dom/bluetooth/linux/BluetoothDBusService.cpp
+++ b/dom/bluetooth/linux/BluetoothDBusService.cpp
@@ -2522,40 +2522,59 @@ BluetoothDBusService::GetScoSocket(const
 }
 
 bool
 BluetoothDBusService::SendFile(const nsAString& aDeviceAddress,
                                BlobParent* aBlobParent,
                                BlobChild* aBlobChild,
                                BluetoothReplyRunnable* aRunnable)
 {
+  NS_ASSERTION(NS_IsMainThread(), "Must be called from main thread!");
+
   // Currently we only support one device sending one file at a time,
   // so we don't need aDeviceAddress here because the target device
   // has been determined when calling 'Connect()'. Nevertheless, keep
   // it for future use.
   BluetoothOppManager* opp = BluetoothOppManager::Get();
   opp->SendFile(aBlobParent, aRunnable);
 
   return true;
 }
 
 bool
 BluetoothDBusService::StopSendingFile(const nsAString& aDeviceAddress,
                                       BluetoothReplyRunnable* aRunnable)
 {
+  NS_ASSERTION(NS_IsMainThread(), "Must be called from main thread!");
+
   // Currently we only support one device sending one file at a time,
   // so we don't need aDeviceAddress here because the target device
   // has been determined when calling 'Connect()'. Nevertheless, keep
   // it for future use.
   BluetoothOppManager* opp = BluetoothOppManager::Get();
   opp->StopSendingFile(aRunnable);
 
   return true;
 }
 
+void
+BluetoothDBusService::ConfirmReceivingFile(const nsAString& aDeviceAddress,
+                                           bool aConfirm,
+                                           BluetoothReplyRunnable* aRunnable)
+{
+  NS_ASSERTION(NS_IsMainThread(), "Must be called from main thread!");
+
+  // Currently we only support one device sending one file at a time,
+  // so we don't need aDeviceAddress here because the target device
+  // has been determined when calling 'Connect()'. Nevertheless, keep
+  // it for future use.
+  BluetoothOppManager* opp = BluetoothOppManager::Get();
+  opp->ConfirmReceivingFile(aConfirm, aRunnable);
+}
+
 nsresult
 BluetoothDBusService::ListenSocketViaService(int aChannel,
                                              BluetoothSocketType aType,
                                              bool aAuth,
                                              bool aEncrypt,
                                              mozilla::ipc::UnixSocketConsumer* aConsumer)
 {
   NS_ASSERTION(NS_IsMainThread(), "Must be called from main thread!");
--- a/dom/bluetooth/linux/BluetoothDBusService.h
+++ b/dom/bluetooth/linux/BluetoothDBusService.h
@@ -147,16 +147,20 @@ public:
            BlobParent* aBlobParent,
            BlobChild* aBlobChild,
            BluetoothReplyRunnable* aRunnable);
 
   virtual bool
   StopSendingFile(const nsAString& aDeviceAddress,
                   BluetoothReplyRunnable* aRunnable);
 
+  virtual void
+  ConfirmReceivingFile(const nsAString& aDeviceAddress, bool aConfirm,
+                       BluetoothReplyRunnable* aRunnable);
+
 private:
   nsresult SendGetPropertyMessage(const nsAString& aPath,
                                   const char* aInterface,
                                   void (*aCB)(DBusMessage *, void *),
                                   BluetoothReplyRunnable* aRunnable);
   nsresult SendDiscoveryMessage(const nsAString& aAdapterPath,
                                 const char* aMessageName,
                                 BluetoothReplyRunnable* aRunnable);
--- a/dom/bluetooth/nsIDOMBluetoothAdapter.idl
+++ b/dom/bluetooth/nsIDOMBluetoothAdapter.idl
@@ -5,17 +5,17 @@
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsIDOMEventTarget.idl"
 
 interface nsIDOMDOMRequest;
 interface nsIDOMBlob;
 interface nsIDOMBluetoothDevice;
 
-[scriptable, builtinclass, uuid(ad42ba9f-4c30-4ed5-80c2-8b8520a50e0b)]
+[scriptable, builtinclass, uuid(6a4a9415-cda3-4a19-b79e-05d9bc2c2700)]
 interface nsIDOMBluetoothAdapter : nsIDOMEventTarget
 {
   readonly attribute DOMString address;
   [binaryname(AdapterClass)] readonly attribute unsigned long class;
   readonly attribute bool enabled;
   readonly attribute bool discovering;
 
   [implicit_jscontext]
@@ -51,16 +51,17 @@ interface nsIDOMBluetoothAdapter : nsIDO
    * @param aProfile 2-octets service UUID
    */
   nsIDOMDOMRequest connect(in DOMString aDeviceAddress, in unsigned short aProfile);
   nsIDOMDOMRequest disconnect(in unsigned short aProfile);
 
   // One device can only send one file at a time
   nsIDOMDOMRequest sendFile(in DOMString aDeviceAddress, in nsIDOMBlob aBlob);
   nsIDOMDOMRequest stopSendingFile(in DOMString aDeviceAddress);
+  nsIDOMDOMRequest confirmReceivingFile(in DOMString aDeviceAddress, in bool aConfirmation);
 
   // Fired when discoverying and any device is discovered.
   [implicit_jscontext] attribute jsval ondevicefound;
   // Fired when any device is out of discoverable range.
   [implicit_jscontext] attribute jsval ondevicedisappeared;
   // Fired when any device is created.
   [implicit_jscontext] attribute jsval ondevicecreated;
   // Fired when a property of the adapter is changed
--- a/dom/camera/GonkRecorder.cpp
+++ b/dom/camera/GonkRecorder.cpp
@@ -221,17 +221,17 @@ status_t GonkRecorder::setOutputFile(int
     if (mOutputFd >= 0) {
         ::close(mOutputFd);
     }
     mOutputFd = dup(fd);
 
     return OK;
 }
 
-// Attempt to parse an int64 literal optionally surrounded by whitespace,
+// Attempt to parse an int64_t literal optionally surrounded by whitespace,
 // returns true on success, false otherwise.
 static bool safe_strtoi64(const char *s, int64_t *val) {
     char *end;
 
     // It is lame, but according to man page, we have to set errno to 0
     // before calling strtoll().
     errno = 0;
     *val = strtoll(s, &end, 10);
@@ -241,17 +241,17 @@ static bool safe_strtoi64(const char *s,
     }
 
     // Skip trailing whitespace
     while (isspace(*end)) {
         ++end;
     }
 
     // For a successful return, the string must contain nothing but a valid
-    // int64 literal optionally surrounded by whitespace.
+    // int64_t literal optionally surrounded by whitespace.
 
     return *end == '\0';
 }
 
 // Return true if the value is in [0, 0x007FFFFFFF]
 static bool safe_strtoi32(const char *s, int32_t *val) {
     int64_t temp;
     if (safe_strtoi64(s, &temp)) {
--- a/dom/messages/SystemMessageInternal.js
+++ b/dom/messages/SystemMessageInternal.js
@@ -85,22 +85,32 @@ SystemMessageInternal.prototype = {
                                    { type: aType,
                                      msg: aMessage,
                                      manifest: aManifestURI.spec,
                                      uri: aPageURI.spec,
                                      msgID: messageID })
       });
     }
 
+    let pagesToOpen = {};
     this._pages.forEach(function(aPage) {
       if (!this._isPageMatched(aPage, aType, aPageURI.spec, aManifestURI.spec)) {
         return;
       }
 
-      this._openAppPage(aPage, aMessage, messageID);
+      // Queue this message in the corresponding pages.
+      this._queueMessage(aPage, aMessage, messageID);
+
+      // Open app pages to handle their pending messages.
+      // Note that we only need to open each app page once.
+      let key = this._createKeyForPage(aPage);
+      if (!pagesToOpen.hasOwnProperty(key)) {
+        this._openAppPage(aPage, aMessage);
+        pagesToOpen[key] = true;
+      }
     }, this);
   },
 
   broadcastMessage: function broadcastMessage(aType, aMessage) {
     // Buffer system messages until the webapps' registration is ready,
     // so that we can know the correct pages registered to be broadcasted.
     if (!this._webappsRegistryReady) {
       this._bufferedSysMsgs.push({ how: "broadcast",
@@ -110,29 +120,39 @@ SystemMessageInternal.prototype = {
     }
 
     // Give this message an ID so that we can identify the message and
     // clean it up from the pending message queue when apps receive it.
     let messageID = gUUIDGenerator.generateUUID().toString();
 
     debug("Broadcasting " + aType + " " + JSON.stringify(aMessage));
     // Find pages that registered an handler for this type.
+    let pagesToOpen = {};
     this._pages.forEach(function(aPage) {
       if (aPage.type == aType) {
         if (this._listeners[aPage.manifest]) {
           this._listeners[aPage.manifest].forEach(function sendMsg(aListener) {
             aListener.sendAsyncMessage("SystemMessageManager:Message",
                                        { type: aType,
                                          msg: aMessage,
                                          manifest: aPage.manifest,
                                          uri: aPage.uri,
                                          msgID: messageID })
           });
         }
-        this._openAppPage(aPage, aMessage, messageID);
+        // Queue this message in the corresponding pages.
+        this._queueMessage(aPage, aMessage, messageID);
+
+        // Open app pages to handle their pending messages.
+        // Note that we only need to open each app page once.
+        let key = this._createKeyForPage(aPage);
+        if (!pagesToOpen.hasOwnProperty(key)) {
+          this._openAppPage(aPage, aMessage);
+          pagesToOpen[key] = true;
+        }
       }
     }, this);
   },
 
   registerPage: function registerPage(aType, aPageURI, aManifestURI) {
     if (!aPageURI || !aManifestURI) {
       throw Cr.NS_ERROR_INVALID_ARG;
     }
@@ -261,37 +281,57 @@ SystemMessageInternal.prototype = {
               break;
           }
         }, this);
         this._bufferedSysMsgs.length = 0;
         break;
     }
   },
 
-  _openAppPage: function _openAppPage(aPage, aMessage, aMessageID) {
+  _queueMessage: function _queueMessage(aPage, aMessage, aMessageID) {
     // Queue the message for this page because we've never known if an app is
     // opened or not. We'll clean it up when the app has already received it.
     aPage.pendingMessages.push({ msg: aMessage, msgID: aMessageID });
     if (aPage.pendingMessages.length > kMaxPendingMessages) {
       aPage.pendingMessages.splice(0, 1);
     }
+  },
 
+  _openAppPage: function _openAppPage(aPage, aMessage) {
     // We don't need to send the full object to observers.
     let page = { uri: aPage.uri,
                  manifest: aPage.manifest,
                  type: aPage.type,
                  target: aMessage.target };
     debug("Asking to open " + JSON.stringify(page));
     Services.obs.notifyObservers(this, "system-messages-open-app", JSON.stringify(page));
   },
 
   _isPageMatched: function _isPageMatched(aPage, aType, aUri, aManifest) {
     return (aPage.type === aType &&
             aPage.manifest === aManifest &&
             aPage.uri === aUri)
   },
 
+  _createKeyForPage: function _createKeyForPage(aPage) {
+    let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"]
+                      .createInstance(Ci.nsIScriptableUnicodeConverter);
+    converter.charset = "UTF-8";
+
+    let hasher = Cc["@mozilla.org/security/hash;1"]
+                   .createInstance(Ci.nsICryptoHash);
+    hasher.init(hasher.SHA1);
+
+    // add uri and action to the hash
+    ["type", "manifest", "uri"].forEach(function(aProp) {
+      let data = converter.convertToByteArray(aPage[aProp], {});
+      hasher.update(data, data.length);
+    });
+
+    return hasher.finish(true);
+  },
+
   classID: Components.ID("{70589ca5-91ac-4b9e-b839-d6a88167d714}"),
 
   QueryInterface: XPCOMUtils.generateQI([Ci.nsISystemMessagesInternal, Ci.nsIObserver])
 }
 
 const NSGetFactory = XPCOMUtils.generateNSGetFactory([SystemMessageInternal]);
--- a/dom/network/interfaces/nsIMobileConnectionProvider.idl
+++ b/dom/network/interfaces/nsIMobileConnectionProvider.idl
@@ -9,19 +9,29 @@ interface nsIDOMMozMobileConnectionInfo;
 interface nsIDOMMozMobileNetworkInfo;
 interface nsIDOMDOMRequest;
 interface nsIDOMWindow;
 
 /**
  * XPCOM component (in the content process) that provides the mobile
  * network information.
  */
-[scriptable, uuid(bc1a82aa-2a1f-4a27-a5e7-614d06b72e0a)]
+[scriptable, uuid(3db24bfe-abc4-43a3-9183-07e516a33af9)]
 interface nsIMobileConnectionProvider : nsISupports
 {
+  /**
+   * Called when a content process registers receiving unsolicited messages from
+   * RadioInterfaceLayer in the chrome process. Only a content granted
+   * mobileconnection permission is allowed to register. Note that a content
+   * doesn't need to unregister because the chrome process will remove it from
+   * the registration list once the chrome receives a 'child-process-shutdown'
+   * message.
+   */
+  void registerMobileConnectionMsg();
+
   readonly attribute DOMString cardState;
   readonly attribute nsIDOMMozMobileICCInfo iccInfo;
   readonly attribute nsIDOMMozMobileConnectionInfo voiceConnectionInfo;
   readonly attribute nsIDOMMozMobileConnectionInfo dataConnectionInfo;
   readonly attribute DOMString networkSelectionMode;
 
   nsIDOMDOMRequest getNetworks(in nsIDOMWindow window);
   nsIDOMDOMRequest selectNetwork(in nsIDOMWindow window, in nsIDOMMozMobileNetworkInfo network);
--- a/dom/network/src/MobileConnection.cpp
+++ b/dom/network/src/MobileConnection.cpp
@@ -77,16 +77,18 @@ NS_IMPL_EVENT_HANDLER(MobileConnection, 
 MobileConnection::MobileConnection()
 {
   mProvider = do_GetService(NS_RILCONTENTHELPER_CONTRACTID);
 
   // Not being able to acquire the provider isn't fatal since we check
   // for it explicitly below.
   if (!mProvider) {
     NS_WARNING("Could not acquire nsIMobileConnectionProvider!");
+  } else {
+    mProvider->RegisterMobileConnectionMsg();
   }
 }
 
 void
 MobileConnection::Init(nsPIDOMWindow* aWindow)
 {
   BindToOwner(aWindow);
 
--- a/dom/plugins/base/android/android_npapi.h
+++ b/dom/plugins/base/android/android_npapi.h
@@ -1029,21 +1029,16 @@ struct ANPSurfaceInterfaceV0 : ANPInterf
   bool (*lock)(JNIEnv* env, jobject surface, ANPBitmap* bitmap, ANPRectI* dirtyRect);
   /** Given a locked surface handle (i.e. result of a successful call to lock)
         the surface is unlocked and the contents of the bitmap, specifically
         those inside the dirtyRect are written to the screen.
   */
   void (*unlock)(JNIEnv* env, jobject surface);
 };
 
-typedef int32_t   int32;
-typedef uint32_t uint32;
-typedef int16_t   int16;
-typedef uint16_t uint16;
-
 /**
  * TODO should we not use EGL and GL data types for ABI safety?
  */
 struct ANPTextureInfo {
     GLuint      textureId;
     uint32_t    width;
     uint32_t    height;
     GLenum      internalFormat;
--- a/dom/plugins/base/nsPluginInstanceOwner.cpp
+++ b/dom/plugins/base/nsPluginInstanceOwner.cpp
@@ -2707,18 +2707,18 @@ void nsPluginInstanceOwner::Paint(const 
   RECTL rectl;
   rectl.xLeft   = relDirtyRect.x + window->x;
   rectl.yBottom = relDirtyRect.y + window->y;
   rectl.xRight  = rectl.xLeft + relDirtyRect.width;
   rectl.yTop    = rectl.yBottom + relDirtyRect.height;
 
   NPEvent pluginEvent;
   pluginEvent.event = WM_PAINT;
-  pluginEvent.wParam = (uint32)aHPS;
-  pluginEvent.lParam = (uint32)&rectl;
+  pluginEvent.wParam = (uint32_t)aHPS;
+  pluginEvent.lParam = (uint32_t)&rectl;
   mInstance->HandleEvent(&pluginEvent, nullptr);
 }
 #endif
 
 #ifdef MOZ_WIDGET_ANDROID
 
 void nsPluginInstanceOwner::Paint(gfxContext* aContext,
                                   const gfxRect& aFrameRect,
--- a/dom/plugins/base/nsPluginsDirDarwin.cpp
+++ b/dom/plugins/base/nsPluginsDirDarwin.cpp
@@ -369,23 +369,23 @@ static bool IsCompatibleArch(nsIFile *fi
     if (packageType == 'BRPL' || packageType == 'IEPL' || packageType == 'NSPL') {
       // Get path to plugin as a C string.
       char executablePath[PATH_MAX];
       executablePath[0] = '\0';
       if (!::CFURLGetFileSystemRepresentation(pluginURL, true, (UInt8*)&executablePath, PATH_MAX)) {
         executablePath[0] = '\0';
       }
 
-      uint32 pluginLibArchitectures;
+      uint32_t pluginLibArchitectures;
       nsresult rv = mozilla::ipc::GeckoChildProcessHost::GetArchitecturesForBinary(executablePath, &pluginLibArchitectures);
       if (NS_FAILED(rv)) {
         return false;
       }
 
-      uint32 containerArchitectures = mozilla::ipc::GeckoChildProcessHost::GetSupportedArchitecturesForProcessType(GeckoProcessType_Plugin);
+      uint32_t containerArchitectures = mozilla::ipc::GeckoChildProcessHost::GetSupportedArchitecturesForProcessType(GeckoProcessType_Plugin);
 
       // Consider the plugin architecture valid if there is any overlap in the masks.
       isPluginFile = !!(containerArchitectures & pluginLibArchitectures);
     }
     ::CFRelease(pluginBundle);
   }
 
   ::CFRelease(pluginURL);
--- a/dom/src/json/nsJSON.cpp
+++ b/dom/src/json/nsJSON.cpp
@@ -571,17 +571,17 @@ nsJSONListener::OnStopRequest(nsIRequest
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   js::RootedValue reviver(mCx, JS::NullValue()), value(mCx);
 
   JS::StableCharPtr chars(reinterpret_cast<const jschar*>(mBufferedChars.Elements()),
                           mBufferedChars.Length());
   JSBool ok = js::ParseJSONWithReviver(mCx, chars,
-                                       (uint32) mBufferedChars.Length(),
+                                       (uint32_t) mBufferedChars.Length(),
                                        reviver, &value,
                                        mDecodingMode);
 
   *mRootVal = value;
   mBufferedChars.TruncateLength(0);
   return ok ? NS_OK : NS_ERROR_FAILURE;
 }
 
--- a/dom/system/gonk/RILContentHelper.js
+++ b/dom/system/gonk/RILContentHelper.js
@@ -509,16 +509,31 @@ RILContentHelper.prototype = {
   registerVoicemailCallback: function registerVoicemailCallback(callback) {
     this.registerCallback("_voicemailCallbacks", callback);
   },
 
   unregisterVoicemailCallback: function unregisteVoicemailCallback(callback) {
     this.unregisterCallback("_voicemailCallbacks", callback);
   },
 
+  registerTelephonyMsg: function registerTelephonyMsg() {
+    debug("Registering for telephony-related messages");
+    cpmm.sendAsyncMessage("RIL:RegisterTelephonyMsg");
+  },
+
+  registerMobileConnectionMsg: function registerMobileConnectionMsg() {
+    debug("Registering for mobile connection-related messages");
+    cpmm.sendAsyncMessage("RIL:RegisterMobileConnectionMsg");
+  },
+
+  registerVoicemailMsg: function registerVoicemailMsg() {
+    debug("Registering for voicemail-related messages");
+    cpmm.sendAsyncMessage("RIL:RegisterVoicemailMsg");
+  },
+
   enumerateCalls: function enumerateCalls(callback) {
     debug("Requesting enumeration of calls for callback: " + callback);
     // We need 'requestId' to meet the 'RILContentHelper <--> RadioInterfaceLayer'
     // protocol.
     let requestId = this._getRandomId();
     cpmm.sendAsyncMessage("RIL:EnumerateCalls", {requestId: requestId});
     if (!this._enumerationTelephonyCallbacks) {
       this._enumerationTelephonyCallbacks = [];
--- a/dom/system/gonk/RadioInterfaceLayer.js
+++ b/dom/system/gonk/RadioInterfaceLayer.js
@@ -54,31 +54,37 @@ const RIL_IPC_TELEPHONY_MSG_NAMES = [
   "RIL:StopTone",
   "RIL:Dial",
   "RIL:DialEmergency",
   "RIL:HangUp",
   "RIL:AnswerCall",
   "RIL:RejectCall",
   "RIL:HoldCall",
   "RIL:ResumeCall",
+  "RIL:RegisterTelephonyMsg"
 ];
 
 const RIL_IPC_MOBILECONNECTION_MSG_NAMES = [
   "RIL:GetRilContext",
   "RIL:GetAvailableNetworks",
   "RIL:SelectNetwork",
   "RIL:SelectNetworkAuto",
   "RIL:GetCardLock",
   "RIL:UnlockCardLock",
   "RIL:SetCardLock",
   "RIL:SendMMI",
   "RIL:CancelMMI",
   "RIL:SendStkResponse",
   "RIL:SendStkMenuSelection",
   "RIL:SendStkEventDownload",
+  "RIL:RegisterMobileConnectionMsg"
+];
+
+const RIL_IPC_VOICEMAIL_MSG_NAMES = [
+  "RIL:RegisterVoicemailMsg"
 ];
 
 XPCOMUtils.defineLazyServiceGetter(this, "gSmsService",
                                    "@mozilla.org/sms/smsservice;1",
                                    "nsISmsService");
 
 XPCOMUtils.defineLazyServiceGetter(this, "gSmsRequestManager",
                                    "@mozilla.org/sms/smsrequestmanager;1",
@@ -246,22 +252,30 @@ function RadioInterfaceLayer() {
   lock.get("ril.callwaiting.enabled", this);
 
   // Read the 'time.nitz.automatic-update.enabled' setting to see if
   // we need to adjust the system clock time and time zone by NITZ.
   lock.get(kTimeNitzAutomaticUpdateEnabled, this);
 
   this._messageManagerByRequest = {};
 
+  // Manage message targets in terms of permission. Only the authorized and
+  // registered contents can receive related messages.
+  this._messageManagerByPermission = {};
+
+  ppmm.addMessageListener("child-process-shutdown", this);
   for (let msgname of RIL_IPC_TELEPHONY_MSG_NAMES) {
     ppmm.addMessageListener(msgname, this);
   }
   for (let msgname of RIL_IPC_MOBILECONNECTION_MSG_NAMES) {
     ppmm.addMessageListener(msgname, this);
   }
+  for (let msgname of RIL_IPC_VOICEMAIL_MSG_NAMES) {
+    ppmm.addMessageListener(msgname, this);
+  }
   Services.obs.addObserver(this, "xpcom-shutdown", false);
   Services.obs.addObserver(this, kMozSettingsChangedObserverTopic, false);
   Services.obs.addObserver(this, kSysMsgListenerReadyObserverTopic, false);
 
   this._sentSmsEnvelopes = {};
 
   this.portAddressedSmsApps = {};
   this.portAddressedSmsApps[WAP.WDP_PORT_PUSH] = this.handleSmsWdpPortPush.bind(this);
@@ -279,28 +293,44 @@ RadioInterfaceLayer.prototype = {
                                          Ci.nsIObserver,
                                          Ci.nsISettingsServiceCallback]),
 
   /**
    * Process a message from the content process.
    */
   receiveMessage: function receiveMessage(msg) {
     debug("Received '" + msg.name + "' message from content process");
+    if (msg.name == "child-process-shutdown") {
+      // By the time we receive child-process-shutdown, the child process has
+      // already forgotten its permissions so we need to unregister for both
+      // telephony and mobile connection messages.
+      this.unregisterTelephonyTarget(msg.target);
+      this.unregisterMobileConnectionTarget(msg.target);
+      this.unregisterVoicemailTarget(msg.target);
+      return;
+    }
+
     if (RIL_IPC_TELEPHONY_MSG_NAMES.indexOf(msg.name) != -1) {
       if (!msg.target.assertPermission("telephony")) {
         debug("Telephony message " + msg.name +
               " from a content process with no 'telephony' privileges.");
         return null;
       }
     } else if (RIL_IPC_MOBILECONNECTION_MSG_NAMES.indexOf(msg.name) != -1) {
       if (!msg.target.assertPermission("mobileconnection")) {
         debug("MobileConnection message " + msg.name +
               " from a content process with no 'mobileconnection' privileges.");
         return null;
       }
+    } else if (RIL_IPC_VOICEMAIL_MSG_NAMES.indexOf(msg.name) != -1) {
+      if (!msg.target.assertPermission("voicemail")) {
+        debug("Voicemail message " + msg.name +
+              " from a content process with no 'voicemail' privileges.");
+        return null;
+      }
     } else {
       debug("Ignoring unknown message type: " + msg.name);
       return null;
     }
 
     switch (msg.name) {
       case "RIL:GetRilContext":
         // This message is sync.
@@ -343,27 +373,31 @@ RadioInterfaceLayer.prototype = {
         this.rejectCall(msg.json);
         break;
       case "RIL:HoldCall":
         this.holdCall(msg.json);
         break;
       case "RIL:ResumeCall":
         this.resumeCall(msg.json);
         break;
+      case "RIL:RegisterTelephonyMsg":
+        this.registerTelephonyTarget(msg.target);
+        break;
       case "RIL:GetAvailableNetworks":
         this.saveRequestTarget(msg);
         this.getAvailableNetworks(msg.json.requestId);
         break;
       case "RIL:SelectNetwork":
         this.saveRequestTarget(msg);
         this.selectNetwork(msg.json);
         break;
       case "RIL:SelectNetworkAuto":
         this.saveRequestTarget(msg);
         this.selectNetworkAuto(msg.json.requestId);
+        break;
       case "RIL:GetCardLock":
         this.saveRequestTarget(msg);
         this.getCardLock(msg.json);
         break;
       case "RIL:UnlockCardLock":
         this.saveRequestTarget(msg);
         this.unlockCardLock(msg.json);
         break;
@@ -383,16 +417,22 @@ RadioInterfaceLayer.prototype = {
         this.sendStkResponse(msg.json);
         break;
       case "RIL:SendStkMenuSelection":
         this.sendStkMenuSelection(msg.json);
         break;
       case "RIL:SendStkEventDownload":
         this.sendStkEventDownload(msg.json);
         break;
+      case "RIL:RegisterMobileConnectionMsg":
+        this.registerMobileConnectionTarget(msg.target);
+        break;
+      case "RIL:RegisterVoicemailMsg":
+        this.registerVoicemailTarget(msg.target);
+        break;
     }
   },
 
   onerror: function onerror(event) {
     debug("Got an error: " + event.filename + ":" +
           event.lineno + ": " + event.message + "\n");
     event.preventDefault();
   },
@@ -453,17 +493,17 @@ RadioInterfaceLayer.prototype = {
       case "operatorchange":
         this.handleOperatorChange(message);
         break;
       case "radiostatechange":
         this.handleRadioStateChange(message);
         break;
       case "cardstatechange":
         this.rilContext.cardState = message.cardState;
-        ppmm.broadcastAsyncMessage("RIL:CardStateChanged", message);
+        this._sendMobileConnectionMessage("RIL:CardStateChanged", message);
         break;
       case "setCallWaiting":
         this.handleCallWaitingStatusChange(message);
         break;
       case "sms-received":
         this.handleSmsReceived(message);
         return;
       case "sms-sent":
@@ -500,17 +540,17 @@ RadioInterfaceLayer.prototype = {
         if (callback) {
           delete this._contactsCallbacks[message.requestId];
           callback.receiveContactsList(message.errorMsg,
                                        message.contactType,
                                        message.contacts);
         }
         break;
       case "iccmbdn":
-        ppmm.broadcastAsyncMessage("RIL:VoicemailNumberChanged", message);
+        this._sendVoicemailMessage("RIL:VoicemailNumberChanged", message);
         break;
       case "USSDReceived":
         debug("USSDReceived " + JSON.stringify(message));
         this.handleUSSDReceived(message);
         break;
       case "sendMMI":
       case "sendUSSD":
         this.handleSendMMI(message);
@@ -518,17 +558,17 @@ RadioInterfaceLayer.prototype = {
       case "cancelMMI":
       case "cancelUSSD":
         this.handleCancelMMI(message);
         break;
       case "stkcommand":
         this.handleStkProactiveCommand(message);
         break;
       case "stksessionend":
-        ppmm.broadcastAsyncMessage("RIL:StkSessionEnd", null);
+        this._sendMobileConnectionMessage("RIL:StkSessionEnd", null);
         break;
       case "setPreferredNetworkType":
         this.handleSetPreferredNetworkType(message);
         break;
       case "stkcallsetup":
         // A call has been placed by the STK app. We shall launch the dialer
         // app by sending a system message, in order to further control the
         // call, e.g. hang it up.
@@ -559,16 +599,96 @@ RadioInterfaceLayer.prototype = {
 
     if (!target) {
       return;
     }
 
     target.sendAsyncMessage(requestType, options);
   },
 
+  _messageManagerByPermission: null,
+  registerMessageTarget: function registerMessageTarget(permission, target) {
+    let targets = this._messageManagerByPermission[permission];
+    if (!targets) {
+      targets = this._messageManagerByPermission[permission] = [];
+    }
+
+    if (targets.indexOf(target) != -1) {
+      debug("Already registered this target!");
+      return;
+    }
+
+    targets.push(target);
+    debug("Registered " + permission + " target: " + target);
+  },
+
+  unregisterMessageTarget: function unregisterMessageTarget(permission, target) {
+    let targets = this._messageManagerByPermission[permission];
+    if (!targets) {
+      return;
+    }
+
+    let index = targets.indexOf(target);
+    if (index != -1) {
+      targets.splice(index, 1);
+      debug("Unregistered " + permission + " target: " + target);
+    }
+  },
+
+  registerTelephonyTarget: function registerTelephonyTarget(target) {
+    this.registerMessageTarget("telephony", target);
+  },
+
+  registerMobileConnectionTarget: function registerMobileConnectionTarget(target) {
+    this.registerMessageTarget("mobileconnection", target);
+  },
+
+  registerVoicemailTarget: function registerVoicemailTarget(target) {
+    this.registerMessageTarget("voicemail", target);
+  },
+
+  unregisterTelephonyTarget: function unregisterTelephonyTarget(target) {
+    this.unregisterMessageTarget("telephony", target);
+  },
+
+  unregisterMobileConnectionTarget: function unregisterMobileConnectionTarget(target) {
+    this.unregisterMessageTarget("mobileconnection", target);
+  },
+
+  unregisterVoicemailTarget: function unregisterVoicemailTarget(target) {
+    this.unregisterMessageTarget("voicemail", target);
+  },
+
+  _sendTargetMessage: function _sendTargetMessage(permission, message, options) {
+    let thisTargets = this._messageManagerByPermission[permission];
+    if (!thisTargets) {
+      return;
+    }
+
+    let targets = thisTargets.slice();
+    for each (let target in targets) {
+      if (thisTargets.indexOf(target) == -1) {
+        continue;
+      }
+      target.sendAsyncMessage(message, options);
+    }
+  },
+
+  _sendTelephonyMessage: function sendTelephonyMessage(message, options) {
+    this._sendTargetMessage("telephony", message, options);
+  },
+
+  _sendMobileConnectionMessage: function sendMobileConnectionMessage(message, options) {
+    this._sendTargetMessage("mobileconnection", message, options);
+  },
+
+  _sendVoicemailMessage: function sendVoicemailMessage(message, options) {
+    this._sendTargetMessage("voicemail", message, options);
+  },
+
   updateNetworkInfo: function updateNetworkInfo(message) {
     let voiceMessage = message[RIL.NETWORK_INFO_VOICE_REGISTRATION_STATE];
     let dataMessage = message[RIL.NETWORK_INFO_DATA_REGISTRATION_STATE];
     let operatorMessage = message[RIL.NETWORK_INFO_OPERATOR];
     let selectionMessage = message[RIL.NETWORK_INFO_NETWORK_SELECTION_MODE];
 
     // Batch the *InfoChanged messages together
     if (voiceMessage) {
@@ -592,20 +712,20 @@ RadioInterfaceLayer.prototype = {
         data.network = operatorMessage;
       }
     }
 
     this.checkRoamingBetweenOperators(voice);
     this.checkRoamingBetweenOperators(data);
 
     if (voiceMessage || operatorMessage) {
-      ppmm.broadcastAsyncMessage("RIL:VoiceInfoChanged", voice);
+      this._sendMobileConnectionMessage("RIL:VoiceInfoChanged", voice);
     }
     if (dataMessage || operatorMessage) {
-      ppmm.broadcastAsyncMessage("RIL:DataInfoChanged", data);
+      this._sendMobileConnectionMessage("RIL:DataInfoChanged", data);
     }
 
     if (selectionMessage) {
       this.updateNetworkSelectionMode(selectionMessage);
     }
   },
 
   /**
@@ -669,17 +789,17 @@ RadioInterfaceLayer.prototype = {
     let newCell = newInfo.cell;
     if ((newCell.gsmLocationAreaCode < 0) || (newCell.gsmCellId < 0)) {
       voiceInfo.cell = null;
     } else {
       voiceInfo.cell = newCell;
     }
 
     if (!newInfo.batch) {
-      ppmm.broadcastAsyncMessage("RIL:VoiceInfoChanged", voiceInfo);
+      this._sendMobileConnectionMessage("RIL:VoiceInfoChanged", voiceInfo);
     }
   },
 
   updateDataConnection: function updateDataConnection(newInfo) {
     let dataInfo = this.rilContext.data;
     dataInfo.state = newInfo.state;
     dataInfo.roaming = newInfo.roaming;
     dataInfo.emergencyCallsOnly = newInfo.emergencyCallsOnly;
@@ -699,28 +819,28 @@ RadioInterfaceLayer.prototype = {
     let newCell = newInfo.cell;
     if ((newCell.gsmLocationAreaCode < 0) || (newCell.gsmCellId < 0)) {
       dataInfo.cell = null;
     } else {
       dataInfo.cell = newCell;
     }
 
     if (!newInfo.batch) {
-      ppmm.broadcastAsyncMessage("RIL:DataInfoChanged", dataInfo);
+      this._sendMobileConnectionMessage("RIL:DataInfoChanged", dataInfo);
     }
     this.updateRILNetworkInterface();
   },
 
   /**
    * Handle data errors
    */
   handleDataCallError: function handleDataCallError(message) {
     // Notify data call error only for data APN
     if (message.apn == this.dataCallSettings["apn"]) {
-      ppmm.broadcastAsyncMessage("RIL:DataError", message);
+      this._sendMobileConnectionMessage("RIL:DataError", message);
     }
 
     this._deliverDataCallCallback("dataCallError", [message]);
   },
 
   _preferredNetworkType: null,
   setPreferredNetworkType: function setPreferredNetworkType(value) {
     let networkType = RIL.RIL_PREFERRED_NETWORK_TYPE_TO_GECKO.indexOf(value);
@@ -756,25 +876,25 @@ RadioInterfaceLayer.prototype = {
 
   handleSignalStrengthChange: function handleSignalStrengthChange(message) {
     let voiceInfo = this.rilContext.voice;
     // TODO CDMA, EVDO, LTE, etc. (see bug 726098)
     if (voiceInfo.signalStrength != message.gsmDBM ||
         voiceInfo.relSignalStrength != message.gsmRelative) {
       voiceInfo.signalStrength = message.gsmDBM;
       voiceInfo.relSignalStrength = message.gsmRelative;
-      ppmm.broadcastAsyncMessage("RIL:VoiceInfoChanged", voiceInfo);
+      this._sendMobileConnectionMessage("RIL:VoiceInfoChanged", voiceInfo);
     }
 
     let dataInfo = this.rilContext.data;
     if (dataInfo.signalStrength != message.gsmDBM ||
         dataInfo.relSignalStrength != message.gsmRelative) {
       dataInfo.signalStrength = message.gsmDBM;
       dataInfo.relSignalStrength = message.gsmRelative;
-      ppmm.broadcastAsyncMessage("RIL:DataInfoChanged", dataInfo);
+      this._sendMobileConnectionMessage("RIL:DataInfoChanged", dataInfo);
     }
   },
 
   networkChanged: function networkChanged(srcNetwork, destNetwork) {
     return !destNetwork ||
       destNetwork.longName != srcNetwork.longName ||
       destNetwork.shortName != srcNetwork.shortName ||
       destNetwork.mnc != srcNetwork.mnc ||
@@ -782,22 +902,22 @@ RadioInterfaceLayer.prototype = {
   },
 
   handleOperatorChange: function handleOperatorChange(message) {
     let voice = this.rilContext.voice;
     let data = this.rilContext.data;
 
     if (this.networkChanged(message, voice.network)) {
       voice.network = message;
-      ppmm.broadcastAsyncMessage("RIL:VoiceInfoChanged", voice);
+      this._sendMobileConnectionMessage("RIL:VoiceInfoChanged", voice);
     }
 
     if (this.networkChanged(message, data.network)) {
       data.network = message;
-      ppmm.broadcastAsyncMessage("RIL:DataInfoChanged", data);
+      this._sendMobileConnectionMessage("RIL:DataInfoChanged", data);
     }
   },
 
   handleRadioStateChange: function handleRadioStateChange(message) {
     this._changingRadioPower = false;
 
     let newState = message.radioState;
     if (this.rilContext.radioState == newState) {
@@ -984,30 +1104,30 @@ RadioInterfaceLayer.prototype = {
     if (call.isActive) {
       this._activeCall = call;
     } else if (this._activeCall &&
                this._activeCall.callIndex == call.callIndex) {
       // Previously active call is not active now.
       this._activeCall = null;
     }
     this.updateCallAudioState();
-    ppmm.broadcastAsyncMessage("RIL:CallStateChanged", call);
+    this._sendTelephonyMessage("RIL:CallStateChanged", call);
   },
 
   /**
    * Handle call disconnects by updating our current state and the audio system.
    */
   handleCallDisconnected: function handleCallDisconnected(call) {
     debug("handleCallDisconnected: " + JSON.stringify(call));
     if (call.isActive) {
       this._activeCall = null;
     }
     this.updateCallAudioState();
     call.state = nsIRadioInterfaceLayer.CALL_STATE_DISCONNECTED;
-    ppmm.broadcastAsyncMessage("RIL:CallStateChanged", call);
+    this._sendTelephonyMessage("RIL:CallStateChanged", call);
   },
 
   /**
    * Handle calls delivered in response to a 'enumerateCalls' request.
    */
   handleEnumerateCalls: function handleEnumerateCalls(options) {
     debug("handleEnumerateCalls: " + JSON.stringify(options));
     for (let i in options.calls) {
@@ -1025,17 +1145,17 @@ RadioInterfaceLayer.prototype = {
     this._sendRequestResults("RIL:GetAvailableNetworks", message);
   },
 
   /**
    * Update network selection mode
    */
   updateNetworkSelectionMode: function updateNetworkSelectionMode(message) {
     debug("updateNetworkSelectionMode: " + JSON.stringify(message));
-    ppmm.broadcastAsyncMessage("RIL:NetworkSelectionModeChanged", message);
+    this._sendMobileConnectionMessage("RIL:NetworkSelectionModeChanged", message);
   },
 
   /**
    * Handle "manual" network selection request.
    */
   handleSelectNetwork: function handleSelectNetwork(message) {
     debug("handleSelectNetwork: " + JSON.stringify(message));
     this._sendRequestResults("RIL:SelectNetwork", message);
@@ -1048,17 +1168,17 @@ RadioInterfaceLayer.prototype = {
     debug("handleSelectNetworkAuto: " + JSON.stringify(message));
     this._sendRequestResults("RIL:SelectNetworkAuto", message);
   },
 
   /**
    * Handle call error.
    */
   handleCallError: function handleCallError(message) {
-    ppmm.broadcastAsyncMessage("RIL:CallError", message);   
+    this._sendTelephonyMessage("RIL:CallError", message);
   },
 
   /**
    * Handle WDP port push PDU. Constructor WDP bearer information and deliver
    * to WapPushManager.
    *
    * @param message
    *        A SMS message.
@@ -1109,17 +1229,17 @@ RadioInterfaceLayer.prototype = {
     // For now we don't store indicators persistently. When the mwi.discard
     // flag is false, we'll need to persist the indicator to EFmwis.
     // See TS 23.040 9.2.3.24.2
 
     let mwi = message.mwi;
     if (mwi) {
       mwi.returnNumber = message.sender || null;
       mwi.returnMessage = message.fullBody || null;
-      ppmm.broadcastAsyncMessage("RIL:VoicemailNotification", mwi);
+      this._sendVoicemailMessage("RIL:VoicemailNotification", mwi);
       return;
     }
 
     let id = -1;
     if (message.messageClass != RIL.PDU_DCS_MSG_CLASS_0) {
       id = gSmsDatabaseService.saveReceivedMessage(message.sender || null,
                                                    message.fullBody || null,
                                                    message.timestamp);
@@ -1225,17 +1345,17 @@ RadioInterfaceLayer.prototype = {
    * Handle data call state changes.
    */
   handleDataCallState: function handleDataCallState(datacall) {
     let data = this.rilContext.data;
 
     if (datacall.ifname &&
         datacall.apn == this.dataCallSettings["apn"]) {
       data.connected = (datacall.state == RIL.GECKO_NETWORK_STATE_CONNECTED);
-      ppmm.broadcastAsyncMessage("RIL:DataInfoChanged", data);
+      this._sendMobileConnectionMessage("RIL:DataInfoChanged", data);
     }
 
     this._deliverDataCallCallback("dataCallStateChanged",
                                   [datacall]);
   },
 
   /**
    * Handle data call list.
@@ -1282,26 +1402,26 @@ RadioInterfaceLayer.prototype = {
                          oldIcc.iccid != message.iccid ||
                          oldIcc.mcc != message.mcc || 
                          oldIcc.mnc != message.mnc;
     if (!iccInfoChanged) {
       return;
     }
     // RIL:IccInfoChanged corresponds to a DOM event that gets fired only
     // when the MCC or MNC codes have changed.
-    ppmm.broadcastAsyncMessage("RIL:IccInfoChanged", message);
+    this._sendMobileConnectionMessage("RIL:IccInfoChanged", message);
   },
 
   handleICCCardLockResult: function handleICCCardLockResult(message) {
     this._sendRequestResults("RIL:CardLockResult", message);
   },
 
   handleUSSDReceived: function handleUSSDReceived(ussd) {
     debug("handleUSSDReceived " + JSON.stringify(ussd));
-    ppmm.broadcastAsyncMessage("RIL:USSDReceived", ussd);
+    this._sendMobileConnectionMessage("RIL:UssdReceived", ussd);
   },
 
   handleSendMMI: function handleSendMMI(message) {
     debug("handleSendMMI " + JSON.stringify(message));
     let messageType = message.success ? "RIL:SendMMI:Return:OK" :
                                         "RIL:SendMMI:Return:KO";
     this._sendRequestResults(messageType, message);
   },
@@ -1311,39 +1431,43 @@ RadioInterfaceLayer.prototype = {
     let messageType = message.success ? "RIL:CancelMMI:Return:OK" :
                                         "RIL:CancelMMI:Return:KO";
     this._sendRequestResults(messageType, message);
   },
 
   handleStkProactiveCommand: function handleStkProactiveCommand(message) {
     debug("handleStkProactiveCommand " + JSON.stringify(message));
     gSystemMessenger.broadcastMessage("icc-stkcommand", message);
-    ppmm.broadcastAsyncMessage("RIL:StkCommand", message);
+    this._sendMobileConnectionMessage("RIL:StkCommand", message);
   },
 
   // nsIObserver
 
   observe: function observe(subject, topic, data) {
     switch (topic) {
       case kSysMsgListenerReadyObserverTopic:
         Services.obs.removeObserver(this, kSysMsgListenerReadyObserverTopic);
         this._sysMsgListenerReady = true;
         this._ensureRadioState();
         break;
       case kMozSettingsChangedObserverTopic:
         let setting = JSON.parse(data);
         this.handle(setting.key, setting.value);
         break;
       case "xpcom-shutdown":
+        ppmm.removeMessageListener("child-process-shutdown", this);
         for (let msgname of RIL_IPC_TELEPHONY_MSG_NAMES) {
           ppmm.removeMessageListener(msgname, this);
         }
         for (let msgname of RIL_IPC_MOBILECONNECTION_MSG_NAMES) {
           ppmm.removeMessageListener(msgname, this);
         }
+        for (let msgname of RIL_IPC_VOICEMAIL_MSG_NAMES) {
+          ppmm.removeMessageListener(msgname, this);
+        }
         // Shutdown all RIL network interfaces
         this.dataNetworkInterface.shutdown();
         this.mmsNetworkInterface.shutdown();
         this.suplNetworkInterface.shutdown();
         ppmm = null;
         Services.obs.removeObserver(this, "xpcom-shutdown");
         Services.obs.removeObserver(this, kMozSettingsChangedObserverTopic);
         break;
--- a/dom/system/gonk/nsIRadioInterfaceLayer.idl
+++ b/dom/system/gonk/nsIRadioInterfaceLayer.idl
@@ -134,26 +134,44 @@ interface nsIRILContactCallback : nsISup
                            in DOMString contactType,
                            in jsval contacts);
 };
 
 /**
  * Helper that runs in the content process and exposes information
  * to the DOM.
  */
-[scriptable, uuid(31ea634b-e710-49ce-bb7d-bfcbaa40fb00)]
+[scriptable, uuid(2abe554b-e07c-44b0-9719-02190460188d)]
 interface nsIRILContentHelper : nsIMobileConnectionProvider
 {
   void registerTelephonyCallback(in nsIRILTelephonyCallback callback);
   void unregisterTelephonyCallback(in nsIRILTelephonyCallback callback);
 
   void registerVoicemailCallback(in nsIRILVoicemailCallback callback);
   void unregisterVoicemailCallback(in nsIRILVoicemailCallback callback);
 
   /**
+   * Called when a content process registers receiving unsolicited messages from
+   * RadioInterfaceLayer in the chrome process. Only content granted telephony
+   * permission is allowed to register. Note that a content doesn't need to
+   * unregister because the chrome process will remove it from the registration
+   * list once the chrome receives a 'child-process-shutdown' message.
+   */
+   void registerTelephonyMsg();
+
+  /**
+   * Called when a content process registers receiving unsolicited messages from
+   * RadioInterfaceLayer in the chrome process. Only a content granted voice
+   * mail permission is allowed to register. Note that a content doesn't need to
+   * unregister because the chrome process will remove it from the registration
+   * list once the chrome receives a 'child-process-shutdown' message.
+   */
+   void registerVoicemailMsg();
+
+  /**
    * Will continue calling callback.enumerateCallState until the callback
    * returns false.
    */
   void enumerateCalls(in nsIRILTelephonyCallback callback);
 
   /**
    * Functionality for making and managing phone calls.
    */
--- a/dom/telephony/Telephony.cpp
+++ b/dom/telephony/Telephony.cpp
@@ -89,16 +89,19 @@ Telephony::Create(nsPIDOMWindow* aOwner,
   telephony->mRILTelephonyCallback = new RILTelephonyCallback(telephony);
 
   nsresult rv = aRIL->EnumerateCalls(telephony->mRILTelephonyCallback);
   NS_ENSURE_SUCCESS(rv, nullptr);
 
   rv = aRIL->RegisterTelephonyCallback(telephony->mRILTelephonyCallback);
   NS_ENSURE_SUCCESS(rv, nullptr);
 
+  rv = aRIL->RegisterTelephonyMsg();
+  NS_ENSURE_SUCCESS(rv, nullptr);
+
   return telephony.forget();
 }
 
 already_AddRefed<TelephonyCall>
 Telephony::CreateNewDialingCall(const nsAString& aNumber)
 {
   nsRefPtr<TelephonyCall> call =
     TelephonyCall::Create(this, aNumber,
--- a/dom/telephony/Voicemail.cpp
+++ b/dom/telephony/Voicemail.cpp
@@ -45,16 +45,21 @@ Voicemail::Voicemail(nsPIDOMWindow* aWin
   BindToOwner(aWindow);
 
   mRILVoicemailCallback = new RILVoicemailCallback(this);
 
   nsresult rv = aRIL->RegisterVoicemailCallback(mRILVoicemailCallback);
   if (NS_FAILED(rv)) {
     NS_WARNING("Failed registering voicemail callback with RIL");
   }
+
+  rv = aRIL->RegisterVoicemailMsg();
+  if (NS_FAILED(rv)) {
+    NS_WARNING("Failed registering voicemail messages with RIL");
+  }
 }
 
 Voicemail::~Voicemail()
 {
   if (mRIL && mRILVoicemailCallback) {
     mRIL->UnregisterVoicemailCallback(mRILVoicemailCallback);
   }
 }
--- a/dom/workers/Events.cpp
+++ b/dom/workers/Events.cpp
@@ -219,17 +219,17 @@ private:
     delete GetJSPrivateSafeish<Event>(aObj);
   }
 
   static JSBool
   GetProperty(JSContext* aCx, JSHandleObject aObj, JSHandleId aIdval, JSMutableHandleValue aVp)
   {
     JS_ASSERT(JSID_IS_INT(aIdval));
 
-    int32 slot = JSID_TO_INT(aIdval);
+    int32_t slot = JSID_TO_INT(aIdval);
 
     const char*& name = sProperties[slot - SLOT_FIRST].name;
     if (!GetInstancePrivate(aCx, aObj, name)) {
       return false;
     }
 
     aVp.set(JS_GetReservedSlot(aObj, slot));
     return true;
@@ -512,17 +512,17 @@ private:
     }
   }
 
   static JSBool
   GetProperty(JSContext* aCx, JSHandleObject aObj, JSHandleId aIdval, JSMutableHandleValue aVp)
   {
     JS_ASSERT(JSID_IS_INT(aIdval));
 
-    int32 slot = JSID_TO_INT(aIdval);
+    int32_t slot = JSID_TO_INT(aIdval);
 
     JS_ASSERT(slot >= SLOT_data && slot < SLOT_COUNT);
 
     const char*& name = sProperties[slot - SLOT_FIRST].name;
     MessageEvent* event = GetInstancePrivate(aCx, aObj, name);
     if (!event) {
       return false;
     }
@@ -632,17 +632,17 @@ public:
     JSClass* clasp = aMainRuntime ? &sMainRuntimeClass : &sClass;
 
     return JS_InitClass(aCx, aObj, aParentProto, clasp, Construct, 0,
                         sProperties, sFunctions, NULL, NULL);
   }
 
   static JSObject*
   Create(JSContext* aCx, JSObject* aParent, JSString* aMessage,
-         JSString* aFilename, uint32 aLineNumber, bool aMainRuntime)
+         JSString* aFilename, uint32_t aLineNumber, bool aMainRuntime)
   {
     JSString* type = JS_InternString(aCx, "error");
     if (!type) {
       return NULL;
     }
 
     JSClass* clasp = aMainRuntime ? &sMainRuntimeClass : &sClass;
 
@@ -692,17 +692,17 @@ private:
                          classPtr->name);
     return NULL;
   }
 
   static void
   InitErrorEventCommon(JSObject* aObj, Event* aEvent, JSString* aType,
                        JSBool aBubbles, JSBool aCancelable,
                        JSString* aMessage, JSString* aFilename,
-                       uint32 aLineNumber, bool aIsTrusted)
+                       uint32_t aLineNumber, bool aIsTrusted)
   {
     Event::InitEventCommon(aObj, aEvent, aType, aBubbles, aCancelable,
                            aIsTrusted);
     JS_SetReservedSlot(aObj, SLOT_message, STRING_TO_JSVAL(aMessage));
     JS_SetReservedSlot(aObj, SLOT_filename, STRING_TO_JSVAL(aFilename));
     JS_SetReservedSlot(aObj, SLOT_lineno, INT_TO_JSVAL(aLineNumber));
   }
 
@@ -721,17 +721,17 @@ private:
     delete GetJSPrivateSafeish<ErrorEvent>(aObj);
   }
 
   static JSBool
   GetProperty(JSContext* aCx, JSHandleObject aObj, JSHandleId aIdval, JSMutableHandleValue aVp)
   {
     JS_ASSERT(JSID_IS_INT(aIdval));
 
-    int32 slot = JSID_TO_INT(aIdval);
+    int32_t slot = JSID_TO_INT(aIdval);
 
     JS_ASSERT(slot >= SLOT_message && slot < SLOT_COUNT);
 
     const char*& name = sProperties[slot - SLOT_FIRST].name;
     ErrorEvent* event = GetInstancePrivate(aCx, aObj, name);
     if (!event) {
       return false;
     }
@@ -901,17 +901,17 @@ private:
     delete GetJSPrivateSafeish<ProgressEvent>(aObj);
   }
 
   static JSBool
   GetProperty(JSContext* aCx, JSHandleObject aObj, JSHandleId aIdval, JSMutableHandleValue aVp)
   {
     JS_ASSERT(JSID_IS_INT(aIdval));
 
-    int32 slot = JSID_TO_INT(aIdval);
+    int32_t slot = JSID_TO_INT(aIdval);
 
     JS_ASSERT(slot >= SLOT_lengthComputable && slot < SLOT_COUNT);
 
     const char*& name = sProperties[slot - SLOT_FIRST].name;
     ProgressEvent* event = GetInstancePrivate(aCx, aObj, name);
     if (!event) {
       return false;
     }
@@ -1018,17 +1018,17 @@ CreateMessageEvent(JSContext* aCx, JSAut
                    bool aMainRuntime)
 {
   JSObject* global = JS_GetGlobalForScopeChain(aCx);
   return MessageEvent::Create(aCx, global, aData, aClonedObjects, aMainRuntime);
 }
 
 JSObject*
 CreateErrorEvent(JSContext* aCx, JSString* aMessage, JSString* aFilename,
-                 uint32 aLineNumber, bool aMainRuntime)
+                 uint32_t aLineNumber, bool aMainRuntime)
 {
   JSObject* global = JS_GetGlobalForScopeChain(aCx);
   return ErrorEvent::Create(aCx, global, aMessage, aFilename, aLineNumber,
                             aMainRuntime);
 }
 
 JSObject*
 CreateProgressEvent(JSContext* aCx, JSString* aType, bool aLengthComputable,
--- a/dom/workers/Events.h
+++ b/dom/workers/Events.h
@@ -23,17 +23,17 @@ CreateGenericEvent(JSContext* aCx, JSStr
 
 JSObject*
 CreateMessageEvent(JSContext* aCx, JSAutoStructuredCloneBuffer& aData,
                    nsTArray<nsCOMPtr<nsISupports> >& aClonedObjects,
                    bool aMainRuntime);
 
 JSObject*
 CreateErrorEvent(JSContext* aCx, JSString* aMessage, JSString* aFilename,
-                 uint32 aLineNumber, bool aMainRuntime);
+                 uint32_t aLineNumber, bool aMainRuntime);
 
 JSObject*
 CreateProgressEvent(JSContext* aCx, JSString* aType, bool aLengthComputable,
                     double aLoaded, double aTotal);
 
 bool
 IsSupportedEventClass(JSObject* aEvent);
 
--- a/dom/workers/Exceptions.cpp
+++ b/dom/workers/Exceptions.cpp
@@ -125,17 +125,17 @@ private:
     return true;
   }
 
   static JSBool
   GetProperty(JSContext* aCx, JSHandleObject aObj, JSHandleId aIdval, JSMutableHandleValue aVp)
   {
     JS_ASSERT(JSID_IS_INT(aIdval));
 
-    int32 slot = JSID_TO_INT(aIdval);
+    int32_t slot = JSID_TO_INT(aIdval);
 
     JSClass* classPtr = JS_GetClass(aObj);
 
     if (classPtr != &sClass || !GetJSPrivateSafeish<DOMException>(aObj)) {
       JS_ReportErrorNumber(aCx, js_GetErrorMessage, NULL,
                            JSMSG_INCOMPATIBLE_PROTO, sClass.name,
                            sProperties[slot].name, classPtr->name);
       return false;
--- a/dom/workers/RuntimeService.cpp
+++ b/dom/workers/RuntimeService.cpp
@@ -137,17 +137,16 @@ const char* gStringChars[] = {
 };
 
 MOZ_STATIC_ASSERT(NS_ARRAY_LENGTH(gStringChars) == ID_COUNT,
                   "gStringChars should have the right length.");
 
 enum {
   PREF_strict = 0,
   PREF_werror,
-  PREF_relimit,
   PREF_methodjit,
   PREF_methodjit_always,
   PREF_typeinference,
   PREF_allow_xml,
   PREF_jit_hardening,
   PREF_mem_max,
   PREF_ion,
 
@@ -158,17 +157,16 @@ enum {
   PREF_COUNT
 };
 
 #define JS_OPTIONS_DOT_STR "javascript.options."
 
 const char* gPrefsToWatch[] = {
   JS_OPTIONS_DOT_STR "strict",
   JS_OPTIONS_DOT_STR "werror",
-  JS_OPTIONS_DOT_STR "relimit",
   JS_OPTIONS_DOT_STR "methodjit.content",
   JS_OPTIONS_DOT_STR "methodjit_always",
   JS_OPTIONS_DOT_STR "typeinference",
   JS_OPTIONS_DOT_STR "allow_xml",
   JS_OPTIONS_DOT_STR "jit_hardening",
   JS_OPTIONS_DOT_STR "mem.max",
   JS_OPTIONS_DOT_STR "ion.content"
 
@@ -201,19 +199,16 @@ PrefCallback(const char* aPrefName, void
   else if (StringBeginsWith(nsDependentCString(aPrefName), jsOptionStr)) {
     uint32_t newOptions = kRequiredJSContextOptions;
     if (Preferences::GetBool(gPrefsToWatch[PREF_strict])) {
       newOptions |= JSOPTION_STRICT;
     }
     if (Preferences::GetBool(gPrefsToWatch[PREF_werror])) {
       newOptions |= JSOPTION_WERROR;
     }
-    if (Preferences::GetBool(gPrefsToWatch[PREF_relimit])) {
-      newOptions |= JSOPTION_RELIMIT;
-    }
     if (Preferences::GetBool(gPrefsToWatch[PREF_methodjit])) {
       newOptions |= JSOPTION_METHODJIT;
     }
     if (Preferences::GetBool(gPrefsToWatch[PREF_methodjit_always])) {
       newOptions |= JSOPTION_METHODJIT_ALWAYS;
     }
     if (Preferences::GetBool(gPrefsToWatch[PREF_typeinference])) {
       newOptions |= JSOPTION_TYPE_INFERENCE;
--- a/dom/workers/WorkerPrivate.cpp
+++ b/dom/workers/WorkerPrivate.cpp
@@ -3781,17 +3781,17 @@ WorkerPrivate::SetTimeout(JSContext* aCx
 
   JS_SET_RVAL(aCx, aVp, INT_TO_JSVAL(timerId));
 
   newInfo.forget();
   return true;
 }
 
 bool
-WorkerPrivate::ClearTimeout(JSContext* aCx, uint32 aId)
+WorkerPrivate::ClearTimeout(JSContext* aCx, uint32_t aId)
 {
   AssertIsOnWorkerThread();
 
   if (!mTimeouts.IsEmpty()) {
     NS_ASSERTION(mTimerRunning, "Huh?!");
 
     for (uint32_t index = 0; index < mTimeouts.Length(); index++) {
       nsAutoPtr<TimeoutInfo>& info = mTimeouts[index];
--- a/dom/workers/WorkerPrivate.h
+++ b/dom/workers/WorkerPrivate.h
@@ -670,17 +670,17 @@ public:
 
   void
   ReportError(JSContext* aCx, const char* aMessage, JSErrorReport* aReport);
 
   bool
   SetTimeout(JSContext* aCx, unsigned aArgc, jsval* aVp, bool aIsInterval);
 
   bool
-  ClearTimeout(JSContext* aCx, uint32 aId);
+  ClearTimeout(JSContext* aCx, uint32_t aId);
 
   bool
   RunExpiredTimeouts(JSContext* aCx);
 
   bool
   RescheduleTimeoutTimer(JSContext* aCx);
 
   void
--- a/dom/workers/WorkerScope.cpp
+++ b/dom/workers/WorkerScope.cpp
@@ -105,30 +105,30 @@ public:
   using EventTarget::GetEventListener;
   using EventTarget::SetEventListener;
 
 protected:
   WorkerGlobalScope(JSContext* aCx, WorkerPrivate* aWorker)
   : EventTarget(aCx), mWorker(aWorker)
   {
     MOZ_COUNT_CTOR(mozilla::dom::workers::WorkerGlobalScope);
-    for (int32 i = 0; i < SLOT_COUNT; i++) {
+    for (int32_t i = 0; i < SLOT_COUNT; i++) {
       mSlots[i] = JSVAL_VOID;
     }
   }
 
   ~WorkerGlobalScope()
   {
     MOZ_COUNT_DTOR(mozilla::dom::workers::WorkerGlobalScope);
   }
 
   virtual void
   _trace(JSTracer* aTrc) MOZ_OVERRIDE
   {
-    for (int32 i = 0; i < SLOT_COUNT; i++) {
+    for (int32_t i = 0; i < SLOT_COUNT; i++) {
       JS_CALL_VALUE_TRACER(aTrc, mSlots[i], "WorkerGlobalScope instance slot");
     }
     mWorker->TraceInternal(aTrc);
     EventTarget::_trace(aTrc);
   }
 
   virtual void
   _finalize(JSFreeOp* aFop) MOZ_OVERRIDE
--- a/extensions/gio/nsGIOProtocolHandler.cpp
+++ b/extensions/gio/nsGIOProtocolHandler.cpp
@@ -2,17 +2,17 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 /*
  * This code is based on original Mozilla gnome-vfs extension. It implements
  * input stream provided by GVFS/GIO.
 */
-#include "NSPRFormatTime.h" // must include before any headers that include prtime.h
+#include "NSPRFormatTime.h" // must be before anything that includes prtime.h
 #include "mozilla/ModuleUtils.h"
 #include "nsIPrefService.h"
 #include "nsIPrefBranch.h"
 #include "nsIObserver.h"
 #include "nsThreadUtils.h"
 #include "nsProxyRelease.h"
 #include "nsIStringBundle.h"
 #include "nsIStandardURL.h"
--- a/gfx/src/nsScriptableRegion.cpp
+++ b/gfx/src/nsScriptableRegion.cpp
@@ -129,17 +129,17 @@ NS_IMETHODIMP nsScriptableRegion::GetRec
 
   JSObject* destArray = JS_NewArrayObject(aCx, numRects * 4, NULL);
   if (!destArray) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
   *aRects = OBJECT_TO_JSVAL(destArray);
 
-  uint32 n = 0;
+  uint32_t n = 0;
   nsIntRegionRectIterator iter(mRegion);
   const nsIntRect *rect;
 
   while ((rect = iter.Next())) {
     if (!JS_DefineElement(aCx, destArray, n, INT_TO_JSVAL(rect->x), NULL, NULL, JSPROP_ENUMERATE) ||
         !JS_DefineElement(aCx, destArray, n + 1, INT_TO_JSVAL(rect->y), NULL, NULL, JSPROP_ENUMERATE) ||
         !JS_DefineElement(aCx, destArray, n + 2, INT_TO_JSVAL(rect->width), NULL, NULL, JSPROP_ENUMERATE) ||
         !JS_DefineElement(aCx, destArray, n + 3, INT_TO_JSVAL(rect->height), NULL, NULL, JSPROP_ENUMERATE)) {
--- a/gfx/thebes/gfxColor.h
+++ b/gfx/thebes/gfxColor.h
@@ -201,17 +201,17 @@ struct THEBES_API gfxRGBA {
     }
     bool operator!=(const gfxRGBA& other) const
     {
         return !(*this == other);
     }
 
     /**
      * Returns this color value as a packed 32-bit integer. This reconstructs
-     * the int32 based on the given colorType, always in the native byte order.
+     * the int32_t based on the given colorType, always in the native byte order.
      *
      * Note: gcc 4.2.3 on at least Ubuntu (x86) does something strange with
      * (uint8_t)(c * 255.0) << x, where the result is different than
      * double d = c * 255.0; v = ((uint8_t) d) << x. 
      */
     uint32_t Packed(PackedColorType colorType = PACKED_ABGR) const {
         gfxFloat rb = (r * 255.0);
         gfxFloat gb = (g * 255.0);
--- a/gfx/thebes/gfxFontUtils.cpp
+++ b/gfx/thebes/gfxFontUtils.cpp
@@ -356,17 +356,17 @@ gfxFontUtils::ReadCMAPTableFormat4(const
 
     uint16_t segCountX2 = ReadShortAt(aBuf, OffsetSegCountX2);
     NS_ENSURE_TRUE(tablelen >= 16 + (segCountX2 * 4), 
                    NS_ERROR_GFX_CMAP_MALFORMED);
 
     const uint16_t segCount = segCountX2 / 2;
 
     const uint16_t *endCounts = reinterpret_cast<const uint16_t*>(aBuf + 14);
-    const uint16_t *startCounts = endCounts + 1 /* skip one uint16 for reservedPad */ + segCount;
+    const uint16_t *startCounts = endCounts + 1 /* skip one uint16_t for reservedPad */ + segCount;
     const uint16_t *idDeltas = startCounts + segCount;
     const uint16_t *idRangeOffsets = idDeltas + segCount;
     uint16_t prevEndCount = 0;
     for (uint16_t i = 0; i < segCount; i++) {
         const uint16_t endCount = ReadShortAt16(endCounts, i);
         const uint16_t startCount = ReadShortAt16(startCounts, i);
         const uint16_t idRangeOffset = ReadShortAt16(idRangeOffsets, i);
 
--- a/image/decoders/nsGIFDecoder2.cpp
+++ b/image/decoders/nsGIFDecoder2.cpp
@@ -433,17 +433,17 @@ nsGIFDecoder2::DoLzw(const uint8_t *q)
       goto END;                                             \
     rowp = mImageData + mGIFStruct.irow * bpr;              \
     rowend = rowp + mGIFStruct.width;                       \
   PR_END_MACRO
 
   for (const uint8_t* ch = q; count-- > 0; ch++)
   {
     /* Feed the next byte into the decoder's 32-bit input buffer. */
-    datum += ((int32) *ch) << bits;
+    datum += ((int32_t) *ch) << bits;
     bits += 8;
 
     /* Check for underflow of decoder's 32-bit input buffer. */
     while (bits >= codesize)
     {
       /* Get the leading variable-length symbol from the data stream */
       int code = datum & codemask;
       datum >>= codesize;
--- a/intl/uconv/public/uconvutil.h
+++ b/intl/uconv/public/uconvutil.h
@@ -4,17 +4,17 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 #ifndef __UCONV_TIL_H__
 #define __UCONV_TIL_H__
 
 #include "prcpucfg.h"
 
 
 /*=====================================*/
-#define PACK(h,l)   (int16)(( (h) << 8) | (l))
+#define PACK(h,l)   (int16_t)(( (h) << 8) | (l))
 
 #if defined(IS_LITTLE_ENDIAN)
 #define ShiftInCell(sub,len,min,max)  \
     PACK(len,sub), PACK(max,min)
 #define ShiftOutCell(sub,len,minh,minl,maxh,maxl)  \
     PACK(len,sub), PACK(minl,minh), PACK(maxl,maxh)
 #else
 #define ShiftInCell(sub,len,min,max)  \
--- a/intl/uconv/tools/umaptable.c
+++ b/intl/uconv/tools/umaptable.c
@@ -1,67 +1,66 @@
 /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include <stdio.h>
-typedef short int16;
-typedef unsigned short uint16;
+#include "mozilla/StandardInteger.h"
 
 #define NOMAPPING 0xfffd
 
 typedef struct {
-		uint16 srcBegin;		/* 2 byte	*/
-		uint16 srcEnd;			/* 2 byte	*/
-		uint16 destBegin;		/* 2 byte	*/
+		uint16_t srcBegin;		/* 2 byte	*/
+		uint16_t srcEnd;		/* 2 byte	*/
+		uint16_t destBegin;		/* 2 byte	*/
 } uFormat0;
 
 typedef struct {
-		uint16 srcBegin;		/* 2 byte	*/
-		uint16 srcEnd;			/* 2 byte	*/
-		uint16	mappingOffset;	/* 2 byte	*/
+		uint16_t srcBegin;		/* 2 byte	*/
+		uint16_t srcEnd;		/* 2 byte	*/
+		uint16_t	mappingOffset;	/* 2 byte	*/
 } uFormat1;
 
 typedef struct {
-		uint16 srcBegin;		/* 2 byte	*/
-		uint16 srcEnd;			/* 2 byte	-waste	*/
-		uint16 destBegin;		/* 2 byte	*/
+		uint16_t srcBegin;		/* 2 byte	*/
+		uint16_t srcEnd;		/* 2 byte	-waste	*/
+		uint16_t destBegin;		/* 2 byte	*/
 } uFormat2;
 
 typedef struct  {
 	union {
 		uFormat0	format0;
 		uFormat1	format1;
 		uFormat2	format2;
 	} fmt;
 } uMapCell;
 
 /* =================================================
 					uTable 
 ================================================= */
 typedef struct  {
-	uint16 		itemOfList;
-	uint16		offsetToFormatArray;
-	uint16		offsetToMapCellArray;
-	uint16		offsetToMappingTable;
-	uint16		data[1];
+	uint16_t 		itemOfList;
+	uint16_t		offsetToFormatArray;
+	uint16_t		offsetToMapCellArray;
+	uint16_t		offsetToMappingTable;
+	uint16_t		data[1];
 } uTable;
 
-uint16 umap[256][256];
+uint16_t umap[256][256];
 int bInitFromOrTo = 0;
 int bGenerateFromUnicodeTable = 0;
 
 #define MAXCELLNUM 1000
 
 static int numOfItem = 0;
 uMapCell cell[MAXCELLNUM];
-uint16    format[MAXCELLNUM / 4];
-uint16   mapping[256*256];
+uint16_t    format[MAXCELLNUM / 4];
+uint16_t   mapping[256*256];
 static int mappinglen  = 0;
 static int formatcount[4] = {0,0,0,0}; 
 
 #define SetFormat(n,f)		{ format[(n >> 2)] |= ((f) << ((n & 0x0003)	<< 2)); formatcount[f]++; }
 #define GetFormat(n)		( format[(n >> 2)] >> ((n & 0x0003)	<< 2)) &0x00FF)
 #define MAPVALUE(i)	(umap[(i >> 8) & 0xFF][(i) & 0xFF])
 
 int  FORMAT1CNST = 10 ;
@@ -80,35 +79,35 @@ void initmaps()
 void SetMapValue(short u,short c)
 {
         if(NOMAPPING == MAPVALUE(u))
 	   MAPVALUE(u) = c & 0x0000FFFF;
         else {
            fprintf(stderr, "warning- duplicate mapping %x map to both %x and %x\n", u, MAPVALUE(u), c);
         }
 }
-void AddFormat2(uint16 srcBegin)
+void AddFormat2(uint16_t srcBegin)
 {
-	uint16 destBegin = MAPVALUE(srcBegin);
+	uint16_t destBegin = MAPVALUE(srcBegin);
 	printf("Begin of Item %04X\n",numOfItem);
 	printf(" Format 2\n");
 	printf("  srcBegin = %04X\n", srcBegin);
 	printf("  destBegin = %04X\n", destBegin );
 	SetFormat(numOfItem,2);
 	cell[numOfItem].fmt.format2.srcBegin = srcBegin;
 	cell[numOfItem].fmt.format2.srcEnd = 0;
 	cell[numOfItem].fmt.format2.destBegin = destBegin;
 	printf("End of Item %04X \n\n",numOfItem);
 	numOfItem++;
 	/*	Unmark the umap */
 	MAPVALUE(srcBegin) = NOMAPPING;
 }
-void AddFormat1(uint16 srcBegin, uint16 srcEnd)
+void AddFormat1(uint16_t srcBegin, uint16_t srcEnd)
 {
-	uint16 i;
+	uint16_t i;
 	printf("Begin of Item %04X\n",numOfItem);
 	printf(" Format 1\n");
 	printf("  srcBegin = %04X\n", srcBegin);
 	printf("  srcEnd = %04X\n", srcEnd );
 	printf("  mappingOffset = %04X\n", mappinglen);
 	printf(" Mapping  = " );  
 	SetFormat(numOfItem,1);
 	cell[numOfItem].fmt.format1.srcBegin = srcBegin;
@@ -122,20 +121,20 @@ void AddFormat1(uint16 srcBegin, uint16 
 		printf("%04X ",(mapping[mappinglen]  ));
 		/*	Unmark the umap */
 		MAPVALUE(i) = NOMAPPING;
 	}
 	printf("\n");
 	printf("End of Item %04X \n\n",numOfItem);
 	numOfItem++;
 }
-void AddFormat0(uint16 srcBegin, uint16 srcEnd)
+void AddFormat0(uint16_t srcBegin, uint16_t srcEnd)
 {
-	uint16 i;
-	uint16 destBegin = MAPVALUE(srcBegin);
+	uint16_t i;
+	uint16_t destBegin = MAPVALUE(srcBegin);
 	printf("Begin of Item %04X\n",numOfItem);
 	printf(" Format 0\n");
 	printf("  srcBegin = %04X\n", srcBegin);
 	printf("  srcEnd = %04X\n", srcEnd );
 	printf("  destBegin = %04X\n", destBegin );
 	SetFormat(numOfItem,0);
 	cell[numOfItem].fmt.format0.srcBegin = srcBegin;
 	cell[numOfItem].fmt.format0.srcEnd = srcEnd;
@@ -155,19 +154,19 @@ printf(
 "/* This Source Code Form is subject to the terms of the Mozilla Public\n"
 " * License, v. 2.0. If a copy of the MPL was not distributed with this\n"
 " * file, You can obtain one at http://mozilla.org/MPL/2.0/. */\n");
 }
 void gentable()
 {
 	/*	OK! For now, we just use format 1 for each row */
 	/*	We need to chage this to use other format to save the space */
-	uint16 begin,end;
-	uint16 ss,gs,gp,state,gc;	
-	uint16 diff, lastdiff;
+	uint16_t begin,end;
+	uint16_t ss,gs,gp,state,gc;	
+	uint16_t diff, lastdiff;
 
         printnpl();
 	printf("/*========================================================\n");
 	printf("  This is a Generated file. Please don't edit it.\n");
 	printf("\n");
 	printf("  The tool which used to generate this file is called umaptable.\n");
 	printf("  You can find this tool under mozilla/intl/uconv/tools/umaptable.c.\n");
 
@@ -278,23 +277,23 @@ void gentable()
 					AddFormat2(ss );	
 				else
 					AddFormat1(ss ,end );	
 	}
 	printf("========================================================*/\n");
 }
 void writetable()
 {
-	uint16 i;
-	uint16 off1,off2,off3;
-	uint16 cur = 0; 
-	uint16 formatitem = (((numOfItem)>>2) + 1);
+	uint16_t i;
+	uint16_t off1,off2,off3;
+	uint16_t cur = 0; 
+	uint16_t formatitem = (((numOfItem)>>2) + 1);
 	off1 = 4;
 	off2 = off1 + formatitem ;
-	off3 = off2 + numOfItem * sizeof(uMapCell) / sizeof(uint16);
+	off3 = off2 + numOfItem * sizeof(uMapCell) / sizeof(uint16_t);
 	/*	write itemOfList		*/
 	printf("/* Offset=0x%04X  ItemOfList */\n  0x%04X,\n", cur++, numOfItem);
 
 	/*	write offsetToFormatArray	*/
 	printf("/*-------------------------------------------------------*/\n");
 	printf("/* Offset=0x%04X  offsetToFormatArray */\n  0x%04X,\n",  cur++,off1);
 
 	/*	write offsetToMapCellArray	*/
--- a/js/src/builtin/MapObject.cpp
+++ b/js/src/builtin/MapObject.cpp
@@ -683,17 +683,17 @@ HashableValue::setValue(JSContext *cx, c
         JSString *str = AtomizeString(cx, v.toString(), DoNotInternAtom);
         if (!str)
             return false;
         value = StringValue(str);
     } else if (v.isDouble()) {
         double d = v.toDouble();
         int32_t i;
         if (MOZ_DOUBLE_IS_INT32(d, &i)) {
-            // Normalize int32-valued doubles to int32 for faster hashing and testing.
+            // Normalize int32_t-valued doubles to int32_t for faster hashing and testing.
             value = Int32Value(i);
         } else if (MOZ_DOUBLE_IS_NaN(d)) {
             // NaNs with different bits must hash and test identically.
             value = DoubleValue(js_NaN);
         } else {
             value = v;
         }
     } else {
--- a/js/src/builtin/ParallelArray.cpp
+++ b/js/src/builtin/ParallelArray.cpp
@@ -152,17 +152,17 @@ ToUint32(JSContext *cx, const Value &v, 
 
 static bool
 GetLength(JSContext *cx, HandleObject obj, uint32_t *length)
 {
     // If obj's length cannot overflow, just use GetLengthProperty.
     if (obj->isArray() || obj->isArguments())
         return GetLengthProperty(cx, obj, length);
 
-    // Otherwise check that we don't overflow uint32.
+    // Otherwise check that we don't overflow uint32_t.
     RootedValue value(cx);
     if (!JSObject::getProperty(cx, obj, obj, cx->names().length, &value))
         return false;
 
     bool malformed;
     if (!ToUint32(cx, value, length, &malformed))
         return false;
     if (malformed)
--- a/js/src/gc/Heap.h
+++ b/js/src/gc/Heap.h
@@ -186,17 +186,17 @@ struct FreeSpan
         checkSpan();
     }
 
     /*
      * To minimize the size of the arena header the first span is encoded
      * there as offsets from the arena start.
      */
     static size_t encodeOffsets(size_t firstOffset, size_t lastOffset) {
-        /* Check that we can pack the offsets into uint16. */
+        /* Check that we can pack the offsets into uint16_t. */
         JS_STATIC_ASSERT(ArenaShift < 16);
         JS_ASSERT(firstOffset <= ArenaSize);
         JS_ASSERT(lastOffset < ArenaSize);
         JS_ASSERT(firstOffset <= ((lastOffset + 1) & ~size_t(1)));
         return firstOffset | (lastOffset << 16);
     }
 
     /*
--- a/js/src/jsanalyze.cpp
+++ b/js/src/jsanalyze.cpp
@@ -274,17 +274,17 @@ ScriptAnalysis::analyzeBytecode(JSContex
             stackDepth -= nuses;
             stackDepth += ndefs;
         }
 
         /*
          * Assign an observed type set to each reachable JOF_TYPESET opcode.
          * This may be less than the number of type sets in the script if some
          * are unreachable, and may be greater in case the number of type sets
-         * overflows a uint16. In the latter case a single type set will be
+         * overflows a uint16_t. In the latter case a single type set will be
          * used for the observed types of all ops after the overflow.
          */
         if ((js_CodeSpec[op].format & JOF_TYPESET) && cx->typeInferenceEnabled()) {
             if (nTypeSets < script_->nTypeSets) {
                 code->observedTypes = typeArray[nTypeSets++].toStackTypeSet();
             } else {
                 JS_ASSERT(nTypeSets == UINT16_MAX);
                 code->observedTypes = typeArray[nTypeSets - 1].toStackTypeSet();
--- a/js/src/jsapi.h
+++ b/js/src/jsapi.h
@@ -3123,21 +3123,18 @@ JS_StringToVersion(const char *string);
                                                    in HTML script tags. */
 #define JSOPTION_DONT_REPORT_UNCAUGHT                                   \
                                 JS_BIT(8)       /* When returning from the
                                                    outermost API call, prevent
                                                    uncaught exceptions from
                                                    being converted to error
                                                    reports */
 
-#define JSOPTION_RELIMIT        JS_BIT(9)       /* Throw exception on any
-                                                   regular expression which
-                                                   backtracks more than n^3
-                                                   times, where n is length
-                                                   of the input string */
+/* JS_BIT(9) is currently unused. */
+
 /* JS_BIT(10) is currently unused. */
 
 /* JS_BIT(11) is currently unused. */
 
 #define JSOPTION_NO_SCRIPT_RVAL JS_BIT(12)      /* A promise to the compiler
                                                    that a null rval out-param
                                                    will be passed to each call
                                                    to JS_ExecuteScript. */
--- a/js/src/jsarray.cpp
+++ b/js/src/jsarray.cpp
@@ -9,17 +9,17 @@
  * JS array class.
  *
  * Array objects begin as "dense" arrays, optimized for index-only property
  * access over a vector of slots with high load factor.  Array methods
  * optimize for denseness by testing that the object's class is
  * &ArrayClass, and can then directly manipulate the slots for efficiency.
  *
  * We track these pieces of metadata for arrays in dense mode:
- *  - The array's length property as a uint32, accessible with
+ *  - The array's length property as a uint32_t, accessible with
  *    getArrayLength(), setArrayLength().
  *  - The number of element slots (capacity), gettable with
  *    getDenseArrayCapacity().
  *  - The array's initialized length, accessible with
  *    getDenseArrayInitializedLength().
  *
  * In dense mode, holes in the array are represented by
  * MagicValue(JS_ARRAY_HOLE) invalid values.
--- a/js/src/jsfun.cpp
+++ b/js/src/jsfun.cpp
@@ -540,21 +540,16 @@ JSFunction::trace(JSTracer *trc)
 }
 
 static void
 fun_trace(JSTracer *trc, RawObject obj)
 {
     obj->toFunction()->trace(trc);
 }
 
-/*
- * Reserve two slots in all function objects for XPConnect.  Note that this
- * does not bloat every instance, only those on which reserved slots are set,
- * and those on which ad-hoc properties are defined.
- */
 JS_FRIEND_DATA(Class) js::FunctionClass = {
     js_Function_str,
     JSCLASS_NEW_RESOLVE | JSCLASS_IMPLEMENTS_BARRIERS |
     JSCLASS_HAS_CACHED_PROTO(JSProto_Function),
     JS_PropertyStub,         /* addProperty */
     JS_PropertyStub,         /* delProperty */
     JS_PropertyStub,         /* getProperty */
     JS_StrictPropertyStub,   /* setProperty */
--- a/js/src/jsobjinlines.h
+++ b/js/src/jsobjinlines.h
@@ -379,17 +379,17 @@ JSObject::setArrayLength(JSContext *cx, 
     }
 
     obj->getElementsHeader()->length = length;
 }
 
 inline void
 JSObject::setDenseArrayLength(uint32_t length)
 {
-    /* Variant of setArrayLength for use on dense arrays where the length cannot overflow int32. */
+    /* Variant of setArrayLength for use on dense arrays where the length cannot overflow int32_t. */
     JS_ASSERT(isDenseArray());
     JS_ASSERT(length <= INT32_MAX);
     getElementsHeader()->length = length;
 }
 
 inline void
 JSObject::setDenseArrayInitializedLength(uint32_t length)
 {
--- a/js/src/jstypedarray.h
+++ b/js/src/jstypedarray.h
@@ -203,18 +203,18 @@ struct TypedArray : public BufferView {
         TYPE_INT16,
         TYPE_UINT16,
         TYPE_INT32,
         TYPE_UINT32,
         TYPE_FLOAT32,
         TYPE_FLOAT64,
 
         /*
-         * Special type that's a uint8, but assignments are clamped to 0 .. 255.
-         * Treat the raw data type as a uint8.
+         * Special type that's a uint8_t, but assignments are clamped to 0 .. 255.
+         * Treat the raw data type as a uint8_t.
          */
         TYPE_UINT8_CLAMPED,
 
         TYPE_MAX
     };
 
     /*
      * Typed array properties stored in slots, beyond those shared by all
--- a/js/src/methodjit/Compiler.cpp
+++ b/js/src/methodjit/Compiler.cpp
@@ -5086,17 +5086,17 @@ mjit::Compiler::jsop_getprop(PropertyNam
             }
         }
 
         types::StackTypeSet *types = analysis->poppedTypes(PC, 0);
 
         /*
          * Check if we are accessing the 'length' property of a known dense array.
          * Note that if the types are known to indicate dense arrays, their lengths
-         * must fit in an int32.
+         * must fit in an int32_t.
          */
         if (!types->hasObjectFlags(cx, types::OBJECT_FLAG_NON_DENSE_ARRAY)) {
             bool isObject = top->isTypeKnown();
             if (!isObject) {
                 Jump notObject = frame.testObject(Assembler::NotEqual, top);
                 stubcc.linkExit(notObject, Uses(1));
                 stubcc.leave();
                 stubcc.masm.move(ImmPtr(name), Registers::ArgReg1);
@@ -5114,17 +5114,17 @@ mjit::Compiler::jsop_getprop(PropertyNam
                 bumpPropCount(PC, PCCounts::PROP_DEFINITE);
             if (!isObject)
                 stubcc.rejoin(Changes(1));
             return true;
         }
 
         /*
          * Check if we're accessing the 'length' property of a typed array.
-         * The typed array length always fits in an int32.
+         * The typed array length always fits in an int32_t.
          */
         if (!types->hasObjectFlags(cx, types::OBJECT_FLAG_NON_TYPED_ARRAY)) {
             if (top->isConstant()) {
                 JSObject *obj = &top->getValue().toObject();
                 uint32_t length = TypedArray::length(obj);
                 frame.pop();
                 frame.push(Int32Value(length));
                 return true;
--- a/js/src/methodjit/FastArithmetic.cpp
+++ b/js/src/methodjit/FastArithmetic.cpp
@@ -348,17 +348,17 @@ mjit::Compiler::jsop_binary_double(Frame
      * double result. Unless the pushed type set already contains the double
      * type, we need to call a stub rather than push. Note that looking at
      * the pushed type tag is not sufficient, as it will be UNKNOWN if
      * we do not yet know the possible types of the division's operands.
      */
     types::TypeSet *resultTypes = pushedTypeSet(0);
     if (resultTypes && !resultTypes->hasType(types::Type::DoubleType())) {
         /*
-         * Call a stub and try harder to convert to int32, failing that trigger
+         * Call a stub and try harder to convert to int32_t, failing that trigger
          * recompilation of this script.
          */
         stubcc.linkExit(masm.jump(), Uses(2));
     } else {
         JS_ASSERT(type != JSVAL_TYPE_INT32);
         if (type != JSVAL_TYPE_DOUBLE)
             masm.storeDouble(fpLeft, frame.addressOf(lhs));
     }
--- a/js/src/methodjit/FastOps.cpp
+++ b/js/src/methodjit/FastOps.cpp
@@ -51,17 +51,17 @@ mjit::Compiler::ensureInteger(FrameEntry
         Jump truncateGuard = masm.branchTruncateDoubleToInt32(fpreg, data);
 
         Label syncPath = stubcc.syncExitAndJump(uses);
         stubcc.linkExitDirect(truncateGuard, stubcc.masm.label());
 
         /*
          * Try an OOL path to convert doubles representing integers within 2^32
          * of a signed integer, by adding/subtracting 2^32 and then trying to
-         * convert to int32. This has to be an exact conversion, as otherwise
+         * convert to int32_t. This has to be an exact conversion, as otherwise
          * the truncation works incorrectly on the modified value.
          */
 
         stubcc.masm.zeroDouble(fptemp);
         Jump positive = stubcc.masm.branchDouble(Assembler::DoubleGreaterThan, fpreg, fptemp);
         stubcc.masm.slowLoadConstantDouble(double(4294967296.0), fptemp);
         Jump skip = stubcc.masm.jump();
         positive.linkTo(stubcc.masm.label(), &stubcc.masm);
@@ -1611,17 +1611,17 @@ mjit::Compiler::jsop_setelem(bool popGua
     //  2) tempRegForData() will work fine on a pinned register.
 
     // Guard that the object is an object.
     if (!obj->isTypeKnown()) {
         Jump j = frame.testObject(Assembler::NotEqual, obj);
         stubcc.linkExit(j, Uses(3));
     }
 
-    // Guard that the id is int32.
+    // Guard that the id is int32_t.
     if (!id->isTypeKnown()) {
         Jump j = frame.testInt32(Assembler::NotEqual, id);
         stubcc.linkExit(j, Uses(3));
     }
 
     // Grab a register for the object. It's safe to unpin |obj| because it
     // won't have been pinned if it shares a backing with |value|. However,
     // it would not be safe to copyDataIntoReg() if the value was pinned,
--- a/js/src/methodjit/FrameEntry.h
+++ b/js/src/methodjit/FrameEntry.h
@@ -50,17 +50,17 @@ class FrameEntry
     }
 #elif defined JS_PUNBOX64
     uint64_t getPayload() const {
         JS_ASSERT(isConstant());
         return v_.asBits & JSVAL_PAYLOAD_MASK;
     }
 #endif
 
-    /* For a constant double FrameEntry, truncate to an int32. */
+    /* For a constant double FrameEntry, truncate to an int32_t. */
     void convertConstantDoubleOrBooleanToInt32(JSContext *cx) {
         JS_ASSERT(isConstant());
         JS_ASSERT(isType(JSVAL_TYPE_DOUBLE) || isType(JSVAL_TYPE_BOOLEAN));
 
         int32_t value;
         ToInt32(cx, getValue(), &value);
 
         Value newValue = Int32Value(value);
--- a/js/src/methodjit/FrameState.h
+++ b/js/src/methodjit/FrameState.h
@@ -313,17 +313,17 @@ class FrameState
      * known to be correct at a slow-path merge point.
      */
     inline void pushUntypedValue(const Value &value);
 
     /*
      * Pushes a number onto the operation stack.
      *
      * If asInt32 is set to true, then the FS will attempt to optimize
-     * syncing the type as int32. Only use this parameter when the fast-path
+     * syncing the type as int32_t. Only use this parameter when the fast-path
      * guaranteed that the stack slot was guarded to be an int32_t originally.
      *
      * For example, checking LHS and RHS as ints guarantees that if the LHS
      * was synced, then popping both and pushing a maybe-int32_t does not need
      * to be synced.
      */
     inline void pushNumber(RegisterID payload, bool asInt32 = false);
 
--- a/js/src/shell/js.cpp
+++ b/js/src/shell/js.cpp
@@ -568,17 +568,16 @@ cleanup:
  */
 static const struct JSOption {
     const char  *name;
     uint32_t    flag;
 } js_options[] = {
     {"atline",          JSOPTION_ATLINE},
     {"methodjit",       JSOPTION_METHODJIT},
     {"methodjit_always",JSOPTION_METHODJIT_ALWAYS},
-    {"relimit",         JSOPTION_RELIMIT},
     {"strict",          JSOPTION_STRICT},
     {"typeinfer",       JSOPTION_TYPE_INFERENCE},
     {"werror",          JSOPTION_WERROR},
     {"allow_xml",       JSOPTION_ALLOW_XML},
     {"moar_xml",        JSOPTION_MOAR_XML},
     {"strict_mode",     JSOPTION_STRICT_MODE},
 };
 
--- a/js/src/tests/browser.js
+++ b/js/src/tests/browser.js
@@ -189,17 +189,16 @@ function options(aOptionName)
 function optionsInit() {
 
   // hash containing the set options.
   options.currvalues = {
     strict:     true,
     werror:     true,
     atline:     true,
     moar_xml:   true,
-    relimit:    true,
     methodjit:  true,
     methodjit_always: true,
     strict_mode: true
   };
 
   // record initial values to support resetting
   // options to their initial values
   options.initvalues = {};
--- a/js/src/tests/js1_5/extensions/regress-330569.js
+++ b/js/src/tests/js1_5/extensions/regress-330569.js
@@ -36,20 +36,16 @@ function test()
     '<script language="JavaScript">\n' +
     'var s = document. body. innerHTML;\n' +
     'var d = s. replace (/<!--(.*|\n)*-->/, "");\n' +
     'alert (d);\n' +
     '</script>\n' +
     '</body>\n' +
     '</html>\n';
 
-  if (!options().match(/relimit/)) {
-    options('relimit');
-  }
-
   try
   {
     /<!--(.*|\n)*-->/.exec(s);
   }
   catch(ex)
   {
     actual = ex + '';
   }
--- a/js/src/tests/js1_5/extensions/regress-351448.js
+++ b/js/src/tests/js1_5/extensions/regress-351448.js
@@ -40,20 +40,16 @@ function test()
     "/.[X](.+)+[X][X]/.exec('bbbbXXXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')",
     "/.[X](.+)+[X][X]/.exec('bbbbXcXXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')",
     "/.[X][X](.+)+[X]/.exec('bbbbXXXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')",
     "/.[X][X](.+)+[X]/.exec('bbbbXXcXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')"
     ];
 
   expect = 'InternalError: regular expression too complex';
 
-  if (!options().match(/relimit/)) {
-    options('relimit');
-  }
-
   for (var i = 0; i < strings.length; i++)
   {
     try
     {
       eval(strings[i]);
     }
     catch(ex)
     {
--- a/js/src/tests/user.js
+++ b/js/src/tests/user.js
@@ -29,9 +29,10 @@ user_pref("extensions.checkUpdateSecurit
 user_pref("browser.EULA.override", true);
 user_pref("javascript.options.methodjit.chrome", true);
 user_pref("javascript.options.methodjit.content", true);
 user_pref("javascript.options.ion.content", true);
 user_pref("javascript.options.methodjit_always", false);
 user_pref("javascript.options.strict", false);
 user_pref("javascript.options.werror", false);
 user_pref("toolkit.startup.max_resumed_crashes", -1);
-user_pref("security.enablePrivilege.enable_for_tests", true);
+user_pref("security.turn_off_all_security_so_that_viruses_can_take_over_this_computer", true);
+
--- a/js/src/vm/SPSProfiler.cpp
+++ b/js/src/vm/SPSProfiler.cpp
@@ -217,17 +217,19 @@ JMChunkInfo::JMChunkInfo(mjit::JSActiveF
     stubEnd(frame->stubCodeEnd),
     pcLengths(pcLengths),
     chunk(chunk)
 {}
 
 jsbytecode*
 SPSProfiler::ipToPC(JSScript *script, size_t ip)
 {
-    JS_ASSERT(jminfo.initialized());
+    if (!jminfo.initialized())
+        return NULL;
+
     JITInfoMap::Ptr ptr = jminfo.lookup(script);
     if (!ptr)
         return NULL;
     JMScriptInfo *info = ptr->value;
 
     /* First check if this ip is in any of the ICs compiled for the script */
     for (unsigned i = 0; i < info->ics.length(); i++) {
         ICInfo &ic = info->ics[i];
--- a/js/xpconnect/idl/xpccomponents.idl
+++ b/js/xpconnect/idl/xpccomponents.idl
@@ -113,17 +113,17 @@ interface nsIXPCComponents_utils_Sandbox
 interface ScheduledGCCallback : nsISupports
 {
     void callback();
 };
 
 /**
 * interface of Components.utils
 */
-[scriptable, uuid(36c19d92-d4a9-4ad1-bee3-945f60c6c991)]
+[scriptable, uuid(a93e230d-e883-4ff8-9aeb-dbe5cc771059)]
 interface nsIXPCComponents_Utils : nsISupports
 {
 
     /* reportError is designed to be called from JavaScript only.
      *
      * It will report a JS Error object to the JS console, and return. It
      * is meant for use in exception handler blocks which want to "eat"
      * an exception, but still want to report it to the console.
@@ -365,19 +365,16 @@ interface nsIXPCComponents_Utils : nsISu
 
     [implicit_jscontext]
     attribute boolean atline;
 
     [implicit_jscontext]
     attribute boolean xml;
 
     [implicit_jscontext]
-    attribute boolean relimit;
-
-    [implicit_jscontext]
     attribute boolean methodjit;
 
     [implicit_jscontext]
     attribute boolean methodjit_always;
 
     [implicit_jscontext]
     attribute boolean strict_mode;
     
--- a/js/xpconnect/public/nsTArrayHelpers.h
+++ b/js/xpconnect/public/nsTArrayHelpers.h
@@ -41,9 +41,50 @@ nsTArrayToJSArray(JSContext* aCx, const 
     NS_WARNING("JS_FreezeObject failed!");
     return NS_ERROR_FAILURE;
   }
 
   *aResultArray = arrayObj;
   return NS_OK;
 }
 
+template <>
+inline nsresult
+nsTArrayToJSArray<nsString>(JSContext* aCx,
+                            const nsTArray<nsString>& aSourceArray,
+                            JSObject** aResultArray)
+{
+  MOZ_ASSERT(aCx);
+  JSAutoRequest ar(aCx);
+
+  JSObject* arrayObj = JS_NewArrayObject(aCx, aSourceArray.Length(), nullptr);
+  if (!arrayObj) {
+    NS_WARNING("JS_NewArrayObject failed!");
+    return NS_ERROR_OUT_OF_MEMORY;
+  }
+
+  for (uint32_t index = 0; index < aSourceArray.Length(); index++) {
+    JSString* s = JS_NewUCStringCopyN(aCx, aSourceArray[index].BeginReading(),
+                                      aSourceArray[index].Length());
+
+    if(!s) {
+      NS_WARNING("Memory allocation error!");
+      return NS_ERROR_OUT_OF_MEMORY;
+    }
+
+    jsval wrappedVal = STRING_TO_JSVAL(s);
+
+    if (!JS_SetElement(aCx, arrayObj, index, &wrappedVal)) {
+      NS_WARNING("JS_SetElement failed!");
+      return NS_ERROR_FAILURE;
+    }
+  }
+
+  if (!JS_FreezeObject(aCx, arrayObj)) {
+    NS_WARNING("JS_FreezeObject failed!");
+    return NS_ERROR_FAILURE;
+  }
+
+  *aResultArray = arrayObj;
+  return NS_OK;
+}
+
 #endif /* __NSTARRAYHELPERS_H__ */
--- a/js/xpconnect/shell/xpcshell.cpp
+++ b/js/xpconnect/shell/xpcshell.cpp
@@ -681,17 +681,16 @@ GetChildGlobalObject(JSContext* cx,
  * JSContext option name to flag map. The option names are in alphabetical
  * order for better reporting.
  */
 static const struct JSOption {
     const char  *name;
     uint32_t    flag;
 } js_options[] = {
     {"atline",          JSOPTION_ATLINE},
-    {"relimit",         JSOPTION_RELIMIT},
     {"strict",          JSOPTION_STRICT},
     {"werror",          JSOPTION_WERROR},
     {"allow_xml",       JSOPTION_ALLOW_XML},
     {"moar_xml",        JSOPTION_MOAR_XML},
     {"strict_mode",     JSOPTION_STRICT_MODE},
 };
 
 static uint32_t
--- a/js/xpconnect/src/XPCComponents.cpp
+++ b/js/xpconnect/src/XPCComponents.cpp
@@ -4418,17 +4418,16 @@ SetBoolOption(JSContext* cx, uint32_t aO
     {                                                                   \
         return SetBoolOption(cx, _flag, aValue);                        \
     }
 
 GENERATE_JSOPTION_GETTER_SETTER(Strict, JSOPTION_STRICT)
 GENERATE_JSOPTION_GETTER_SETTER(Werror, JSOPTION_WERROR)
 GENERATE_JSOPTION_GETTER_SETTER(Atline, JSOPTION_ATLINE)
 GENERATE_JSOPTION_GETTER_SETTER(Xml, JSOPTION_MOAR_XML)
-GENERATE_JSOPTION_GETTER_SETTER(Relimit, JSOPTION_RELIMIT)
 GENERATE_JSOPTION_GETTER_SETTER(Methodjit, JSOPTION_METHODJIT)
 GENERATE_JSOPTION_GETTER_SETTER(Methodjit_always, JSOPTION_METHODJIT_ALWAYS)
 GENERATE_JSOPTION_GETTER_SETTER(Strict_mode, JSOPTION_STRICT_MODE)
 GENERATE_JSOPTION_GETTER_SETTER(Ion, JSOPTION_ION)
 
 #undef GENERATE_JSOPTION_GETTER_SETTER
 
 NS_IMETHODIMP
--- a/layout/base/FrameLayerBuilder.cpp
+++ b/layout/base/FrameLayerBuilder.cpp
@@ -2428,17 +2428,17 @@ FrameLayerBuilder::AddThebesDisplayItem(
 }
 
 FrameLayerBuilder::DisplayItemData*
 FrameLayerBuilder::StoreDataForFrame(nsDisplayItem* aItem, Layer* aLayer, LayerState aState)
 {
   DisplayItemData* oldData = GetDisplayItemDataForManager(aItem, mRetainingManager);
   if (oldData) {
     if (!oldData->mUsed) {
-      oldData->UpdateContents(aLayer, aState, mContainerLayerGeneration);
+      oldData->UpdateContents(aLayer, aState, mContainerLayerGeneration, aItem);
     }
     return oldData;
   }
   
   LayerManagerData* lmd = static_cast<LayerManagerData*>
     (mRetainingManager->GetUserData(&gLayerManagerUserData));
   
   nsRefPtr<DisplayItemData> data = 
--- a/media/libcubeb/README_MOZILLA
+++ b/media/libcubeb/README_MOZILLA
@@ -1,8 +1,9 @@
 The source from this directory was copied from the cubeb 
 git repository using the update.sh script.  The only changes
 made were those applied by update.sh and the addition of
 Makefile.in build files for the Mozilla build system.
 
 The cubeb git repository is: git://github.com/kinetiknz/cubeb.git
 
 The git commit ID used was 2d7d3e8f2ecabb70d2723f3c86fcb591a84b7f85.
+Plus the single commit f4c927fb1c2dc0a0580d0bca4bd267c34febada4.
--- a/media/libcubeb/src/cubeb_audiounit.c
+++ b/media/libcubeb/src/cubeb_audiounit.c
@@ -2,17 +2,16 @@
  * Copyright © 2011 Mozilla Foundation
  *
  * This program is made available under an ISC-style license.  See the
  * accompanying file LICENSE for details.
  */
 #undef NDEBUG
 #include <assert.h>
 #include <pthread.h>
-#include <stdio.h>
 #include <stdlib.h>
 #include <CoreServices/CoreServices.h>
 #include <AudioUnit/AudioUnit.h>
 #include "cubeb/cubeb.h"
 
 #define NBUFS 4
 
 struct cubeb_stream {
@@ -178,68 +177,70 @@ cubeb_stream_init(cubeb * context, cubeb
   r = pthread_mutex_init(&stm->mutex, NULL);
   assert(r == 0);
 
   stm->frames_played = 0;
   stm->frames_queued = 0;
 
   r = OpenAComponent(comp, &stm->unit);
   if (r != 0) {
-    fprintf(stderr, "cubeb_audiounit: FATAL: OpenAComponent returned %ld\n", (long) r);
+    cubeb_stream_destroy(stm);
+    return CUBEB_ERROR;
   }
-  assert(r == 0);
 
   input.inputProc = audio_unit_output_callback;
   input.inputProcRefCon = stm;
   r = AudioUnitSetProperty(stm->unit, kAudioUnitProperty_SetRenderCallback,
                            kAudioUnitScope_Global, 0, &input, sizeof(input));
   if (r != 0) {
-    fprintf(stderr, "cubeb_audiounit: FATAL: AudioUnitSetProperty(SetRenderCallback) returned %ld\n", (long) r);
+    cubeb_stream_destroy(stm);
+    return CUBEB_ERROR;
   }
-  assert(r == 0);
 
   r = AudioUnitSetProperty(stm->unit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
                            0, &ss, sizeof(ss));
   if (r != 0) {
-    fprintf(stderr, "cubeb_audiounit: FATAL: AudioUnitSetProperty(StreamFormat) returned %ld\n", (long) r);
+    cubeb_stream_destroy(stm);
+    return CUBEB_ERROR;
   }
-  assert(r == 0);
 
   buffer_size = ss.mSampleRate / 1000.0 * latency * ss.mBytesPerFrame / NBUFS;
   if (buffer_size % ss.mBytesPerFrame != 0) {
     buffer_size += ss.mBytesPerFrame - (buffer_size % ss.mBytesPerFrame);
   }
   assert(buffer_size % ss.mBytesPerFrame == 0);
 
   r = AudioUnitInitialize(stm->unit);
   if (r != 0) {
-    fprintf(stderr, "cubeb_audiounit: FATAL: AudioUnitInitialize returned %ld\n", (long) r);
+    cubeb_stream_destroy(stm);
+    return CUBEB_ERROR;
   }
-  assert(r == 0);
 
   *stream = stm;
 
   return CUBEB_OK;
 }
 
 void
 cubeb_stream_destroy(cubeb_stream * stm)
 {
   OSStatus r;
 
   stm->shutdown = 1;
 
-  r = AudioOutputUnitStop(stm->unit);
-  assert(r == 0);
+  if (stm->unit) {
+    r = AudioOutputUnitStop(stm->unit);
+    assert(r == 0);
 
-  r = AudioUnitUninitialize(stm->unit);
-  assert(r == 0);
+    r = AudioUnitUninitialize(stm->unit);
+    assert(r == 0);
 
-  r = CloseComponent(stm->unit);
-  assert(r == 0);
+    r = CloseComponent(stm->unit);
+    assert(r == 0);
+  }
 
   r = pthread_mutex_destroy(&stm->mutex);
   assert(r == 0);
 
   free(stm);
 }
 
 int
--- a/mobile/android/base/GeckoInputConnection.java
+++ b/mobile/android/base/GeckoInputConnection.java
@@ -504,18 +504,18 @@ class GeckoInputConnection
         final int oldStart = start;
         final int oldEnd = end;
         postToUiThread(new Runnable() {
             public void run() {
                 InputMethodManager imm = getInputMethodManager();
                 if (imm != null && imm.isFullscreenMode()) {
                     int newStart;
                     int newEnd;
-                    if (hasCompositionString()) {
-                        Span span = getComposingSpan();
+                    Span span = getComposingSpan();
+                    if (span != null && hasCompositionString()) {
                         newStart = span.start;
                         newEnd = span.end;
                     } else {
                         newStart = -1;
                         newEnd = -1;
                     }
                     View v = getView();
                     imm.updateSelection(v, oldStart, oldEnd, newStart, newEnd);
--- a/modules/libjar/nsJARInputStream.cpp
+++ b/modules/libjar/nsJARInputStream.cpp
@@ -1,16 +1,16 @@
 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /* nsJARInputStream.cpp
  * 
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-#include "NSPRFormatTime.h" // must include before any headers that include prtime.h
+#include "NSPRFormatTime.h" // must be before anything that includes prtime.h
 #include "nsJARInputStream.h"
 #include "zipstruct.h"         // defines ZIP compression codes
 #include "nsZipArchive.h"
 
 #include "nsNetUtil.h"
 #include "nsEscape.h"
 #include "nsIFile.h"
 #include "nsDebug.h"
--- a/modules/libpref/src/init/all.js
+++ b/modules/libpref/src/init/all.js
@@ -704,17 +704,16 @@ pref("privacy.donottrackheader.enabled",
 pref("dom.event.contextmenu.enabled",       true);
 pref("dom.event.clipboardevents.enabled",   true);
 
 pref("javascript.enabled",                  true);
 pref("javascript.options.strict",           false);
 #ifdef DEBUG
 pref("javascript.options.strict.debug",     true);
 #endif
-pref("javascript.options.relimit",          true);
 pref("javascript.options.methodjit.content", true);
 pref("javascript.options.methodjit.chrome",  true);
 pref("javascript.options.ion.content",      true);
 pref("javascript.options.pccounts.content", false);
 pref("javascript.options.pccounts.chrome",  false);
 pref("javascript.options.methodjit_always", false);
 pref("javascript.options.xml.content", false);
 pref("javascript.options.xml.chrome", true);
--- a/netwerk/base/src/nsDirectoryIndexStream.cpp
+++ b/netwerk/base/src/nsDirectoryIndexStream.cpp
@@ -9,17 +9,17 @@
 
   The converts a filesystem directory into an "HTTP index" stream per
   Lou Montulli's original spec:
 
   http://www.mozilla.org/projects/netlib/dirindexformat.html
 
  */
 
-#include "NSPRFormatTime.h" // must include before any headers that include prtime.h
+#include "NSPRFormatTime.h" // must be before anything that includes prtime.h
 #include "nsEscape.h"
 #include "nsDirectoryIndexStream.h"
 #include "nsXPIDLString.h"
 #include "prio.h"
 #include "prlog.h"
 #include "prlong.h"
 #ifdef PR_LOGGING
 static PRLogModuleInfo* gLog;
--- a/netwerk/cache/nsCacheService.cpp
+++ b/netwerk/cache/nsCacheService.cpp
@@ -935,17 +935,17 @@ nsCacheProfilePrefObserver::MemoryCacheC
     CACHE_LOG_DEBUG(("Physical Memory size is %llu\n", bytes));
 
     // If getting the physical memory failed, arbitrarily assume
     // 32 MB of RAM. We use a low default to have a reasonable
     // size on all the devices we support.
     if (bytes == 0)
         bytes = 32 * 1024 * 1024;
 
-    // Conversion from unsigned int64 to double doesn't work on all platforms.
+    // Conversion from unsigned int64_t to double doesn't work on all platforms.
     // We need to truncate the value at INT64_MAX to make sure we don't
     // overflow.
     if (bytes > INT64_MAX)
         bytes = INT64_MAX;
 
     uint64_t kbytes = bytes >> 10;
 
     double kBytesD = double(kbytes);
--- a/netwerk/cookie/nsCookieService.cpp
+++ b/netwerk/cookie/nsCookieService.cpp
@@ -5,17 +5,17 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 
 #ifdef MOZ_LOGGING
 // this next define has to appear before the include of prlog.h
 #define FORCE_PR_LOG // Allow logging in the release build
 #endif
 
-#include "NSPRFormatTime.h" // must include before any headers that include prtime.h
+#include "NSPRFormatTime.h" // must be before anything that includes prtime.h
 #include "mozilla/net/CookieServiceChild.h"
 #include "mozilla/net/NeckoCommon.h"
 
 #include "nsCookieService.h"
 #include "nsIServiceManager.h"
 
 #include "nsIIOService.h"
 #include "nsIPrefBranch.h"
--- a/netwerk/protocol/about/nsAboutBloat.cpp
+++ b/netwerk/protocol/about/nsAboutBloat.cpp
@@ -1,14 +1,14 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-#include "NSPRFormatTime.h" // must include before any headers that include prtime.h
+#include "NSPRFormatTime.h" // must be before anything that includes prtime.h
 #include "nsTraceRefcntImpl.h"
 
 // if NS_BUILD_REFCNT_LOGGING isn't defined, don't try to build
 #ifdef NS_BUILD_REFCNT_LOGGING
 
 #include "nsAboutBloat.h"
 #include "nsIIOService.h"
 #include "nsIServiceManager.h"
--- a/netwerk/protocol/about/nsAboutCache.cpp
+++ b/netwerk/protocol/about/nsAboutCache.cpp
@@ -1,14 +1,14 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-#include "NSPRFormatTime.h" // must include before any headers that include prtime.h
+#include "NSPRFormatTime.h" // must be before anything that includes prtime.h
 #include "nsAboutCache.h"
 #include "nsIIOService.h"
 #include "nsIServiceManager.h"
 #include "nsIInputStream.h"
 #include "nsIStorageStream.h"
 #include "nsISimpleEnumerator.h"
 #include "nsXPIDLString.h"
 #include "nsIURI.h"
--- a/netwerk/protocol/about/nsAboutCacheEntry.cpp
+++ b/netwerk/protocol/about/nsAboutCacheEntry.cpp
@@ -1,16 +1,16 @@
 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include <limits.h>
 
-#include "NSPRFormatTime.h" // must include before any headers that include prtime.h
+#include "NSPRFormatTime.h" // must be before anything that includes prtime.h
 #include "nsAboutCacheEntry.h"
 #include "nsICacheService.h"
 #include "nsICacheSession.h"
 #include "nsIStorageStream.h"
 #include "nsNetUtil.h"
 #include "nsAutoPtr.h"
 #include "prprf.h"
 #include "nsEscape.h"
--- a/netwerk/socket/nsSOCKSIOLayer.cpp
+++ b/netwerk/socket/nsSOCKSIOLayer.cpp
@@ -898,39 +898,39 @@ nsSOCKSSocketInfo::WriteString(const nsA
     mDataLength += str.Length();
 }
 
 inline uint8_t
 nsSOCKSSocketInfo::ReadUint8()
 {
     uint8_t rv;
     NS_ABORT_IF_FALSE(mReadOffset + sizeof(rv) <= mDataLength,
-                      "Not enough space to pop a uint8!");
+                      "Not enough space to pop a uint8_t!");
     rv = mData[mReadOffset];
     mReadOffset += sizeof(rv);
     return rv;
 }
 
 inline uint16_t
 nsSOCKSSocketInfo::ReadUint16()
 {
     uint16_t rv;
     NS_ABORT_IF_FALSE(mReadOffset + sizeof(rv) <= mDataLength,
-                      "Not enough space to pop a uint16!");
+                      "Not enough space to pop a uint16_t!");
     memcpy(&rv, mData + mReadOffset, sizeof(rv));
     mReadOffset += sizeof(rv);
     return rv;
 }
 
 inline uint32_t
 nsSOCKSSocketInfo::ReadUint32()
 {
     uint32_t rv;
     NS_ABORT_IF_FALSE(mReadOffset + sizeof(rv) <= mDataLength,
-                      "Not enough space to pop a uint32!");
+                      "Not enough space to pop a uint32_t!");
     memcpy(&rv, mData + mReadOffset, sizeof(rv));
     mReadOffset += sizeof(rv);
     return rv;
 }
 
 void
 nsSOCKSSocketInfo::ReadNetAddr(PRNetAddr *addr, uint16_t fam)
 {
--- a/netwerk/streamconv/converters/nsFTPDirListingConv.cpp
+++ b/netwerk/streamconv/converters/nsFTPDirListingConv.cpp
@@ -1,14 +1,14 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-#include "NSPRFormatTime.h" // must include before any headers that include prtime.h
+#include "NSPRFormatTime.h" // must be before anything that includes prtime.h
 #include "nsFTPDirListingConv.h"
 #include "nsMemory.h"
 #include "plstr.h"
 #include "prlog.h"
 #include "nsIServiceManager.h"
 #include "nsXPIDLString.h"
 #include "nsReadableUtils.h"
 #include "nsCOMPtr.h"
--- a/netwerk/test/TestProtocols.cpp
+++ b/netwerk/test/TestProtocols.cpp
@@ -7,17 +7,17 @@
 /* 
     The TestProtocols tests the basic protocols architecture and can 
     be used to test individual protocols as well. If this grows too
     big then we should split it to individual protocols. 
 
     -Gagan Saksena 04/29/99
 */
 
-#include "NSPRFormatTime.h" // must include before any headers that include prtime.h
+#include "NSPRFormatTime.h" // must be before anything that includes prtime.h
 #include "TestCommon.h"
 
 #define FORCE_PR_LOG
 #include <stdio.h>
 #ifdef WIN32 
 #include <windows.h>
 #endif
 #ifdef XP_UNIX
--- a/parser/expat/expat_config.h
+++ b/parser/expat/expat_config.h
@@ -11,17 +11,17 @@
 
 #ifdef IS_LITTLE_ENDIAN
 #define BYTEORDER 1234
 #else 
 #define BYTEORDER 4321
 #endif /* IS_LITTLE_ENDIAN */
 
 #if PR_BYTES_PER_INT != 4
-#define int int32
+#define int int32_t
 #endif /* PR_BYTES_PER_INT != 4 */
 
 /* Other Mozilla code relies on memmove already, so we assume it's available */
 #define HAVE_MEMMOVE 1
 
 #define XMLCALL
 #define XML_STATIC
 #define XMLIMPORT
--- a/rdf/base/src/rdfutil.cpp
+++ b/rdf/base/src/rdfutil.cpp
@@ -14,17 +14,17 @@
   1) Make this so that it doesn't permanently leak the RDF service
      object.
 
   2) Make container functions thread-safe. They currently don't ensure
      that the RDF:nextVal property is maintained safely.
 
  */
 
-#include "NSPRFormatTime.h" // must include before any headers that include prtime.h
+#include "NSPRFormatTime.h" // must be before anything that includes prtime.h
 #include "nsCOMPtr.h"
 #include "nsIRDFDataSource.h"
 #include "nsIRDFNode.h"
 #include "nsIRDFService.h"
 #include "nsIServiceManager.h"
 #include "nsIURL.h"
 #include "nsIIOService.h"
 #include "nsIURL.h"
--- a/security/manager/boot/src/Makefile.in
+++ b/security/manager/boot/src/Makefile.in
@@ -11,16 +11,17 @@ include $(DEPTH)/config/autoconf.mk
 
 MODULE		= pipboot
 LIBRARY_NAME	= pipboot
 IS_COMPONENT	= 1
 MODULE_NAME	= BOOT
 EXPORT_LIBRARY	= 1
 GRE_MODULE	= 1
 LIBXUL_LIBRARY	= 1
+FAIL_ON_WARNINGS = 1
 
 CPPSRCS = \
 	nsEntropyCollector.cpp \
 	nsSecureBrowserUIImpl.cpp \
 	nsBOOTModule.cpp \
 	nsSecurityWarningDialogs.cpp \
 	nsStrictTransportSecurityService.cpp \
 	$(NULL)
--- a/security/manager/boot/src/nsStrictTransportSecurityService.cpp
+++ b/security/manager/boot/src/nsStrictTransportSecurityService.cpp
@@ -44,27 +44,27 @@ PRLogModuleInfo *gSTSLog = PR_NewLogModu
     return NS_ERROR_FAILURE; \
   }
 
 ////////////////////////////////////////////////////////////////////////////////
 
 nsSTSHostEntry::nsSTSHostEntry(const char* aHost)
   : mHost(aHost)
   , mExpireTime(0)
+  , mStsPermission(STS_UNSET)
   , mExpired(false)
-  , mStsPermission(STS_UNSET)
   , mIncludeSubdomains(false)
 {
 }
 
 nsSTSHostEntry::nsSTSHostEntry(const nsSTSHostEntry& toCopy)
   : mHost(toCopy.mHost)
   , mExpireTime(toCopy.mExpireTime)
+  , mStsPermission(toCopy.mStsPermission)
   , mExpired(toCopy.mExpired)
-  , mStsPermission(toCopy.mStsPermission)
   , mIncludeSubdomains(toCopy.mIncludeSubdomains)
 {
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 
 
 nsStrictTransportSecurityService::nsStrictTransportSecurityService()
--- a/security/manager/pki/src/Makefile.in
+++ b/security/manager/pki/src/Makefile.in
@@ -13,16 +13,17 @@ include $(DEPTH)/config/autoconf.mk
 
 MODULE		= pippki
 LIBRARY_NAME	= pippki
 IS_COMPONENT	= 1
 MODULE_NAME	= PKI
 EXPORT_LIBRARY	= 1
 GRE_MODULE	= 1
 LIBXUL_LIBRARY	= 1
+FAIL_ON_WARNINGS = 1
 
 CPPSRCS = \
 	nsNSSDialogs.cpp \
 	nsPKIModule.cpp \
 	nsPKIParamBlock.cpp \
         nsASN1Tree.cpp \
         nsNSSDialogHelper.cpp \
 	nsFormSigningDialog.cpp \
--- a/security/manager/ssl/src/nsCertTree.cpp
+++ b/security/manager/ssl/src/nsCertTree.cpp
@@ -1,13 +1,13 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-#include "NSPRFormatTime.h" // must include before any headers that include prtime.h
+#include "NSPRFormatTime.h" // must be before anything that includes prtime.h
 #include "nsNSSComponent.h" // for PIPNSS string bundle calls.
 #include "nsCertTree.h"
 #include "nsITreeColumns.h"
 #include "nsIX509Cert.h"
 #include "nsIX509CertValidity.h"
 #include "nsIX509CertDB.h"
 #include "nsXPIDLString.h"
 #include "nsReadableUtils.h"
--- a/testing/talos/talos.json
+++ b/testing/talos/talos.json
@@ -1,6 +1,6 @@
 {
     "talos.zip": {
-        "url": "http://build.mozilla.org/talos/zips/talos.8960d6a0b2c2.zip",
+        "url": "http://build.mozilla.org/talos/zips/talos.0e9224d7bc95.zip",
         "path": ""
     }
 }
--- a/toolkit/components/osfile/osfile_async_worker.js
+++ b/toolkit/components/osfile/osfile_async_worker.js
@@ -176,20 +176,20 @@ if (this.Components) {
       */
      let Agent = {
        // Functions of OS.File
        stat: function stat(path) {
          return exports.OS.File.Info.toMsg(
            exports.OS.File.stat(Type.path.fromMsg(path)));
        },
        getCurrentDirectory: function getCurrentDirectory() {
-         return exports.OS.Shared.Type.path.toMsg(exports.OS.File.curDir);
+         return exports.OS.Shared.Type.path.toMsg(File.getCurrentDirectory());
        },
        setCurrentDirectory: function setCurrentDirectory(path) {
-         exports.OS.File.curDir = exports.OS.Shared.Type.path.fromMsg(path);
+         File.setCurrentDirectory(exports.OS.Shared.Type.path.fromMsg(path));
        },
        copy: function copy(sourcePath, destPath, options) {
          return File.copy(Type.path.fromMsg(sourcePath),
            Type.path.fromMsg(destPath), options);
        },
        move: function move(sourcePath, destPath, options) {
          return File.move(Type.path.fromMsg(sourcePath),
            Type.path.fromMsg(destPath), options);
--- a/toolkit/components/osfile/osfile_unix_front.jsm
+++ b/toolkit/components/osfile/osfile_unix_front.jsm
@@ -841,29 +841,43 @@
        }
        return new File.Info(gStatData);
      };
 
      File.read = exports.OS.Shared.AbstractFile.read;
      File.writeAtomic = exports.OS.Shared.AbstractFile.writeAtomic;
 
      /**
+      * Get the current directory by getCurrentDirectory.
+      */
+     File.getCurrentDirectory = function getCurrentDirectory() {
+       let path = UnixFile.get_current_dir_name?UnixFile.get_current_dir_name():
+         UnixFile.getwd_auto(null);
+       throw_on_null("getCurrentDirectory",path);
+       return path.readString();
+     };
+
+     /**
+      * Set the current directory by setCurrentDirectory.
+      */
+     File.setCurrentDirectory = function setCurrentDirectory(path) {
+       throw_on_negative("setCurrentDirectory",
+         UnixFile.chdir(path)
+       );
+     };
+
+     /**
       * Get/set the current directory.
       */
      Object.defineProperty(File, "curDir", {
          set: function(path) {
-           throw_on_negative("curDir",
-             UnixFile.chdir(path)
-           );
+           this.setCurrentDirectory(path);
          },
          get: function() {
-           let path = UnixFile.get_current_dir_name?UnixFile.get_current_dir_name():
-             UnixFile.getwd_auto(null);
-           throw_on_null("curDir",path);
-           return path.readString();
+           return this.getCurrentDirectory();
          }
        }
      );
 
      // Utility functions
 
      /**
       * Turn the result of |open| into an Error or a File
--- a/toolkit/components/osfile/osfile_win_front.jsm
+++ b/toolkit/components/osfile/osfile_win_front.jsm
@@ -837,54 +837,67 @@
        winFlags: OS.Constants.Win.FILE_FLAG_BACKUP_SEMANTICS,
        winDisposition: OS.Constants.Win.OPEN_EXISTING
      };
 
      File.read = exports.OS.Shared.AbstractFile.read;
      File.writeAtomic = exports.OS.Shared.AbstractFile.writeAtomic;
 
      /**
-      * Get/set the current directory.
+      * Get the current directory by getCurrentDirectory.
       */
-     Object.defineProperty(File, "curDir", {
-         set: function(path) {
-           throw_on_zero("set curDir",
-             WinFile.SetCurrentDirectory(path));
-         },
-         get: function() {
+     File.getCurrentDirectory = function getCurrentDirectory() {
            // This function is more complicated than one could hope.
            //
            // This is due to two facts:
            // - the maximal length of a path under Windows is not completely
            //  specified (there is a constant MAX_PATH, but it is quite possible
            //  to create paths that are much larger, see bug 744413);
            // - if we attempt to call |GetCurrentDirectory| with a buffer that
            //  is too short, it returns the length of the current directory, but
            //  this length might be insufficient by the time we can call again
            //  the function with a larger buffer, in the (unlikely byt possible)
            //  case in which the process changes directory to a directory with
            //  a longer name between both calls.
-
            let buffer_size = 4096;
            while (true) {
              let array = new (ctypes.ArrayType(ctypes.jschar, buffer_size))();
-             let expected_size = throw_on_zero("get curDir",
+         let expected_size = throw_on_zero("getCurrentDirectory",
                WinFile.GetCurrentDirectory(buffer_size, array)
              );
              if (expected_size <= buffer_size) {
                return array.readString();
              }
              // At this point, we are in a case in which our buffer was not
              // large enough to hold the name of the current directory.
              // Consequently
 
              // Note that, even in crazy scenarios, the loop will eventually
              // converge, as the length of the paths cannot increase infinitely.
              buffer_size = expected_size;
            }
+     };
+
+     /**
+      * Set the current directory by setCurrentDirectory.
+      */
+     File.setCurrentDirectory = function setCurrentDirectory(path) {
+       throw_on_zero("setCurrentDirectory",
+         WinFile.SetCurrentDirectory(path));
+     };
+
+     /**
+      * Get/set the current directory by |curDir|.
+      */
+     Object.defineProperty(File, "curDir", {
+         set: function(path) {
+           this.setCurrentDirectory(path);
+         },
+         get: function() {
+           return this.getCurrentDirectory();
          }
        }
      );
 
      // Utility functions, used for error-handling
      function error_or_file(maybe) {
        if (maybe == exports.OS.Constants.Win.INVALID_HANDLE_VALUE) {
          throw new File.Error("open");
--- a/toolkit/components/osfile/tests/mochi/worker_test_osfile_front.js
+++ b/toolkit/components/osfile/tests/mochi/worker_test_osfile_front.js
@@ -436,17 +436,17 @@ function test_iter_dir()
 {
   ok(true, "test_iter_dir: Starting");
 
   // Create a file, to be sure that it exists
   let tmp_file_name = "test_osfile_front.tmp";
   let tmp_file = OS.File.open(tmp_file_name, {write: true, trunc:true});
   tmp_file.close();
 
-  let parent = OS.File.curDir;
+  let parent = OS.File.getCurrentDirectory();
   ok(true, "test_iter_dir: directory " + parent);
   let iterator = new OS.File.DirectoryIterator(parent);
   ok(true, "test_iter_dir: iterator created");
   let encountered_tmp_file = false;
   for (let entry in iterator) {
     // Checking that |name| can be decoded properly
     ok(true, "test_iter_dir: encountering entry " + entry.name);
 
@@ -666,17 +666,17 @@ function test_info() {
      "test_info: file 2 was accessed between the start of the test and now - " + start + ", " + stop + ", " + access);
 
   change = info.lastModificationDate;
   ok(change.getTime() >= startMs
      && change.getTime() <= stopMs,
      "test_info: file 2 has changed between the start of the test and now - " + start + ", " + stop + ", " + change);
 
   // Test OS.File.stat on directory
-  info = OS.File.stat(OS.File.curDir);
+  info = OS.File.stat(OS.File.getCurrentDirectory());
   ok(!!info, "test_info: info on directory acquired");
   ok(info.isDir, "test_info: directory is a directory");
 
   ok(true, "test_info: Complete");
 }
 
 function test_mkdir()
 {
--- a/toolkit/components/places/nsNavHistoryResult.cpp
+++ b/toolkit/components/places/nsNavHistoryResult.cpp
@@ -1158,17 +1158,17 @@ int32_t nsNavHistoryContainerResultNode:
         NS_ENSURE_SUCCESS(annosvc->GetItemAnnotationType(b->mItemId,
                                                          annoName,
                                                          &b_type), 0);
       } else {
         NS_ENSURE_SUCCESS(annosvc->GetPageAnnotationType(b_uri, annoName,
                                                          &b_type), 0);
       }
       // We better make the API not support this state, really
-      // XXXmano: this is actually wrong for double<->int and int64<->int32
+      // XXXmano: this is actually wrong for double<->int and int64_t<->int32_t
       if (a_hasAnno && b_type != annoType)
         return 0;
       annoType = b_type;
     }
 
 #define GET_ANNOTATIONS_VALUES(METHOD_ITEM, METHOD_PAGE, A_VAL, B_VAL)        \
         if (a_hasAnno) {                                                      \
           if (a_itemAnno) {                                                   \
--- a/toolkit/components/url-classifier/ChunkSet.cpp
+++ b/toolkit/components/url-classifier/ChunkSet.cpp
@@ -35,57 +35,57 @@ ChunkSet::Serialize(nsACString& aChunkSt
 
   return NS_OK;
 }
 
 nsresult
 ChunkSet::Set(uint32_t aChunk)
 {
   uint32_t idx = mChunks.BinaryIndexOf(aChunk);
-  if (idx == nsTArray<uint32>::NoIndex) {
+  if (idx == nsTArray<uint32_t>::NoIndex) {
     mChunks.InsertElementSorted(aChunk);
   }
   return NS_OK;
 }
 
 nsresult
 ChunkSet::Unset(uint32_t aChunk)
 {
   mChunks.RemoveElementSorted(aChunk);
 
   return NS_OK;
 }
 
 bool
 ChunkSet::Has(uint32_t aChunk) const
 {
-  return mChunks.BinaryIndexOf(aChunk) != nsTArray<uint32>::NoIndex;
+  return mChunks.BinaryIndexOf(aChunk) != nsTArray<uint32_t>::NoIndex;
 }
 
 nsresult
 ChunkSet::Merge(const ChunkSet& aOther)
 {
-  const uint32 *dupIter = aOther.mChunks.Elements();
-  const uint32 *end = aOther.mChunks.Elements() + aOther.mChunks.Length();
+  const uint32_t *dupIter = aOther.mChunks.Elements();
+  const uint32_t *end = aOther.mChunks.Elements() + aOther.mChunks.Length();
 
-  for (const uint32 *iter = dupIter; iter != end; iter++) {
+  for (const uint32_t *iter = dupIter; iter != end; iter++) {
     nsresult rv = Set(*iter);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   return NS_OK;
 }
 
 nsresult
 ChunkSet::Remove(const ChunkSet& aOther)
 {
-  uint32 *addIter = mChunks.Elements();
-  uint32 *end = mChunks.Elements() + mChunks.Length();
+  uint32_t *addIter = mChunks.Elements();
+  uint32_t *end = mChunks.Elements() + mChunks.Length();
 
-  for (uint32 *iter = addIter; iter != end; iter++) {
+  for (uint32_t *iter = addIter; iter != end; iter++) {
     if (!aOther.Has(*iter)) {
       *addIter = *iter;
       addIter++;
     }
   }
 
   mChunks.SetLength(addIter - mChunks.Elements());
 
--- a/toolkit/components/url-classifier/ChunkSet.h
+++ b/toolkit/components/url-classifier/ChunkSet.h
@@ -10,17 +10,17 @@
 #include "Entries.h"
 #include "nsString.h"
 #include "nsTArray.h"
 
 namespace mozilla {
 namespace safebrowsing {
 
 /**
- * Store the chunks as an array of uint32.
+ * Store the chunks as an array of uint32_t.
  * XXX: We should optimize this further to compress the
  * many consecutive numbers.
  */
 class ChunkSet {
 public:
   ChunkSet() {}
   ~ChunkSet() {}
 
@@ -28,29 +28,29 @@ public:
   nsresult Set(uint32_t aChunk);
   nsresult Unset(uint32_t aChunk);
   void Clear();
   nsresult Merge(const ChunkSet& aOther);
   nsresult Remove(const ChunkSet& aOther);
 
   bool Has(uint32_t chunk) const;
 
-  uint32 Length() const { return mChunks.Length(); }
+  uint32_t Length() const { return mChunks.Length(); }
 
   nsresult Write(nsIOutputStream* aOut) {
     return WriteTArray(aOut, mChunks);
   }
 
   nsresult Read(nsIInputStream* aIn, uint32_t aNumElements) {
     return ReadTArray(aIn, &mChunks, aNumElements);
   }
 
-  uint32 *Begin() { return mChunks.Elements(); }
-  uint32 *End() { return mChunks.Elements() + mChunks.Length(); }
+  uint32_t *Begin() { return mChunks.Elements(); }
+  uint32_t *End() { return mChunks.Elements() + mChunks.Length(); }
 
 private:
-  nsTArray<uint32> mChunks;
+  nsTArray<uint32_t> mChunks;
 };
 
 }
 }
 
 #endif
--- a/toolkit/components/url-classifier/Classifier.cpp
+++ b/toolkit/components/url-classifier/Classifier.cpp
@@ -122,17 +122,17 @@ Classifier::SetupPathNames()
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = mStoreDirectory->AppendNative(STORE_DIRECTORY);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Make sure LookupCaches (which are persistent and survive updates)
   // are reading/writing in the right place. We will be moving their
   // files "underneath" them during backup/restore.
-  for (uint32 i = 0; i < mLookupCaches.Length(); i++) {
+  for (uint32_t i = 0; i < mLookupCaches.Length(); i++) {
     mLookupCaches[i]->UpdateDirHandle(mStoreDirectory);
   }
 
   // Directory where to move a backup before an update.
   rv = mCacheDirectory->Clone(getter_AddRefs(mBackupDirectory));
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = mBackupDirectory->AppendNative(STORE_DIRECTORY + BACKUP_DIR_SUFFIX);
@@ -235,17 +235,17 @@ Classifier::Reset()
   RegenActiveTables();
 }
 
 void
 Classifier::TableRequest(nsACString& aResult)
 {
   nsTArray<nsCString> tables;
   ActiveTables(tables);
-  for (uint32 i = 0; i < tables.Length(); i++) {
+  for (uint32_t i = 0; i < tables.Length(); i++) {
     nsAutoPtr<HashStore> store(new HashStore(tables[i], mStoreDirectory));
     if (!store)
       continue;
 
     nsresult rv = store->Open();
     if (NS_FAILED(rv))
       continue;
 
@@ -371,17 +371,17 @@ Classifier::ApplyUpdates(nsTArray<TableU
 
   LOG(("Backup before update."));
 
   nsresult rv = BackupTables();
   NS_ENSURE_SUCCESS(rv, rv);
 
   LOG(("Applying table updates."));
 
-  for (uint32 i = 0; i < aUpdates->Length(); i++) {
+  for (uint32_t i = 0; i < aUpdates->Length(); i++) {
     // Previous ApplyTableUpdates() may have consumed this update..
     if ((*aUpdates)[i]) {
       // Run all updates for one table
       nsCString updateTable(aUpdates->ElementAt(i)->TableName());
       rv = ApplyTableUpdates(aUpdates, updateTable);
       if (NS_FAILED(rv)) {
         Reset();
         return rv;
@@ -415,46 +415,46 @@ Classifier::ApplyUpdates(nsTArray<TableU
 #endif
 
   return NS_OK;
 }
 
 nsresult
 Classifier::MarkSpoiled(nsTArray<nsCString>& aTables)
 {
-  for (uint32 i = 0; i < aTables.Length(); i++) {
+  for (uint32_t i = 0; i < aTables.Length(); i++) {
     LOG(("Spoiling table: %s", aTables[i].get()));
     // Spoil this table by marking it as no known freshness
     mTableFreshness.Remove(aTables[i]);
   }
   return NS_OK;
 }
 
 void
 Classifier::DropStores()
 {
-  for (uint32 i = 0; i < mHashStores.Length(); i++) {
+  for (uint32_t i = 0; i < mHashStores.Length(); i++) {
     delete mHashStores[i];
   }
   mHashStores.Clear();
-  for (uint32 i = 0; i < mLookupCaches.Length(); i++) {
+  for (uint32_t i = 0; i < mLookupCaches.Length(); i++) {
     delete mLookupCaches[i];
   }
   mLookupCaches.Clear();
 }
 
 nsresult
 Classifier::RegenActiveTables()
 {
   mActiveTablesCache.Clear();
 
   nsTArray<nsCString> foundTables;
   ScanStoreDir(foundTables);
 
-  for (uint32 i = 0; i < foundTables.Length(); i++) {
+  for (uint32_t i = 0; i < foundTables.Length(); i++) {
     nsAutoPtr<HashStore> store(new HashStore(nsCString(foundTables[i]), mStoreDirectory));
     if (!store)
       return NS_ERROR_OUT_OF_MEMORY;
 
     nsresult rv = store->Open();
     if (NS_FAILED(rv))
       continue;
 
@@ -624,19 +624,19 @@ Classifier::ApplyTableUpdates(nsTArray<T
 
   nsAutoPtr<HashStore> store(new HashStore(aTable, mStoreDirectory));
 
   if (!store)
     return NS_ERROR_FAILURE;
 
   // take the quick exit if there is no valid update for us
   // (common case)
-  uint32 validupdates = 0;
+  uint32_t validupdates = 0;
 
-  for (uint32 i = 0; i < aUpdates->Length(); i++) {
+  for (uint32_t i = 0; i < aUpdates->Length(); i++) {
     TableUpdate *update = aUpdates->ElementAt(i);
     if (!update || !update->TableName().Equals(store->TableName()))
       continue;
     if (update->Empty()) {
       aUpdates->ElementAt(i) = nullptr;
       delete update;
       continue;
     }
@@ -659,20 +659,20 @@ Classifier::ApplyTableUpdates(nsTArray<T
   }
   nsTArray<uint32_t> AddPrefixHashes;
   rv = prefixSet->GetPrefixes(&AddPrefixHashes);
   NS_ENSURE_SUCCESS(rv, rv);
   rv = store->AugmentAdds(AddPrefixHashes);
   NS_ENSURE_SUCCESS(rv, rv);
   AddPrefixHashes.Clear();
 
-  uint32 applied = 0;
+  uint32_t applied = 0;
   bool updateFreshness = false;
 
-  for (uint32 i = 0; i < aUpdates->Length(); i++) {
+  for (uint32_t i = 0; i < aUpdates->Length(); i++) {
     TableUpdate *update = aUpdates->ElementAt(i);
     if (!update || !update->TableName().Equals(store->TableName()))
       continue;
 
     rv = store->ApplyUpdate(*update);
     NS_ENSURE_SUCCESS(rv, rv);
 
     applied++;
@@ -729,17 +729,17 @@ Classifier::ApplyTableUpdates(nsTArray<T
   }
 
   return NS_OK;
 }
 
 LookupCache *
 Classifier::GetLookupCache(const nsACString& aTable)
 {
-  for (uint32 i = 0; i < mLookupCaches.Length(); i++) {
+  for (uint32_t i = 0; i < mLookupCaches.Length(); i++) {
     if (mLookupCaches[i]->TableName().Equals(aTable)) {
       return mLookupCaches[i];
     }
   }
 
   LookupCache *cache = new LookupCache(aTable, mStoreDirectory,
                                        mPerClientRandomize);
   nsresult rv = cache->Init();
--- a/toolkit/components/url-classifier/Entries.h
+++ b/toolkit/components/url-classifier/Entries.h
@@ -26,33 +26,33 @@ extern PRLogModuleInfo *gUrlClassifierDb
 #endif
 
 namespace mozilla {
 namespace safebrowsing {
 
 #define PREFIX_SIZE   4
 #define COMPLETE_SIZE 32
 
-template <uint32 S, class Comparator>
+template <uint32_t S, class Comparator>
 struct SafebrowsingHash
 {
-  static const uint32 sHashSize = S;
+  static const uint32_t sHashSize = S;
   typedef SafebrowsingHash<S, Comparator> self_type;
-  uint8 buf[S];
+  uint8_t buf[S];
 
   nsresult FromPlaintext(const nsACString& aPlainText, nsICryptoHash* aHash) {
     // From the protocol doc:
     // Each entry in the chunk is composed
     // of the SHA 256 hash of a suffix/prefix expression.
 
     nsresult rv = aHash->Init(nsICryptoHash::SHA256);
     NS_ENSURE_SUCCESS(rv, rv);
 
     rv = aHash->Update
-      (reinterpret_cast<const uint8*>(aPlainText.BeginReading()),
+      (reinterpret_cast<const uint8_t*>(aPlainText.BeginReading()),
        aPlainText.Length());
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsAutoCString hashed;
     rv = aHash->Finish(false, hashed);
     NS_ENSURE_SUCCESS(rv, rv);
 
     NS_ASSERTION(hashed.Length() >= sHashSize,
@@ -82,35 +82,35 @@ struct SafebrowsingHash
   }
 
   bool operator<(const self_type& aOther) const {
     return Comparator::Compare(buf, aOther.buf) < 0;
   }
 
 #ifdef DEBUG
   void ToString(nsACString& aStr) const {
-    uint32 len = ((sHashSize + 2) / 3) * 4;
+    uint32_t len = ((sHashSize + 2) / 3) * 4;
     aStr.SetCapacity(len + 1);
     PL_Base64Encode((char*)buf, sHashSize, aStr.BeginWriting());
     aStr.BeginWriting()[len] = '\0';
   }
 #endif
   uint32_t ToUint32() const {
-      return *((uint32*)buf);
+      return *((uint32_t*)buf);
   }
   void FromUint32(uint32_t aHash) {
-      *((uint32*)buf) = aHash;
+      *((uint32_t*)buf) = aHash;
   }
 };
 
 class PrefixComparator {
 public:
   static int Compare(const uint8_t* a, const uint8_t* b) {
-      uint32 first = *((uint32*)a);
-      uint32 second = *((uint32*)b);
+      uint32_t first = *((uint32_t*)a);
+      uint32_t second = *((uint32_t*)b);
       if (first > second) {
           return 1;
       } else if (first == second) {
           return 0;
       } else {
           return -1;
       }
   }
@@ -124,21 +124,21 @@ public:
     return memcmp(a, b, COMPLETE_SIZE);
   }
 };
 typedef SafebrowsingHash<COMPLETE_SIZE, CompletionComparator> Completion;
 typedef nsTArray<Completion> CompletionArray;
 
 struct AddPrefix {
   Prefix prefix;
-  uint32 addChunk;
+  uint32_t addChunk;
 
   AddPrefix() : addChunk(0) {}
 
-  uint32 Chunk() const { return addChunk; }
+  uint32_t Chunk() const { return addChunk; }
   const Prefix &PrefixHash() const { return prefix; }
 
   template<class T>
   int Compare(const T& other) const {
     int cmp = prefix.Compare(other.PrefixHash());
     if (cmp != 0) {
       return cmp;
     }
@@ -146,43 +146,43 @@ struct AddPrefix {
   }
 };
 
 struct AddComplete {
   union {
     Prefix prefix;
     Completion complete;
   } hash;
-  uint32 addChunk;
+  uint32_t addChunk;
 
   AddComplete() : addChunk(0) {}
 
-  uint32 Chunk() const { return addChunk; }
+  uint32_t Chunk() const { return addChunk; }
   const Prefix &PrefixHash() const { return hash.prefix; }
   const Completion &CompleteHash() const { return hash.complete; }
 
   template<class T>
   int Compare(const T& other) const {
     int cmp = hash.complete.Compare(other.CompleteHash());
     if (cmp != 0) {
       return cmp;
     }
     return addChunk - other.addChunk;
   }
 };
 
 struct SubPrefix {
   Prefix prefix;
-  uint32 addChunk;
-  uint32 subChunk;
+  uint32_t addChunk;
+  uint32_t subChunk;
 
   SubPrefix(): addChunk(0), subChunk(0) {}
 
-  uint32 Chunk() const { return subChunk; }
-  uint32 AddChunk() const { return addChunk; }
+  uint32_t Chunk() const { return subChunk; }
+  uint32_t AddChunk() const { return addChunk; }
   const Prefix &PrefixHash() const { return prefix; }
 
   template<class T>
   int Compare(const T& aOther) const {
     int cmp = prefix.Compare(aOther.PrefixHash());
     if (cmp != 0)
       return cmp;
     if (addChunk != aOther.addChunk)
@@ -199,23 +199,23 @@ struct SubPrefix {
   }
 };
 
 struct SubComplete {
   union {
     Prefix prefix;
     Completion complete;
   } hash;
-  uint32 addChunk;
-  uint32 subChunk;
+  uint32_t addChunk;
+  uint32_t subChunk;
 
   SubComplete() : addChunk(0), subChunk(0) {}
 
-  uint32 Chunk() const { return subChunk; }
-  uint32 AddChunk() const { return addChunk; }
+  uint32_t Chunk() const { return subChunk; }
+  uint32_t AddChunk() const { return addChunk; }
   const Prefix &PrefixHash() const { return hash.prefix; }
   const Completion &CompleteHash() const { return hash.complete; }
 
   int Compare(const SubComplete& aOther) const {
     int cmp = hash.complete.Compare(aOther.hash.complete);
     if (cmp != 0)
       return cmp;
     if (addChunk != aOther.addChunk)
--- a/toolkit/components/url-classifier/HashStore.cpp
+++ b/toolkit/components/url-classifier/HashStore.cpp
@@ -53,45 +53,45 @@
 // the upper 16-bits are correlated, it is worthwhile to slice 32-bit
 // values into 4 1-byte slices and compress the slices individually.
 // The slices corresponding to MSBs will compress very well, and the
 // slice corresponding to LSB almost nothing. Because of this, we
 // only apply DEFLATE to the 3 most significant bytes, and store the
 // LSB uncompressed.
 //
 // byte sliced (numValues) data format:
-//    uint32 compressed-size
+//    uint32_t compressed-size
 //    compressed-size bytes    zlib DEFLATE data
 //        0...numValues        byte MSB of 4-byte numValues data
-//    uint32 compressed-size
+//    uint32_t compressed-size
 //    compressed-size bytes    zlib DEFLATE data
 //        0...numValues        byte 2nd byte of 4-byte numValues data
-//    uint32 compressed-size
+//    uint32_t compressed-size
 //    compressed-size bytes    zlib DEFLATE data
 //        0...numValues        byte 3rd byte of 4-byte numValues data
 //    0...numValues            byte LSB of 4-byte numValues data
 //
 // Store data format:
-//    uint32 magic
-//    uint32 version
-//    uint32 numAddChunks
-//    uint32 numSubChunks
-//    uint32 numAddPrefixes
-//    uint32 numSubPrefixes
-//    uint32 numAddCompletes
-//    uint32 numSubCompletes
-//    0...numAddChunks               uint32 addChunk
-//    0...numSubChunks               uint32 subChunk
-//    byte sliced (numAddPrefixes)   uint32 add chunk of AddPrefixes
-//    byte sliced (numSubPrefixes)   uint32 add chunk of SubPrefixes
-//    byte sliced (numSubPrefixes)   uint32 sub chunk of SubPrefixes
-//    byte sliced (numSubPrefixes)   uint32 SubPrefixes
-//    0...numAddCompletes            32-byte Completions + uint32 addChunk
-//    0...numSubCompletes            32-byte Completions + uint32 addChunk
-//                                                       + uint32 subChunk
+//    uint32_t magic
+//    uint32_t version
+//    uint32_t numAddChunks
+//    uint32_t numSubChunks
+//    uint32_t numAddPrefixes
+//    uint32_t numSubPrefixes
+//    uint32_t numAddCompletes
+//    uint32_t numSubCompletes
+//    0...numAddChunks               uint32_t addChunk
+//    0...numSubChunks               uint32_t subChunk
+//    byte sliced (numAddPrefixes)   uint32_t add chunk of AddPrefixes
+//    byte sliced (numSubPrefixes)   uint32_t add chunk of SubPrefixes
+//    byte sliced (numSubPrefixes)   uint32_t sub chunk of SubPrefixes
+//    byte sliced (numSubPrefixes)   uint32_t SubPrefixes
+//    0...numAddCompletes            32-byte Completions + uint32_t addChunk
+//    0...numSubCompletes            32-byte Completions + uint32_t addChunk
+//                                                       + uint32_t subChunk
 //    16-byte MD5 of all preceding data
 
 // Name of the SafeBrowsing store
 #define STORE_SUFFIX ".sbstore"
 
 // NSPR_LOG_MODULES=UrlClassifierDbService:5
 extern PRLogModuleInfo *gUrlClassifierDbServiceLog;
 #if defined(PR_LOGGING)
@@ -112,18 +112,18 @@ extern PRLogModuleInfo *gUrlClassifierDb
       Reset();                                                            \
       return __rv;                                                        \
     }                                                                     \
   } while(0)
 
 namespace mozilla {
 namespace safebrowsing {
 
-const uint32 STORE_MAGIC = 0x1231af3b;
-const uint32 CURRENT_VERSION = 2;
+const uint32_t STORE_MAGIC = 0x1231af3b;
+const uint32_t CURRENT_VERSION = 2;
 
 void
 TableUpdate::NewAddPrefix(uint32_t aAddChunk, const Prefix& aHash)
 {
   AddPrefix *add = mAddPrefixes.AppendElement();
   add->addChunk = aAddChunk;
   add->prefix = aHash;
 }
@@ -309,17 +309,17 @@ HashStore::CalculateChecksum(nsAutoCStri
   // Reset mInputStream to start
   nsCOMPtr<nsISeekableStream> seekable = do_QueryInterface(mInputStream);
   nsresult rv = seekable->Seek(nsISeekableStream::NS_SEEK_SET, 0);
 
   nsCOMPtr<nsICryptoHash> hash = do_CreateInstance(NS_CRYPTO_HASH_CONTRACTID, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Size of MD5 hash in bytes
-  const uint32 CHECKSUM_SIZE = 16;
+  const uint32_t CHECKSUM_SIZE = 16;
 
   rv = hash->Init(nsICryptoHash::MD5);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (!aChecksumPresent) {
     // Hash entire file
     rv = hash->UpdateFromStream(mInputStream, UINT32_MAX);
   } else {
@@ -374,18 +374,18 @@ nsresult
 HashStore::ReadHashes()
 {
   if (!mInputStream) {
     return NS_OK;
   }
 
   nsCOMPtr<nsISeekableStream> seekable = do_QueryInterface(mInputStream);
 
-  uint32 offset = sizeof(Header);
-  offset += (mHeader.numAddChunks + mHeader.numSubChunks) * sizeof(uint32);
+  uint32_t offset = sizeof(Header);
+  offset += (mHeader.numAddChunks + mHeader.numSubChunks) * sizeof(uint32_t);
   nsresult rv = seekable->Seek(nsISeekableStream::NS_SEEK_SET, offset);
 
   rv = ReadAddPrefixes();
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = ReadSubPrefixes();
   NS_ENSURE_SUCCESS(rv, rv);
 
@@ -668,17 +668,17 @@ ByteSliceRead(nsIInputStream* aInStream,
   rv = InflateReadTArray(aInStream, &slice3, count);
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = ReadTArray(aInStream, &slice4, count);
   NS_ENSURE_SUCCESS(rv, rv);
 
   aData->SetCapacity(count);
 
-  for (uint32 i = 0; i < count; i++) {
+  for (uint32_t i = 0; i < count; i++) {
     aData->AppendElement((slice1[i] << 24) | (slice2[i] << 16)
                          | (slice3[i] << 8) | (slice4[i]));
   }
 
   return NS_OK;
 }
 
 nsresult
@@ -713,17 +713,17 @@ HashStore::ReadSubPrefixes()
 
   rv = ByteSliceRead(mInputStream, &subchunks, count);
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = ByteSliceRead(mInputStream, &prefixes, count);
   NS_ENSURE_SUCCESS(rv, rv);
 
   mSubPrefixes.SetCapacity(count);
-  for (uint32 i = 0; i < count; i++) {
+  for (uint32_t i = 0; i < count; i++) {
     SubPrefix *sub = mSubPrefixes.AppendElement();
     sub->addChunk = addchunks[i];
     sub->prefix.FromUint32(prefixes[i]);
     sub->subChunk = subchunks[i];
   }
 
   return NS_OK;
 }
@@ -731,17 +731,17 @@ HashStore::ReadSubPrefixes()
 // Split up PrefixArray back into the constituents
 nsresult
 HashStore::WriteAddPrefixes(nsIOutputStream* aOut)
 {
   nsTArray<uint32_t> chunks;
   uint32_t count = mAddPrefixes.Length();
   chunks.SetCapacity(count);
 
-  for (uint32 i = 0; i < count; i++) {
+  for (uint32_t i = 0; i < count; i++) {
     chunks.AppendElement(mAddPrefixes[i].Chunk());
   }
 
   nsresult rv = ByteSliceWrite(aOut, chunks);
   NS_ENSURE_SUCCESS(rv, rv);
 
   return NS_OK;
 }
@@ -752,17 +752,17 @@ HashStore::WriteSubPrefixes(nsIOutputStr
   nsTArray<uint32_t> addchunks;
   nsTArray<uint32_t> subchunks;
   nsTArray<uint32_t> prefixes;
   uint32_t count = mSubPrefixes.Length();
   addchunks.SetCapacity(count);
   subchunks.SetCapacity(count);
   prefixes.SetCapacity(count);
 
-  for (uint32 i = 0; i < count; i++) {
+  for (uint32_t i = 0; i < count; i++) {
     addchunks.AppendElement(mSubPrefixes[i].AddChunk());
     prefixes.AppendElement(mSubPrefixes[i].PrefixHash().ToUint32());
     subchunks.AppendElement(mSubPrefixes[i].Chunk());
   }
 
   nsresult rv = ByteSliceWrite(aOut, addchunks);
   NS_ENSURE_SUCCESS(rv, rv);
 
@@ -823,18 +823,18 @@ HashStore::WriteFile()
 
   return NS_OK;
 }
 
 template <class T>
 static void
 Erase(nsTArray<T>* array, T* iterStart, T* iterEnd)
 {
-  uint32 start = iterStart - array->Elements();
-  uint32 count = iterEnd - iterStart;
+  uint32_t start = iterStart - array->Elements();
+  uint32_t count = iterEnd - iterStart;
 
   if (count > 0) {
     array->RemoveElementsAt(start, count);
   }
 }
 
 // Find items matching between |subs| and |adds|, and remove them,
 // recording the item from |adds| in |adds_removed|.  To minimize
@@ -858,17 +858,17 @@ KnockoutSubs(nsTArray<TSub>* aSubs, nsTA
   TSub* subOut = aSubs->Elements();
   TSub* subIter = aSubs->Elements();
 
   TAdd* addEnd = addIter + aAdds->Length();
   TSub* subEnd = subIter + aSubs->Length();
 
   while (addIter != addEnd && subIter != subEnd) {
     // additer compare, so it compares on add chunk
-    int32 cmp = addIter->Compare(*subIter);
+    int32_t cmp = addIter->Compare(*subIter);
     if (cmp > 0) {
       // If |*sub_iter| < |*add_iter|, retain the sub.
       *subOut = *subIter;
       ++subOut;
       ++subIter;
     } else if (cmp < 0) {
       // If |*add_iter| < |*sub_iter|, retain the add.
       *addOut = *addIter;
@@ -895,17 +895,17 @@ RemoveMatchingPrefixes(const SubPrefixAr
   T* out = aFullHashes->Elements();
   T* hashIter = out;
   T* hashEnd = aFullHashes->Elements() + aFullHashes->Length();
 
   SubPrefix const * removeIter = aSubs.Elements();
   SubPrefix const * removeEnd = aSubs.Elements() + aSubs.Length();
 
   while (hashIter != hashEnd && removeIter != removeEnd) {
-    int32 cmp = removeIter->CompareAlt(*hashIter);
+    int32_t cmp = removeIter->CompareAlt(*hashIter);
     if (cmp > 0) {
       // Keep items less than |*removeIter|.
       *out = *hashIter;
       ++out;
       ++hashIter;
     } else if (cmp < 0) {
       // No hit for |*removeIter|, bump it forward.
       ++removeIter;
@@ -1001,22 +1001,22 @@ HashStore::ProcessSubs()
 #endif
 
   return NS_OK;
 }
 
 nsresult
 HashStore::AugmentAdds(const nsTArray<uint32_t>& aPrefixes)
 {
-  uint32 cnt = aPrefixes.Length();
+  uint32_t cnt = aPrefixes.Length();
   if (cnt != mAddPrefixes.Length()) {
     LOG(("Amount of prefixes in cache not consistent with store (%d vs %d)",
          aPrefixes.Length(), mAddPrefixes.Length()));
     return NS_ERROR_FAILURE;
   }
-  for (uint32 i = 0; i < cnt; i++) {
+  for (uint32_t i = 0; i < cnt; i++) {
     mAddPrefixes[i].prefix.FromUint32(aPrefixes[i]);
   }
   return NS_OK;
 }
 
 }
 }
--- a/toolkit/components/url-classifier/HashStore.h
+++ b/toolkit/components/url-classifier/HashStore.h
@@ -126,24 +126,24 @@ private:
   nsresult ReadSubPrefixes();
 
   nsresult WriteAddPrefixes(nsIOutputStream* aOut);
   nsresult WriteSubPrefixes(nsIOutputStream* aOut);
 
   nsresult ProcessSubs();
 
   struct Header {
-    uint32 magic;
-    uint32 version;
-    uint32 numAddChunks;
-    uint32 numSubChunks;
-    uint32 numAddPrefixes;
-    uint32 numSubPrefixes;
-    uint32 numAddCompletes;
-    uint32 numSubCompletes;
+    uint32_t magic;
+    uint32_t version;
+    uint32_t numAddChunks;
+    uint32_t numSubChunks;
+    uint32_t numAddPrefixes;
+    uint32_t numSubPrefixes;
+    uint32_t numAddCompletes;
+    uint32_t numSubCompletes;
   };
 
   Header mHeader;
 
   nsCString mTableName;
   nsCOMPtr<nsIFile> mStoreDirectory;
 
   bool mInUpdate;
--- a/toolkit/components/url-classifier/LookupCache.cpp
+++ b/toolkit/components/url-classifier/LookupCache.cpp
@@ -16,19 +16,19 @@
 // the updates from the protocol.
 
 // This module has its own store, which stores the Completions,
 // mostly caching lookups that have happened over the net.
 // The prefixes are cached/checked by looking them up in the
 // PrefixSet.
 
 // Data format for the ".cache" files:
-//    uint32 magic           Identify the file type
-//    uint32 version         Version identifier for file format
-//    uint32 numCompletions  Amount of completions stored
+//    uint32_t magic           Identify the file type
+//    uint32_t version         Version identifier for file format
+//    uint32_t numCompletions  Amount of completions stored
 //    0...numCompletions     256-bit Completions
 
 // Name of the lookupcomplete cache
 #define CACHE_SUFFIX ".cache"
 
 // Name of the persistent PrefixSet storage
 #define PREFIXSET_SUFFIX  ".pset"
 
@@ -40,18 +40,18 @@ extern PRLogModuleInfo *gUrlClassifierDb
 #else
 #define LOG(args)
 #define LOG_ENABLED() (false)
 #endif
 
 namespace mozilla {
 namespace safebrowsing {
 
-const uint32 LOOKUPCACHE_MAGIC = 0x1231af3e;
-const uint32 CURRENT_VERSION = 1;
+const uint32_t LOOKUPCACHE_MAGIC = 0x1231af3e;
+const uint32_t CURRENT_VERSION = 1;
 
 LookupCache::LookupCache(const nsACString& aTableName, nsIFile* aStoreDir,
                          bool aPerClientRandomize)
   : mPrimed(false)
   , mPerClientRandomize(aPerClientRandomize)
   , mTableName(aTableName)
   , mStoreDirectory(aStoreDir)
 {
@@ -154,17 +154,17 @@ nsresult
 LookupCache::Build(AddPrefixArray& aAddPrefixes,
                    AddCompleteArray& aAddCompletes)
 {
   Telemetry::Accumulate(Telemetry::URLCLASSIFIER_LC_COMPLETIONS,
                         static_cast<uint32_t>(aAddCompletes.Length()));
 
   mCompletions.Clear();
   mCompletions.SetCapacity(aAddCompletes.Length());
-  for (uint32 i = 0; i < aAddCompletes.Length(); i++) {
+  for (uint32_t i = 0; i < aAddCompletes.Length(); i++) {
     mCompletions.AppendElement(aAddCompletes[i].CompleteHash());
   }
   aAddCompletes.Clear();
   mCompletions.Sort();
 
   Telemetry::Accumulate(Telemetry::URLCLASSIFIER_LC_PREFIXES,
                         static_cast<uint32_t>(aAddPrefixes.Length()));
 
@@ -177,17 +177,17 @@ LookupCache::Build(AddPrefixArray& aAddP
 
 #if defined(DEBUG) && defined(PR_LOGGING)
 void
 LookupCache::Dump()
 {
   if (!LOG_ENABLED())
     return;
 
-  for (uint32 i = 0; i < mCompletions.Length(); i++) {
+  for (uint32_t i = 0; i < mCompletions.Length(); i++) {
     nsAutoCString str;
     mCompletions[i].ToString(str);
     LOG(("Completion: %s", str.get()));
   }
 }
 #endif
 
 nsresult
@@ -676,17 +676,17 @@ static void EnsureSorted(T* aArray)
 nsresult
 LookupCache::ConstructPrefixSet(AddPrefixArray& aAddPrefixes)
 {
   Telemetry::AutoTimer<Telemetry::URLCLASSIFIER_PS_CONSTRUCT_TIME> timer;
 
   nsTArray<uint32_t> array;
   array.SetCapacity(aAddPrefixes.Length());
 
-  for (uint32 i = 0; i < aAddPrefixes.Length(); i++) {
+  for (uint32_t i = 0; i < aAddPrefixes.Length(); i++) {
     array.AppendElement(aAddPrefixes[i].PrefixHash().ToUint32());
   }
   aAddPrefixes.Clear();
 
 #ifdef DEBUG
   // PrefixSet requires sorted order
   EnsureSorted(&array);
 #endif
--- a/toolkit/components/url-classifier/LookupCache.h
+++ b/toolkit/components/url-classifier/LookupCache.h
@@ -134,19 +134,19 @@ private:
   nsresult ReadCompletions(nsIInputStream* aInputStream);
   nsresult EnsureSizeConsistent();
   nsresult LoadPrefixSet();
   // Construct a Prefix Set with known prefixes.
   // This will Clear() aAddPrefixes when done.
   nsresult ConstructPrefixSet(AddPrefixArray& aAddPrefixes);
 
   struct Header {
-    uint32 magic;
-    uint32 version;
-    uint32 numCompletions;
+    uint32_t magic;
+    uint32_t version;
+    uint32_t numCompletions;
   };
   Header mHeader;
 
   bool mPrimed;
   bool mPerClientRandomize;
   nsCString mTableName;
   nsCOMPtr<nsIFile> mStoreDirectory;
   CompletionArray mCompletions;
--- a/toolkit/components/url-classifier/ProtocolParser.cpp
+++ b/toolkit/components/url-classifier/ProtocolParser.cpp
@@ -22,19 +22,19 @@ extern PRLogModuleInfo *gUrlClassifierDb
 #define LOG(args)
 #define LOG_ENABLED() (false)
 #endif
 
 namespace mozilla {
 namespace safebrowsing {
 
 // Updates will fail if fed chunks larger than this
-const uint32 MAX_CHUNK_SIZE = (1024 * 1024);
+const uint32_t MAX_CHUNK_SIZE = (1024 * 1024);
 
-const uint32 DOMAIN_SIZE = 4;
+const uint32_t DOMAIN_SIZE = 4;
 
 // Parse one stringified range of chunks of the form "n" or "n-m" from a
 // comma-separated list of chunks.  Upon return, 'begin' will point to the
 // next range of chunks in the list of chunks.
 static bool
 ParseChunkRange(nsACString::const_iterator& aBegin,
                 const nsACString::const_iterator& aEnd,
                 uint32_t* aFirst, uint32_t* aLast)
@@ -426,17 +426,17 @@ ProtocolParser::ProcessPlaintextChunk(co
     return NS_ERROR_FAILURE;
   }
 
   nsresult rv;
   nsTArray<nsCString> lines;
   ParseString(PromiseFlatCString(aChunk), '\n', lines);
 
   // non-hashed tables need to be hashed
-  for (uint32 i = 0; i < lines.Length(); i++) {
+  for (uint32_t i = 0; i < lines.Length(); i++) {
     nsCString& line = lines[i];
 
     if (mChunkState.type == CHUNK_ADD) {
       if (mChunkState.hashSize == COMPLETE_SIZE) {
         Completion hash;
         hash.FromPlaintext(line, mCryptoHash);
         mTableUpdate->NewAddComplete(mChunkState.num, hash);
       } else {
@@ -454,17 +454,17 @@ ProtocolParser::ProcessPlaintextChunk(co
         newHash.FromUint32(codedHash);
         mTableUpdate->NewAddPrefix(mChunkState.num, newHash);
       }
     } else {
       nsCString::const_iterator begin, iter, end;
       line.BeginReading(begin);
       line.EndReading(end);
       iter = begin;
-      uint32 addChunk;
+      uint32_t addChunk;
       if (!FindCharInReadable(':', iter, end) ||
           PR_sscanf(lines[i].get(), "%d:", &addChunk) != 1) {
         NS_WARNING("Received sub chunk without associated add chunk.");
         return NS_ERROR_FAILURE;
       }
       iter++;
 
       if (mChunkState.hashSize == COMPLETE_SIZE) {
@@ -502,17 +502,17 @@ ProtocolParser::ProcessShaChunk(const ns
   uint32_t start = 0;
   while (start < aChunk.Length()) {
     // First four bytes are the domain key.
     Prefix domain;
     domain.Assign(Substring(aChunk, start, DOMAIN_SIZE));
     start += DOMAIN_SIZE;
 
     // Then a count of entries.
-    uint8 numEntries = static_cast<uint8>(aChunk[start]);
+    uint8_t numEntries = static_cast<uint8_t>(aChunk[start]);
     start++;
 
     nsresult rv;
     if (mChunkState.type == CHUNK_ADD && mChunkState.hashSize == PREFIX_SIZE) {
       rv = ProcessHostAdd(domain, numEntries, aChunk, &start);
     } else if (mChunkState.type == CHUNK_ADD && mChunkState.hashSize == COMPLETE_SIZE) {
       rv = ProcessHostAddComplete(numEntries, aChunk, &start);
     } else if (mChunkState.type == CHUNK_SUB && mChunkState.hashSize == PREFIX_SIZE) {
@@ -552,17 +552,17 @@ ProtocolParser::ProcessHostAdd(const Pre
     return NS_OK;
   }
 
   if (*aStart + (PREFIX_SIZE * aNumEntries) > aChunk.Length()) {
     NS_WARNING("Chunk is not long enough to contain the expected entries.");
     return NS_ERROR_FAILURE;
   }
 
-  for (uint8 i = 0; i < aNumEntries; i++) {
+  for (uint8_t i = 0; i < aNumEntries; i++) {
     Prefix hash;
     hash.Assign(Substring(aChunk, *aStart, PREFIX_SIZE));
     nsresult rv = LookupCache::KeyedHash(hash.ToUint32(), domHash, mHashKey, &codedHash,
                                          !mPerClientRandomize);
     NS_ENSURE_SUCCESS(rv, rv);
     Prefix newHash;
     newHash.FromUint32(codedHash);
     mTableUpdate->NewAddPrefix(mChunkState.num, newHash);
@@ -586,17 +586,17 @@ ProtocolParser::ProcessHostSub(const Pre
     if ((*aStart) + 4 > aChunk.Length()) {
       NS_WARNING("Received a zero-entry sub chunk without an associated add.");
       return NS_ERROR_FAILURE;
     }
 
     const nsCSubstring& addChunkStr = Substring(aChunk, *aStart, 4);
     *aStart += 4;
 
-    uint32 addChunk;
+    uint32_t addChunk;
     memcpy(&addChunk, addChunkStr.BeginReading(), 4);
     addChunk = PR_ntohl(addChunk);
 
     nsresult rv = LookupCache::KeyedHash(domHash, domHash, mHashKey, &codedHash,
                                          !mPerClientRandomize);
     NS_ENSURE_SUCCESS(rv, rv);
     Prefix newHash;
     newHash.FromUint32(codedHash);
@@ -609,21 +609,21 @@ ProtocolParser::ProcessHostSub(const Pre
     return NS_OK;
   }
 
   if (*aStart + ((PREFIX_SIZE + 4) * aNumEntries) > aChunk.Length()) {
     NS_WARNING("Chunk is not long enough to contain the expected entries.");
     return NS_ERROR_FAILURE;
   }
 
-  for (uint8 i = 0; i < aNumEntries; i++) {
+  for (uint8_t i = 0; i < aNumEntries; i++) {
     const nsCSubstring& addChunkStr = Substring(aChunk, *aStart, 4);
     *aStart += 4;
 
-    uint32 addChunk;
+    uint32_t addChunk;
     memcpy(&addChunk, addChunkStr.BeginReading(), 4);
     addChunk = PR_ntohl(addChunk);
 
     Prefix prefix;
     prefix.Assign(Substring(aChunk, *aStart, PREFIX_SIZE));
     *aStart += PREFIX_SIZE;
 
     nsresult rv = LookupCache::KeyedHash(prefix.ToUint32(), domHash, mHashKey,
@@ -655,17 +655,17 @@ ProtocolParser::ProcessHostAddComplete(u
     return NS_OK;
   }
 
   if (*aStart + (COMPLETE_SIZE * aNumEntries) > aChunk.Length()) {
     NS_WARNING("Chunk is not long enough to contain the expected entries.");
     return NS_ERROR_FAILURE;
   }
 
-  for (uint8 i = 0; i < aNumEntries; i++) {
+  for (uint8_t i = 0; i < aNumEntries; i++) {
     Completion hash;
     hash.Assign(Substring(aChunk, *aStart, COMPLETE_SIZE));
     mTableUpdate->NewAddComplete(mChunkState.num, hash);
     *aStart += COMPLETE_SIZE;
   }
 
   return NS_OK;
 }
@@ -691,51 +691,51 @@ ProtocolParser::ProcessHostSubComplete(u
   for (uint8_t i = 0; i < aNumEntries; i++) {
     Completion hash;
     hash.Assign(Substring(aChunk, *aStart, COMPLETE_SIZE));
     *aStart += COMPLETE_SIZE;
 
     const nsCSubstring& addChunkStr = Substring(aChunk, *aStart, 4);
     *aStart += 4;
 
-    uint32 addChunk;
+    uint32_t addChunk;
     memcpy(&addChunk, addChunkStr.BeginReading(), 4);
     addChunk = PR_ntohl(addChunk);
 
     mTableUpdate->NewSubComplete(addChunk, hash, mChunkState.num);
   }
 
   return NS_OK;
 }
 
 bool
 ProtocolParser::NextLine(nsACString& line)
 {
-  int32 newline = mPending.FindChar('\n');
+  int32_t newline = mPending.FindChar('\n');
   if (newline == kNotFound) {
     return false;
   }
   line.Assign(Substring(mPending, 0, newline));
   mPending = Substring(mPending, newline + 1);
   return true;
 }
 
 void
 ProtocolParser::CleanupUpdates()
 {
-  for (uint32 i = 0; i < mTableUpdates.Length(); i++) {
+  for (uint32_t i = 0; i < mTableUpdates.Length(); i++) {
     delete mTableUpdates[i];
   }
   mTableUpdates.Clear();
 }
 
 TableUpdate *
 ProtocolParser::GetTableUpdate(const nsACString& aTable)
 {
-  for (uint32 i = 0; i < mTableUpdates.Length(); i++) {
+  for (uint32_t i = 0; i < mTableUpdates.Length(); i++) {
     if (aTable.Equals(mTableUpdates[i]->TableName())) {
       return mTableUpdates[i];
     }
   }
 
   // We free automatically on destruction, ownership of these
   // updates can be transferred to DBServiceWorker, which passes
   // them back to Classifier when doing the updates, and that
--- a/toolkit/components/url-classifier/ProtocolParser.h
+++ b/toolkit/components/url-classifier/ProtocolParser.h
@@ -42,17 +42,17 @@ public:
   // Forget the table updates that were created by this pass.  It
   // becomes the caller's responsibility to free them.  This is shitty.
   TableUpdate *GetTableUpdate(const nsACString& aTable);
   void ForgetTableUpdates() { mTableUpdates.Clear(); }
   nsTArray<TableUpdate*> &GetTableUpdates() { return mTableUpdates; }
 
   // Update information.
   const nsTArray<ForwardedUpdate> &Forwards() const { return mForwards; }
-  int32 UpdateWait() { return mUpdateWait; }
+  int32_t UpdateWait() { return mUpdateWait; }
   bool ResetRequested() { return mResetRequested; }
   bool RekeyRequested() { return mRekeyRequested; }
 
 private:
   nsresult ProcessControl(bool* aDone);
   nsresult ProcessMAC(const nsCString& aLine);
   nsresult ProcessExpirations(const nsCString& aLine);
   nsresult ProcessChunkControl(const nsCString& aLine);
@@ -81,34 +81,34 @@ private:
 
   enum ChunkType {
     CHUNK_ADD,
     CHUNK_SUB
   };
 
   struct ChunkState {
     ChunkType type;
-    uint32 num;
-    uint32 hashSize;
-    uint32 length;
+    uint32_t num;
+    uint32_t hashSize;
+    uint32_t length;
     void Clear() { num = 0; hashSize = 0; length = 0; }
   };
   ChunkState mChunkState;
 
   uint32_t mHashKey;
   bool mPerClientRandomize;
   nsCOMPtr<nsICryptoHash> mCryptoHash;
 
   nsresult mUpdateStatus;
   nsCString mPending;
 
   nsCOMPtr<nsICryptoHMAC> mHMAC;
   nsCString mServerMAC;
 
-  uint32 mUpdateWait;
+  uint32_t mUpdateWait;
   bool mResetRequested;
   bool mRekeyRequested;
 
   nsTArray<ForwardedUpdate> mForwards;
   nsTArray<TableUpdate*> mTableUpdates;
   TableUpdate *mTableUpdate;
 };
 
--- a/toolkit/components/url-classifier/nsCheckSummedOutputStream.cpp
+++ b/toolkit/components/url-classifier/nsCheckSummedOutputStream.cpp
@@ -45,15 +45,15 @@ nsCheckSummedOutputStream::Finish()
   NS_ENSURE_SUCCESS(rv, rv);
 
   return nsSafeFileOutputStream::Finish();
 }
 
 NS_IMETHODIMP
 nsCheckSummedOutputStream::Write(const char *buf, uint32_t count, uint32_t *result)
 {
-  nsresult rv = mHash->Update(reinterpret_cast<const uint8*>(buf), count);
+  nsresult rv = mHash->Update(reinterpret_cast<const uint8_t*>(buf), count);
   NS_ENSURE_SUCCESS(rv, rv);
 
   return nsSafeFileOutputStream::Write(buf, count, result);
 }
 
 ////////////////////////////////////////////////////////////////////////////////
--- a/toolkit/components/url-classifier/nsUrlClassifierDBService.cpp
+++ b/toolkit/components/url-classifier/nsUrlClassifierDBService.cpp
@@ -565,17 +565,17 @@ nsUrlClassifierDBServiceWorker::FinishSt
   mProtocolParser->FinishHMAC();
   if (NS_SUCCEEDED(mProtocolParser->Status())) {
     if (mProtocolParser->UpdateWait()) {
       mUpdateWait = mProtocolParser->UpdateWait();
     }
     // XXX: Only allow forwards from the initial update?
     const nsTArray<ProtocolParser::ForwardedUpdate> &forwards =
       mProtocolParser->Forwards();
-    for (uint32 i = 0; i < forwards.Length(); i++) {
+    for (uint32_t i = 0; i < forwards.Length(); i++) {
       const ProtocolParser::ForwardedUpdate &forward = forwards[i];
       mUpdateObserver->UpdateUrlRequested(forward.url, forward.table, forward.mac);
     }
     // Hold on to any TableUpdate objects that were created by the
     // parser.
     mTableUpdates.AppendElements(mProtocolParser->GetTableUpdates());
     mProtocolParser->ForgetTableUpdates();
   } else {
@@ -978,17 +978,17 @@ nsUrlClassifierLookupCallback::HandleRes
   }
 
   // Some parts of this gethash request generated no hits at all.
   // Prefixes must have been removed from the database since our last update.
   // Save the prefixes we checked to prevent repeated requests
   // until the next update.
   nsAutoPtr<PrefixArray> cacheMisses(new PrefixArray());
   if (cacheMisses) {
-    for (uint32 i = 0; i < mResults->Length(); i++) {
+    for (uint32_t i = 0; i < mResults->Length(); i++) {
       LookupResult &result = mResults->ElementAt(i);
       if (!result.Confirmed()) {
         cacheMisses->AppendElement(result.PrefixHash());
       }
     }
     // Hands ownership of the miss array back to the worker thread.
     mDBService->CacheMisses(cacheMisses.forget());
   }
--- a/toolkit/profile/nsToolkitProfileService.cpp
+++ b/toolkit/profile/nsToolkitProfileService.cpp
@@ -604,17 +604,17 @@ static const char kTable[] =
       'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
       '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' };
 
 static void SaltProfileName(nsACString& aName)
 {
     double fpTime = double(PR_Now());
 
     // use 1e-6, granularity of PR_Now() on the mac is seconds
-    srand((uint)(fpTime * 1e-6 + 0.5));
+    srand((unsigned int)(fpTime * 1e-6 + 0.5));
 
     char salt[9];
 
     int i;
     for (i = 0; i < 8; ++i)
         salt[i] = kTable[rand() % ArrayLength(kTable)];
 
     salt[8] = '.';
--- a/tools/profiler/libunwind/src/include/unwind.h
+++ b/tools/profiler/libunwind/src/include/unwind.h
@@ -66,17 +66,17 @@ typedef void (*_Unwind_Exception_Cleanup
 
 typedef _Unwind_Reason_Code (*_Unwind_Stop_Fn) (int, _Unwind_Action,
 						uint64_t,
 						struct _Unwind_Exception *,
 						struct _Unwind_Context *,
 						void *);
 
 /* The C++ ABI requires exception_class, private_1, and private_2 to
-   be of type uint64 and the entire structure to be
+   be of type uint64_t and the entire structure to be
    double-word-aligned. Please note that exception_class stays 64-bit 
    even on 32-bit machines for gcc compatibility.  */
 struct _Unwind_Exception
   {
     uint64_t exception_class;
     _Unwind_Exception_Cleanup_Fn exception_cleanup;
     unsigned long private_1;
     unsigned long private_2;
--- a/tools/trace-malloc/bloatblame.cpp
+++ b/tools/trace-malloc/bloatblame.cpp
@@ -31,17 +31,17 @@ extern int  optind;
 #include "tmreader.h"
 
 static char   *program;
 static int    sort_by_direct = 0;
 static int    js_mode = 0;
 static int    do_tree_dump = 0;
 static int    unified_output = 0;
 static char   *function_dump = NULL;
-static uint32 min_subtotal = 0;
+static uint32_t min_subtotal = 0;
 
 static void compute_callsite_totals(tmcallsite *site)
 {
     tmcallsite *kid;
 
     site->allocs.bytes.total += site->allocs.bytes.direct;
     site->allocs.calls.total += site->allocs.calls.direct;
     for (kid = site->kids; kid; kid = kid->siblings) {
@@ -200,17 +200,17 @@ static int tabulate_node(PLHashEntry *he
         (curr->allocs.bytes.total < next->allocs.bytes.total));
     return HT_ENUMERATE_NEXT;
 }
 
 /* Sort in reverse size order, so biggest node comes first. */
 static int node_table_compare(const void *p1, const void *p2)
 {
     const tmgraphnode *node1, *node2;
-    uint32 key1, key2;
+    uint32_t key1, key2;
 
     node1 = *(const tmgraphnode**) p1;
     node2 = *(const tmgraphnode**) p2;
     if (sort_by_direct) {
         key1 = node1->allocs.bytes.direct;
         key2 = node2->allocs.bytes.direct;
     } else {
         key1 = node1->allocs.bytes.total;
@@ -234,30 +234,30 @@ static int mean_size_compare(const void 
     key2 = (double)node2->allocs.bytes.direct / div2;
     if (key1 < key2)
         return 1;
     if (key1 > key2)
         return -1;
     return 0;
 }
 
-static const char *prettybig(uint32 num, char *buf, size_t limit)
+static const char *prettybig(uint32_t num, char *buf, size_t limit)
 {
     if (num >= 1000000000)
         PR_snprintf(buf, limit, "%1.2fG", (double) num / 1e9);
     else if (num >= 1000000)
         PR_snprintf(buf, limit, "%1.2fM", (double) num / 1e6);
     else if (num >= 1000)
         PR_snprintf(buf, limit, "%1.2fK", (double) num / 1e3);
     else
         PR_snprintf(buf, limit, "%lu", (unsigned long) num);
     return buf;
 }
 
-static double percent(uint32 num, uint32 total)
+static double percent(uint32_t num, uint32_t total)
 {
     if (num == 0)
         return 0.0;
     return ((double) num * 100) / (double) total;
 }
 
 static void sort_graphlink_list(tmgraphlink **listp, int which)
 {
@@ -306,17 +306,17 @@ static void dump_graphlink_list(tmgraphl
         }
         fputs("</td>", fp);
     }
 }
 
 static void dump_graph(tmreader *tmr, PLHashTable *hashtbl, const char *varname,
                        const char *title, FILE *fp)
 {
-    uint32 i, count;
+    uint32_t i, count;
     tmgraphnode **table, *node;
     char *name;
     size_t namelen;
     char buf1[16], buf2[16], buf3[16], buf4[16];
 
     count = hashtbl->nentries;
     table = (tmgraphnode**) malloc(count * sizeof(tmgraphnode*));
     if (!table) {
@@ -456,18 +456,18 @@ static void dump_graph(tmreader *tmr, PL
                     "<tr>"
                       "<td valign=top>%.*s%s</td>"
                       "<td valign=top>%s</td>"
                       "<td valign=top>%s</td>"
                       "<td valign=top>%s</td>"
                     "</tr>\n",
                     (namelen > 65) ? 45 : (int)namelen, name,
                     (namelen > 65) ? "<i>...</i>" : "",
-                    prettybig((uint32)mean, buf1, sizeof buf1),
-                    prettybig((uint32)sigma, buf2, sizeof buf2),
+                    prettybig((uint32_t)mean, buf1, sizeof buf1),
+                    prettybig((uint32_t)sigma, buf2, sizeof buf2),
                     prettybig(node->allocs.calls.direct, buf3, sizeof buf3));
         }
         fputs("</table>\n", fp);
     }
 
     free((void*) table);
 }
 
--- a/tools/trace-malloc/leakstats.c
+++ b/tools/trace-malloc/leakstats.c
@@ -20,22 +20,22 @@ int optind=1;
 #include <time.h>
 #include "nsTraceMalloc.h"
 #include "tmreader.h"
 #include "prlog.h"
 
 static char *program;
 
 typedef struct handler_data {
-    uint32 current_heapsize;
-    uint32 max_heapsize;
-    uint32 bytes_allocated;
-    uint32 current_allocations;
-    uint32 total_allocations;
-    uint32 unmatched_frees;
+    uint32_t current_heapsize;
+    uint32_t max_heapsize;
+    uint32_t bytes_allocated;
+    uint32_t current_allocations;
+    uint32_t total_allocations;
+    uint32_t unmatched_frees;
     int finished;
 } handler_data;
 
 static void handler_data_init(handler_data *data)
 {
     data->current_heapsize = 0;
     data->max_heapsize = 0;
     data->bytes_allocated = 0;
--- a/tools/trace-malloc/lib/nsDebugHelpWin32.cpp
+++ b/tools/trace-malloc/lib/nsDebugHelpWin32.cpp
@@ -219,17 +219,17 @@ DHWImportHooker::PatchOneModule(HMODULE 
     if(aModule == mIgnoreModule)
     {
         return true;
     }
 
     // do the fun stuff...
 
     PIMAGE_IMPORT_DESCRIPTOR desc;
-    uint32 size;
+    ULONG size;
 
     desc = (PIMAGE_IMPORT_DESCRIPTOR) 
         dhwImageDirectoryEntryToData(aModule, true, 
                                      IMAGE_DIRECTORY_ENTRY_IMPORT, &size);
 
     if(!desc)
     {
         return true;
--- a/tools/trace-malloc/lib/nsTraceMalloc.c
+++ b/tools/trace-malloc/lib/nsTraceMalloc.c
@@ -91,18 +91,18 @@ typedef struct logfile logfile;
 #define LOGFILE_TMBUFSIZE (16 * 1024)
 
 struct logfile {
     int         fd;
     int         lfd;            /* logical fd, dense among all logfiles */
     char        *buf;
     int         bufsize;
     int         pos;
-    uint32      size;
-    uint32      simsize;
+    uint32_t    size;
+    uint32_t    simsize;
     logfile     *next;
     logfile     **prevp;
 };
 
 static char      default_buf[STARTUP_TMBUFSIZE];
 static logfile   default_logfile =
                    {-1, 0, default_buf, STARTUP_TMBUFSIZE, 0, 0, 0, NULL, NULL};
 static logfile   *logfile_list = NULL;
@@ -120,22 +120,22 @@ static char      sdlogname[PATH_MAX] = "
  * It is separate from suppress_tracing so that we do not have to pay
  * the performance cost of repeated TM_TLS_GET_DATA calls when
  * trace-malloc is disabled (which is not as bad as the locking we used
  * to have).
  *
  * It must default to zero, since it can be tested by the Linux malloc
  * hooks before NS_TraceMallocStartup sets it.
  */
-static uint32 tracing_enabled = 0;
+static uint32_t tracing_enabled = 0;
 
 /*
  * Control whether we should log stacks
  */
-static uint32 stacks_enabled = 1;
+static uint32_t stacks_enabled = 1;
 
 /*
  * This lock must be held while manipulating the calltree, the
  * allocations table, the log, or the tmstats.
  *
  * Callers should not *enter* the lock without checking suppress_tracing
  * first; otherwise they risk trying to re-enter on the same thread.
  */
@@ -263,23 +263,23 @@ tm_get_thread(void)
 
         PR_ASSERT(stack_tm_thread.suppress_tracing == 1); /* balanced */
     }
 
     return t;
 }
 
 /* We don't want more than 32 logfiles open at once, ok? */
-typedef uint32          lfd_set;
+typedef uint32_t        lfd_set;
 
 #define LFD_SET_STATIC_INITIALIZER 0
 #define LFD_SET_SIZE    32
 
 #define LFD_ZERO(s)     (*(s) = 0)
-#define LFD_BIT(i)      ((uint32)1 << (i))
+#define LFD_BIT(i)      ((uint32_t)1 << (i))
 #define LFD_TEST(i,s)   (LFD_BIT(i) & *(s))
 #define LFD_SET(i,s)    (*(s) |= LFD_BIT(i))
 #define LFD_CLR(i,s)    (*(s) &= ~LFD_BIT(i))
 
 static logfile *get_logfile(int fd)
 {
     logfile *fp;
     int lfd;
@@ -377,17 +377,17 @@ static void log_filename(logfile* fp, co
                 *cp = '/';
         }
 
         filename = bp;
     }
     log_string(fp, filename);
 }
 
-static void log_uint32(logfile *fp, uint32 ival)
+static void log_uint32(logfile *fp, uint32_t ival)
 {
     if (ival < 0x80) {
         /* 0xxx xxxx */
         log_byte(fp, (char) ival);
     } else if (ival < 0x4000) {
         /* 10xx xxxx xxxx xxxx */
         log_byte(fp, (char) ((ival >> 8) | 0x80));
         log_byte(fp, (char) (ival & 0xff));
@@ -407,92 +407,92 @@ static void log_uint32(logfile *fp, uint
         log_byte(fp, (char) 0xf0);
         log_byte(fp, (char) ((ival >> 24) & 0xff));
         log_byte(fp, (char) ((ival >> 16) & 0xff));
         log_byte(fp, (char) ((ival >> 8) & 0xff));
         log_byte(fp, (char) (ival & 0xff));
     }
 }
 
-static void log_event1(logfile *fp, char event, uint32 serial)
+static void log_event1(logfile *fp, char event, uint32_t serial)
 {
     log_byte(fp, event);
-    log_uint32(fp, (uint32) serial);
+    log_uint32(fp, (uint32_t) serial);
 }
 
-static void log_event2(logfile *fp, char event, uint32 serial, size_t size)
+static void log_event2(logfile *fp, char event, uint32_t serial, size_t size)
 {
     log_event1(fp, event, serial);
-    log_uint32(fp, (uint32) size);
+    log_uint32(fp, (uint32_t) size);
 }
 
-static void log_event3(logfile *fp, char event, uint32 serial, size_t oldsize,
+static void log_event3(logfile *fp, char event, uint32_t serial, size_t oldsize,
                        size_t size)
 {
     log_event2(fp, event, serial, oldsize);
-    log_uint32(fp, (uint32) size);
+    log_uint32(fp, (uint32_t) size);
 }
 
-static void log_event4(logfile *fp, char event, uint32 serial, uint32 ui2,
-                       uint32 ui3, uint32 ui4)
+static void log_event4(logfile *fp, char event, uint32_t serial, uint32_t ui2,
+                       uint32_t ui3, uint32_t ui4)
 {
     log_event3(fp, event, serial, ui2, ui3);
     log_uint32(fp, ui4);
 }
 
-static void log_event5(logfile *fp, char event, uint32 serial, uint32 ui2,
-                       uint32 ui3, uint32 ui4, uint32 ui5)
+static void log_event5(logfile *fp, char event, uint32_t serial, uint32_t ui2,
+                       uint32_t ui3, uint32_t ui4, uint32_t ui5)
 {
     log_event4(fp, event, serial, ui2, ui3, ui4);
     log_uint32(fp, ui5);
 }
 
-static void log_event6(logfile *fp, char event, uint32 serial, uint32 ui2,
-                       uint32 ui3, uint32 ui4, uint32 ui5, uint32 ui6)
+static void log_event6(logfile *fp, char event, uint32_t serial, uint32_t ui2,
+                       uint32_t ui3, uint32_t ui4, uint32_t ui5, uint32_t ui6)
 {
     log_event5(fp, event, serial, ui2, ui3, ui4, ui5);
     log_uint32(fp, ui6);
 }
 
-static void log_event7(logfile *fp, char event, uint32 serial, uint32 ui2,
-                       uint32 ui3, uint32 ui4, uint32 ui5, uint32 ui6,
-                       uint32 ui7)
+static void log_event7(logfile *fp, char event, uint32_t serial, uint32_t ui2,
+                       uint32_t ui3, uint32_t ui4, uint32_t ui5, uint32_t ui6,
+                       uint32_t ui7)
 {
     log_event6(fp, event, serial, ui2, ui3, ui4, ui5, ui6);
     log_uint32(fp, ui7);
 }
 
-static void log_event8(logfile *fp, char event, uint32 serial, uint32 ui2,
-                       uint32 ui3, uint32 ui4, uint32 ui5, uint32 ui6,
-                       uint32 ui7, uint32 ui8)
+static void log_event8(logfile *fp, char event, uint32_t serial, uint32_t ui2,
+                       uint32_t ui3, uint32_t ui4, uint32_t ui5, uint32_t ui6,
+                       uint32_t ui7, uint32_t ui8)
 {
     log_event7(fp, event, serial, ui2, ui3, ui4, ui5, ui6, ui7);
     log_uint32(fp, ui8);
 }
 
 typedef struct callsite callsite;
 
 struct callsite {
     void*       pc;
-    uint32      serial;
+    uint32_t      serial;
     lfd_set     lfdset;
     const char  *name;    /* pointer to string owned by methods table */
     const char  *library; /* pointer to string owned by libraries table */
     int         offset;
     callsite    *parent;
     callsite    *siblings;
     callsite    *kids;
 };
 
 /* NB: these counters are incremented and decremented only within tmlock. */
-static uint32 library_serial_generator = 0;
-static uint32 method_serial_generator = 0;
-static uint32 callsite_serial_generator = 0;
-static uint32 tmstats_serial_generator = 0;
-static uint32 filename_serial_generator = 0;
+static uint32_t library_serial_generator = 0;
+static uint32_t method_serial_generator = 0;
+static uint32_t callsite_serial_generator = 0;
+static uint32_t tmstats_serial_generator = 0;
+static uint32_t filename_serial_generator = 0;
 
 /* Root of the tree of callsites, the sum of all (cycle-compressed) stacks. */
 static callsite calltree_root =
   {0, 0, LFD_SET_STATIC_INITIALIZER, NULL, NULL, 0, NULL, NULL, NULL};
 
 /* a fake pc for when stacks are disabled; must be different from the
    pc in calltree_root */
 #define STACK_DISABLED_PC ((void*)1)
@@ -588,20 +588,20 @@ static PLHashTable *methods = NULL;
  * Presumes that its caller is holding tmlock, but may temporarily exit
  * the lock.
  */
 static callsite *
 calltree(void **stack, size_t num_stack_entries, tm_thread *t)
 {
     logfile *fp = logfp;
     void *pc;
-    uint32 nkids;
+    uint32_t nkids;
     callsite *parent, *site, **csp, *tmp;
     int maxstack;
-    uint32 library_serial, method_serial, filename_serial;
+    uint32_t library_serial, method_serial, filename_serial;
     const char *library, *method, *filename;
     char *slash;
     PLHashNumber hash;
     PLHashEntry **hep, *he;
     lfdset_entry *le;
     size_t stack_index;
     nsCodeAddressDetails details;
     nsresult rv;
@@ -713,17 +713,17 @@ calltree(void **stack, size_t num_stack_
                     goto fail;
                 }
             }
             hash = PL_HashString(details.library);
             hep = PL_HashTableRawLookup(libraries, hash, details.library);
             he = *hep;
             if (he) {
                 library = (char*) he->key;
-                library_serial = (uint32) NS_PTR_TO_INT32(he->value);
+                library_serial = (uint32_t) NS_PTR_TO_INT32(he->value);
                 le = (lfdset_entry *) he;
                 if (LFD_TEST(fp->lfd, &le->lfdset)) {
                     /* We already logged an event on fp for this library. */
                     le = NULL;
                 }
             } else {
                 library = strdup(details.library);
                 if (library) {
@@ -760,17 +760,17 @@ calltree(void **stack, size_t num_stack_
                 return NULL;
             }
         }
         hash = PL_HashString(filename);
         hep = PL_HashTableRawLookup(filenames, hash, filename);
         he = *hep;
         if (he) {
             filename = (char*) he->key;
-            filename_serial = (uint32) NS_PTR_TO_INT32(he->value);
+            filename_serial = (uint32_t) NS_PTR_TO_INT32(he->value);
             le = (lfdset_entry *) he;
             if (LFD_TEST(fp->lfd, &le->lfdset)) {
                 /* We already logged an event on fp for this filename. */
                 le = NULL;
             }
         } else {
             filename = strdup(filename);
             if (filename) {
@@ -807,17 +807,17 @@ calltree(void **stack, size_t num_stack_
                 goto fail;
             }
         }
         hash = PL_HashString(details.function);
         hep = PL_HashTableRawLookup(methods, hash, details.function);
         he = *hep;
         if (he) {
             method = (char*) he->key;
-            method_serial = (uint32) NS_PTR_TO_INT32(he->value);
+            method_serial = (uint32_t) NS_PTR_TO_INT32(he->value);
             le = (lfdset_entry *) he;
             if (LFD_TEST(fp->lfd, &le->lfdset)) {
                 /* We already logged an event on fp for this method. */
                 le = NULL;
             }
         } else {
             method = strdup(details.function);
             if (method) {
@@ -1310,17 +1310,17 @@ cfree(void *ptr)
 
 #endif
 
 static const char magic[] = NS_TRACE_MALLOC_MAGIC;
 
 static void
 log_header(int logfd)
 {
-    uint32 ticksPerSec = PR_htonl(PR_TicksPerSecond());
+    uint32_t ticksPerSec = PR_htonl(PR_TicksPerSecond());
     (void) write(logfd, magic, NS_TRACE_MALLOC_MAGIC_SIZE);
     (void) write(logfd, &ticksPerSec, sizeof ticksPerSec);
 }
 
 PR_IMPLEMENT(void)
 NS_TraceMallocStartup(int logfd)
 {
     const char* stack_disable_env;
@@ -1552,17 +1552,17 @@ NS_TraceMallocShutdown(void)
     }
 }
 
 PR_IMPLEMENT(void)
 NS_TraceMallocDisable(void)
 {
     tm_thread *t = tm_get_thread();
     logfile *fp;
-    uint32 sample;
+    uint32_t sample;
 
     /* Robustify in case of duplicate call. */
     PR_ASSERT(tracing_enabled);
     if (tracing_enabled == 0)
         return;
 
     TM_SUPPRESS_TRACING_AND_ENTER_LOCK(t);
     for (fp = logfile_list; fp; fp = fp->next)
@@ -1572,17 +1572,17 @@ NS_TraceMallocDisable(void)
     if (sample == 0)
         ShutdownHooker();
 }
 
 PR_IMPLEMENT(void)
 NS_TraceMallocEnable(void)
 {
     tm_thread *t = tm_get_thread();
-    uint32 sample;
+    uint32_t sample;
 
     TM_SUPPRESS_TRACING_AND_ENTER_LOCK(t);
     sample = ++tracing_enabled;
     TM_EXIT_LOCK_AND_UNSUPPRESS_TRACING(t);
     if (sample == 1)
         StartupHooker();
 }
 
@@ -1686,23 +1686,23 @@ NS_TraceMallocLogTimestamp(const char *c
 
     TM_SUPPRESS_TRACING_AND_ENTER_LOCK(t);
 
     fp = logfp;
     log_byte(fp, TM_EVENT_TIMESTAMP);
 
 #ifdef XP_UNIX
     gettimeofday(&tv, NULL);
-    log_uint32(fp, (uint32) tv.tv_sec);
-    log_uint32(fp, (uint32) tv.tv_usec);
+    log_uint32(fp, (uint32_t) tv.tv_sec);
+    log_uint32(fp, (uint32_t) tv.tv_usec);
 #endif
 #ifdef XP_WIN32
     _ftime(&tb);
-    log_uint32(fp, (uint32) tb.time);
-    log_uint32(fp, (uint32) tb.millitm);
+    log_uint32(fp, (uint32_t) tb.time);
+    log_uint32(fp, (uint32_t) tb.millitm);
 #endif
     log_string(fp, caption);
 
     TM_EXIT_LOCK_AND_UNSUPPRESS_TRACING(t);
 }
 
 static void
 print_stack(FILE *ofp, callsite *site)
@@ -1843,17 +1843,17 @@ MallocCallback(void *ptr, size_t size, u
     TM_SUPPRESS_TRACING_AND_ENTER_LOCK(t);
     tmstats.malloc_calls++;
     if (!ptr) {
         tmstats.malloc_failures++;
     } else {
         if (site) {
             log_event5(logfp, TM_EVENT_MALLOC,
                        site->serial, start, end - start,
-                       (uint32)NS_PTR_TO_INT32(ptr), size);
+                       (uint32_t)NS_PTR_TO_INT32(ptr), size);
         }
         if (get_allocations()) {
             he = PL_HashTableAdd(allocations, ptr, site);
             if (he) {
                 alloc = (allocation*) he;
                 alloc->size = size;
                 alloc->trackfp = NULL;
             }
@@ -1881,17 +1881,17 @@ CallocCallback(void *ptr, size_t count, 
     tmstats.calloc_calls++;
     if (!ptr) {
         tmstats.calloc_failures++;
     } else {
         size *= count;
         if (site) {
             log_event5(logfp, TM_EVENT_CALLOC,
                        site->serial, start, end - start,
-                       (uint32)NS_PTR_TO_INT32(ptr), size);
+                       (uint32_t)NS_PTR_TO_INT32(ptr), size);
         }
         if (get_allocations()) {
             he = PL_HashTableAdd(allocations, ptr, site);
             if (he) {
                 alloc = (allocation*) he;
                 alloc->size = size;
                 alloc->trackfp = NULL;
             }
@@ -1948,19 +1948,19 @@ ReallocCallback(void * oldptr, void *ptr
          * When realloc() fails, the original block is not freed or moved, so
          * we'll leave the allocation entry untouched.
          */
         tmstats.realloc_failures++;
     } else {
         if (site) {
             log_event8(logfp, TM_EVENT_REALLOC,
                        site->serial, start, end - start,
-                       (uint32)NS_PTR_TO_INT32(ptr), size,
+                       (uint32_t)NS_PTR_TO_INT32(ptr), size,
                        oldsite ? oldsite->serial : 0,
-                       (uint32)NS_PTR_TO_INT32(oldptr), oldsize);
+                       (uint32_t)NS_PTR_TO_INT32(oldptr), oldsize);
         }
         if (ptr && allocations) {
             if (ptr != oldptr) {
                 /*
                  * If we're reallocating (not allocating new space by passing
                  * null to realloc) and realloc moved the block, free oldptr.
                  */
                 if (he)
@@ -2016,17 +2016,17 @@ FreeCallback(void * ptr, uint32_t start,
                     alloc = (allocation*) he;
                     if (alloc->trackfp) {
                         fprintf(alloc->trackfp, "\nfree(%p), alloc site %p\n",
                                 (void*) ptr, (void*) site);
                         NS_TraceStack(1, alloc->trackfp);
                     }
                     log_event5(logfp, TM_EVENT_FREE,
                                site->serial, start, end - start,
-                               (uint32)NS_PTR_TO_INT32(ptr), alloc->size);
+                               (uint32_t)NS_PTR_TO_INT32(ptr), alloc->size);
                 }
                 PL_HashTableRawRemove(allocations, hep, he);
             }
         }
     }
     TM_EXIT_LOCK_AND_UNSUPPRESS_TRACING(t);
 }
 
--- a/tools/trace-malloc/lib/nsTraceMallocCallbacks.h
+++ b/tools/trace-malloc/lib/nsTraceMallocCallbacks.h
@@ -4,16 +4,17 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 /* declarations needed by both nsTraceMalloc.c and nsWinTraceMalloc.cpp */
 
 #ifndef NSTRACEMALLOCCALLBACKS_H
 #define NSTRACEMALLOCCALLBACKS_H
 
+#include "mozilla/StandardInteger.h"
 #include <stdlib.h>
 
 #ifdef __cplusplus
 extern "C" {
 #endif
 
 /* Used by backtrace. */
 typedef struct stack_buffer_info {
@@ -23,17 +24,17 @@ typedef struct stack_buffer_info {
 } stack_buffer_info;
 
 typedef struct tm_thread tm_thread;
 struct tm_thread {
     /*
      * This counter suppresses tracing, in case any tracing code needs
      * to malloc.
      */
-    uint32 suppress_tracing;
+    uint32_t suppress_tracing;
 
     /* buffer for backtrace, below */
     stack_buffer_info backtrace_buf;
 };
 
 /* implemented in nsTraceMalloc.c */
 tm_thread * tm_get_thread(void);
 
--- a/tools/trace-malloc/spacetrace.c
+++ b/tools/trace-malloc/spacetrace.c
@@ -114,17 +114,17 @@ ticks2xsec(tmreader * aReader, uint32_t 
     uint64_t bigone;
     uint64_t tmp64;
 
     LL_UI2L(bigone, aResolution);
     LL_UI2L(tmp64, aTicks);
     bigone *= tmp64;
     LL_UI2L(tmp64, aReader->ticksPerSec);
     bigone /= tmp64;
-    return (uint32)bigone;
+    return (uint32_t)bigone;
 }
 
 #define ticks2msec(reader, ticks) ticks2xsec((reader), (ticks), 1000)
 #define ticks2usec(reader, ticks) ticks2xsec((reader), (ticks), 1000000)
 
 /*
 ** initOptions
 **
--- a/tools/trace-malloc/spacetrace.h
+++ b/tools/trace-malloc/spacetrace.h
@@ -12,16 +12,17 @@
 **
 ** SpaceTrace is meant to take the output of trace-malloc and present
 **   a picture of allocations over the run of the application.
 */
 
 /*
 ** Required includes.
 */
+#include "mozilla/StandardInteger.h"
 #include "nspr.h"
 #include "prlock.h"
 #include "prrwlock.h"
 #include "nsTraceMalloc.h"
 #include "tmreader.h"
 #include "formdata.h"
 
 /*
--- a/tools/trace-malloc/tmreader.c
+++ b/tools/trace-malloc/tmreader.c
@@ -19,60 +19,60 @@
 #include "plarena.h"
 
 #include "prnetdb.h"
 #include "nsTraceMalloc.h"
 #include "tmreader.h"
 
 #undef  DEBUG_tmreader
 
-static int accum_byte(FILE *fp, uint32 *uip)
+static int accum_byte(FILE *fp, uint32_t *uip)
 {
     int c = getc(fp);
     if (c == EOF)
         return 0;
     *uip = (*uip << 8) | c;
     return 1;
 }
 
-static int get_uint32(FILE *fp, uint32 *uip)
+static int get_uint32(FILE *fp, uint32_t *uip)
 {
     int c;
-    uint32 ui;
+    uint32_t ui;
 
     c = getc(fp);
     if (c == EOF)
         return 0;
     ui = 0;
     if (c & 0x80) {
         c &= 0x7f;
         if (c & 0x40) {
             c &= 0x3f;
             if (c & 0x20) {
                 c &= 0x1f;
                 if (c & 0x10) {
                     if (!accum_byte(fp, &ui))
                         return 0;
                 } else {
-                    ui = (uint32) c;
+                    ui = (uint32_t) c;
                 }
                 if (!accum_byte(fp, &ui))
                     return 0;
             } else {
-                ui = (uint32) c;
+                ui = (uint32_t) c;
             }
             if (!accum_byte(fp, &ui))
                 return 0;
         } else {
-            ui = (uint32) c;
+            ui = (uint32_t) c;
         }
         if (!accum_byte(fp, &ui))
             return 0;
     } else {
-        ui = (uint32) c;
+        ui = (uint32_t) c;
     }
     *uip = ui;
     return 1;
 }
 
 static char *get_string(FILE *fp)
 {
     char *cp;
@@ -695,17 +695,17 @@ int tmreader_eventloop(tmreader *tmr, co
             site->frees.calls.direct = site->frees.calls.total = 0;
             break;
           }
 
           case TM_EVENT_MALLOC:
           case TM_EVENT_CALLOC:
           case TM_EVENT_REALLOC: {
             tmcallsite *site;
-            uint32 size, oldsize;
+            uint32_t size, oldsize;
             double delta, sqdelta, sqszdelta = 0;
             tmgraphnode *comp, *lib;
             tmmethodnode *meth;
 
             site = tmreader_callsite(tmr, event.serial);
             if (!site) {
                 fprintf(stderr, "%s: no callsite for '%c' (%lu)!\n",
                         tmr->program, event.type, (unsigned long) event.serial);
@@ -751,17 +751,17 @@ int tmreader_eventloop(tmreader *tmr, co
                     }
                 }
             }
             break;
           }
 
           case TM_EVENT_FREE: {
             tmcallsite *site;
-            uint32 size;
+            uint32_t size;
             tmgraphnode *comp, *lib;
             tmmethodnode *meth;
 
             site = tmreader_callsite(tmr, event.serial);
             if (!site) {
                 fprintf(stderr, "%s: no callsite for '%c' (%lu)!\n",
                         tmr->program, event.type, (unsigned long) event.serial);
                 continue;
@@ -792,27 +792,27 @@ int tmreader_eventloop(tmreader *tmr, co
         }
 
         eventhandler(tmr, &event);
     }
 
     return 1;
 }
 
-tmgraphnode *tmreader_library(tmreader *tmr, uint32 serial)
+tmgraphnode *tmreader_library(tmreader *tmr, uint32_t serial)
 {
     const void *key;
     PLHashNumber hash;
 
     key = (const void*) serial;
     hash = hash_serial(key);
     return (tmgraphnode*) *PL_HashTableRawLookup(tmr->libraries, hash, key);
 }
 
-tmgraphnode *tmreader_filename(tmreader *tmr, uint32 serial)
+tmgraphnode *tmreader_filename(tmreader *tmr, uint32_t serial)
 {
     const void *key;
     PLHashNumber hash;
 
     key = (const void*) serial;
     hash = hash_serial(key);
     return (tmgraphnode*) *PL_HashTableRawLookup(tmr->filenames, hash, key);
 }
@@ -820,27 +820,27 @@ tmgraphnode *tmreader_filename(tmreader 
 tmgraphnode *tmreader_component(tmreader *tmr, const char *name)
 {
     PLHashNumber hash;
 
     hash = PL_HashString(name);
     return (tmgraphnode*) *PL_HashTableRawLookup(tmr->components, hash, name);
 }
 
-tmmethodnode *tmreader_method(tmreader *tmr, uint32 serial)
+tmmethodnode *tmreader_method(tmreader *tmr, uint32_t serial)
 {
     const void *key;
     PLHashNumber hash;
 
     key = (const void*) serial;
     hash = hash_serial(key);
     return (tmmethodnode*) *PL_HashTableRawLookup(tmr->methods, hash, key);
 }
 
-tmcallsite *tmreader_callsite(tmreader *tmr, uint32 serial)
+tmcallsite *tmreader_callsite(tmreader *tmr, uint32_t serial)
 {
     const void *key;
     PLHashNumber hash;
 
     key = (const void*) serial;
     hash = hash_serial(key);
     return (tmcallsite*) *PL_HashTableRawLookup(tmr->callsites, hash, key);
 }
--- a/tools/trace-malloc/tmreader.h
+++ b/tools/trace-malloc/tmreader.h
@@ -1,17 +1,16 @@
 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  *
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 #ifndef tmreader_h___
 #define tmreader_h___
 
-#include "prtypes.h"
 #include "plhash.h"
 #include "nsTraceMalloc.h"
 #include "plarena.h"
 
 #ifdef __cplusplus
 extern "C" {
 #endif
 
@@ -22,51 +21,51 @@ typedef struct tmallcounts  tmallcounts;
 typedef struct tmgraphlink  tmgraphlink;
 typedef struct tmgraphedge  tmgraphedge;
 typedef struct tmgraphnode  tmgraphnode;
 typedef struct tmcallsite   tmcallsite;
 typedef struct tmmethodnode tmmethodnode;
 
 struct tmevent {
     char            type;
-    uint32          serial;
+    uint32_t        serial;
     union {
         char        *libname;
         char        *srcname;
         struct {
-            uint32  library;
-            uint32  filename;
-            uint32  linenumber;
-            char    *name;
+            uint32_t  library;
+            uint32_t  filename;
+            uint32_t  linenumber;
+            char      *name;
         } method;
         struct {
-            uint32  parent;
-            uint32  method;
-            uint32  offset;
+            uint32_t  parent;
+            uint32_t  method;
+            uint32_t  offset;
         } site;
         struct {
-            uint32  interval; /* in ticks */
-            uint32  ptr;
-            uint32  size;
-            uint32  oldserial;
-            uint32  oldptr;
-            uint32  oldsize;
-            uint32  cost;     /* in ticks */
+            uint32_t  interval; /* in ticks */
+            uint32_t  ptr;
+            uint32_t  size;
+            uint32_t  oldserial;
+            uint32_t  oldptr;
+            uint32_t  oldsize;
+            uint32_t  cost;     /* in ticks */
         } alloc;
         struct {
             nsTMStats tmstats;
-            uint32  calltree_maxkids_parent;
-            uint32  calltree_maxstack_top;
+            uint32_t  calltree_maxkids_parent;
+            uint32_t  calltree_maxstack_top;
         } stats;
     } u;
 };
 
 struct tmcounts {
-    uint32          direct;     /* things allocated by this node's code */
-    uint32          total;      /* direct + things from all descendents */
+    uint32_t          direct;     /* things allocated by this node's code */
+    uint32_t          total;      /* direct + things from all descendents */
 };
 
 struct tmallcounts {
     tmcounts        bytes;
     tmcounts        calls;
 };
 
 struct tmgraphnode {
@@ -81,23 +80,23 @@ struct tmgraphnode {
     tmallcounts     frees;
     double          sqsum;      /* sum of squared bytes.direct */
     int             sort;       /* sorted index in node table, -1 if no table */
 };
 
 struct tmmethodnode {
     tmgraphnode   graphnode;
     char          *sourcefile;
-    uint32        linenumber;
+    uint32_t      linenumber;
 };
 
 #define tmgraphnode_name(node)  ((char*) (node)->entry.value)
 #define tmmethodnode_name(node)  ((char*) (node)->graphnode.entry.value)
 
-#define tmlibrary_serial(lib)   ((uint32) (lib)->entry.key)
+#define tmlibrary_serial(lib)   ((uint32_t) (lib)->entry.key)
 #define tmcomponent_name(comp)  ((const char*) (comp)->entry.key)
 #define filename_name(hashentry) ((char*)hashentry->value)
 
 /* Half a graphedge, not including per-edge allocation stats. */
 struct tmgraphlink {
     tmgraphlink     *next;      /* next fanning out from or into a node */
     tmgraphnode     *node;      /* the other node (to if OUT, from if IN) */
 };
@@ -121,17 +120,17 @@ struct tmgraphedge {
 #define TM_LINK_TO_EDGE(link,which) ((tmgraphedge*) &(link)[-(which)])
 
 struct tmcallsite {
     PLHashEntry     entry;      /* key is site serial number */
     tmcallsite      *parent;    /* calling site */
     tmcallsite      *siblings;  /* other sites reached from parent */
     tmcallsite      *kids;      /* sites reached from here */
     tmmethodnode    *method;    /* method node in tmr->methods graph */
-    uint32          offset;     /* pc offset from start of method */
+    uint32_t        offset;     /* pc offset from start of method */
     tmallcounts     allocs;
     tmallcounts     frees;
     void            *data;      /* tmreader clients can stick arbitrary
                                  *  data onto a callsite.
                                  */
 };
 
 struct tmreader {
@@ -139,38 +138,38 @@ struct tmreader {
     void            *data;
     PLHashTable     *libraries;
     PLHashTable     *filenames;
     PLHashTable     *components;
     PLHashTable     *methods;
     PLHashTable     *callsites;
     PLArenaPool     arena;
     tmcallsite      calltree_root;
-    uint32          ticksPerSec;
+    uint32_t        ticksPerSec;
 };
 
 typedef void (*tmeventhandler)(tmreader *tmr, tmevent *event);
 
 /* The tmreader constructor and destructor. */
 extern tmreader     *tmreader_new(const char *program, void *data);
 extern void         tmreader_destroy(tmreader *tmr);
 
 /*
  * Return -1 on permanent fatal error, 0 if filename can't be opened or is not
  * a trace-malloc logfile, and 1 on success.
  */
 extern int          tmreader_eventloop(tmreader *tmr, const char *filename,
                                        tmeventhandler eventhandler);
 
 /* Map serial number or name to graphnode or callsite. */
-extern tmgraphnode  *tmreader_library(tmreader *tmr, uint32 serial);
-extern tmgraphnode  *tmreader_filename(tmreader *tmr, uint32 serial);
+extern tmgraphnode  *tmreader_library(tmreader *tmr, uint32_t serial);
+extern tmgraphnode  *tmreader_filename(tmreader *tmr, uint32_t serial);
 extern tmgraphnode  *tmreader_component(tmreader *tmr, const char *name);
-extern tmmethodnode  *tmreader_method(tmreader *tmr, uint32 serial);
-extern tmcallsite   *tmreader_callsite(tmreader *tmr, uint32 serial);
+extern tmmethodnode  *tmreader_method(tmreader *tmr, uint32_t serial);
+extern tmcallsite   *tmreader_callsite(tmreader *tmr, uint32_t serial);
 
 /*
  * Connect node 'from' to node 'to' with an edge, if there isn't one already
  * connecting the nodes.  Add site's allocation stats to the edge only if we
  * create the edge, or if we find that it exists, but that to->low is zero or
  * less than from->low.
  *
  * If the callsite tree already totals allocation costs (tmcounts.total for
--- a/widget/cocoa/TextInputHandler.h
+++ b/widget/cocoa/TextInputHandler.h
@@ -1092,16 +1092,56 @@ public:
    */
   bool KeyPressWasHandled()
   {
     KeyEventState* currentKeyEvent = GetCurrentKeyEvent();
     return currentKeyEvent && currentKeyEvent->mKeyPressHandled;
   }
 
 protected:
+  // Stores the association of device dependent modifier flags with a modifier
+  // keyCode.  Being device dependent, this association may differ from one kind
+  // of hardware to the next.
+  struct ModifierKey
+  {
+    NSUInteger flags;
+    unsigned short keyCode;
+
+    ModifierKey(NSUInteger aFlags, unsigned short aKeyCode) :
+      flags(aFlags), keyCode(aKeyCode)
+    {
+    }
+
+    NSUInteger GetDeviceDependentFlags() const
+    {
+      return (flags & ~NSDeviceIndependentModifierFlagsMask);
+    }
+
+    NSUInteger GetDeviceIndependentFlags() const
+    {
+      return (flags & NSDeviceIndependentModifierFlagsMask);
+    }
+  };
+  typedef nsTArray<ModifierKey> ModifierKeyArray;
+  ModifierKeyArray mModifierKeys;
+
+  /**
+   * GetModifierKeyForNativeKeyCode() returns the stored ModifierKey for
+   * the key.
+   */
+  ModifierKey*
+    GetModifierKeyForNativeKeyCode(unsigned short aKeyCode) const;
+
+  /**
+   * GetModifierKeyForDeviceDependentFlags() returns the stored ModifierKey for
+   * the device dependent flags.
+   */
+  ModifierKey*
+    GetModifierKeyForDeviceDependentFlags(NSUInteger aFlags) const;
+
   /**
    * DispatchKeyEventForFlagsChanged() dispatches keydown event or keyup event
    * for the aNativeEvent.
    *
    * @param aNativeEvent          A native flagschanged event which you want to
    *                              dispatch our key event for.
    * @param aDispatchKeyDown      TRUE if you want to dispatch a keydown event.
    *                              Otherwise, i.e., to dispatch keyup event,
--- a/widget/cocoa/TextInputHandler.mm
+++ b/widget/cocoa/TextInputHandler.mm
@@ -1552,64 +1552,279 @@ TextInputHandler::HandleFlagsChanged(NSE
        "widget has been already destroyed", this));
     return;
   }
 
   nsRefPtr<nsChildView> kungFuDeathGrip(mWidget);
 
   PR_LOG(gLog, PR_LOG_ALWAYS,
     ("%p TextInputHandler::HandleFlagsChanged, aNativeEvent=%p, "
-     "type=%s, keyCode=%s (0x%X), sLastModifierState=0x%X, IsIMEComposing()=%s",
+     "type=%s, keyCode=%s (0x%X), modifierFlags=0x%08X, "
+     "sLastModifierState=0x%08X, IsIMEComposing()=%s",
      this, aNativeEvent, GetNativeKeyEventType(aNativeEvent),
      GetKeyNameForNativeKeyCode([aNativeEvent keyCode]), [aNativeEvent keyCode],
-     sLastModifierState, TrueOrFalse(IsIMEComposing())));
-
-  // CapsLock state and other modifier states are different:
-  // CapsLock state does not revert when the CapsLock key goes up, as the
-  // modifier state does for other modifier keys on key up.
-  if ([aNativeEvent keyCode] == kVK_CapsLock) {
-    // Fire key down event for caps lock.
-    DispatchKeyEventForFlagsChanged(aNativeEvent, true);
-    if (Destroyed()) {
-      return;
+     [aNativeEvent modifierFlags], sLastModifierState,
+     TrueOrFalse(IsIMEComposing())));
+
+  MOZ_ASSERT([aNativeEvent type] == NSFlagsChanged);
+
+  NSUInteger diff = [aNativeEvent modifierFlags] ^ sLastModifierState;
+  // Device dependent flags for left-control key, both shift keys, both command
+  // keys and both option keys have been defined in Next's SDK.  But we
+  // shouldn't use it directly as far as possible since Cocoa SDK doesn't
+  // define them.  Fortunately, we need them only when we dispatch keyup
+  // events.  So, we can usually know the actual relation between keyCode and
+  // device dependent flags.  However, we need to remove following flags first
+  // since the differences don't indicate modifier key state.
+  // NX_STYLUSPROXIMITYMASK: Probably used for pen like device.
+  // kCGEventFlagMaskNonCoalesced (= NX_NONCOALSESCEDMASK): See the document for
+  // Quartz Event Services.
+  diff &= ~(NX_STYLUSPROXIMITYMASK | kCGEventFlagMaskNonCoalesced);
+
+  switch ([aNativeEvent keyCode]) {
+    // CapsLock state and other modifier states are different:
+    // CapsLock state does not revert when the CapsLock key goes up, as the
+    // modifier state does for other modifier keys on key up.
+    case kVK_CapsLock: {
+      // Fire key down event for caps lock.
+      DispatchKeyEventForFlagsChanged(aNativeEvent, true);
+      // XXX should we fire keyup event too? The keyup event for CapsLock key
+      // is never dispatched on Gecko.
+      // XXX WebKit dispatches keydown event when CapsLock is locked, otherwise,
+      // keyup event.  If we do so, we cannot keep the consistency with other
+      // platform's behavior...
+      break;
+    }
+
+    // If the event is caused by pressing or releasing a modifier key, just
+    // dispatch the key's event.
+    case kVK_Shift:
+    case kVK_RightShift:
+    case kVK_Command:
+    case kVK_RightCommand:
+    case kVK_Control:
+    case kVK_RightControl:
+    case kVK_Option:
+    case kVK_RightOption:
+    case kVK_Help: {
+      // We assume that at most one modifier is changed per event if the event
+      // is caused by pressing or releasing a modifier key.
+      bool isKeyDown = ([aNativeEvent modifierFlags] & diff) != 0;
+      DispatchKeyEventForFlagsChanged(aNativeEvent, isKeyDown);
+      if (isKeyDown && ((diff & ~NSDeviceIndependentModifierFlagsMask) != 0)) {
+        unsigned short keyCode = [aNativeEvent keyCode];
+        ModifierKey* modifierKey = GetModifierKeyForDeviceDependentFlags(diff);
+        if (modifierKey) {
+          MOZ_ASSERT(modifierKey->keyCode == keyCode);
+        } else {
+          mModifierKeys.AppendElement(ModifierKey(diff, keyCode));
+        }
+      }
+      break;
     }
-    // XXX should we fire keyup event too? The keyup event for CapsLock key
-    // is never dispatched on Gecko.
-  } else if ([aNativeEvent type] == NSFlagsChanged) {
-    // Fire key up/down events for the modifier keys (shift, alt, ctrl, command)
-    NSUInteger modifiers =
-      [aNativeEvent modifierFlags] & NSDeviceIndependentModifierFlagsMask;
-    const NSUInteger kModifierMaskTable[] =
-      { NSShiftKeyMask, NSControlKeyMask,
-        NSAlternateKeyMask, NSCommandKeyMask };
-    const uint32_t kModifierCount = ArrayLength(kModifierMaskTable);
-
-    for (uint32_t i = 0; i < kModifierCount; i++) {
-      NSUInteger modifierBit = kModifierMaskTable[i];
-      if ((modifiers & modifierBit) != (sLastModifierState & modifierBit)) {
-        bool isKeyDown = ((modifiers & modifierBit) != 0);
-        DispatchKeyEventForFlagsChanged(aNativeEvent, isKeyDown);
+
+    // Currently we don't support Fn key since other browsers don't dispatch
+    // events for it and we don't have keyCode for this key.
+    // It should be supported when we implement .key and .char.
+    case kVK_Function:
+      break;
+
+    // If the event is caused by something else than pressing or releasing a
+    // single modifier key (for example by the app having been deactivated
+    // using command-tab), use the modifiers themselves to determine which
+    // key's event to dispatch, and whether it's a keyup or keydown event.
+    // In all cases we assume one or more modifiers are being deactivated
+    // (never activated) -- otherwise we'd have received one or more events
+    // corresponding to a single modifier key being pressed.
+    default: {
+      NSUInteger modifiers = sLastModifierState;
+      for (int32_t bit = 0; bit < 32; ++bit) {
+        NSUInteger flag = 1 << bit;
+        if (!(diff & flag)) {
+          continue;
+        }
+
+        unsigned short keyCode = 0;
+        bool dispatchKeyDown = false;
+        if (flag & NSDeviceIndependentModifierFlagsMask) {
+          switch (flag) {
+            case NSAlphaShiftKeyMask:
+              keyCode = kVK_CapsLock;
+              dispatchKeyDown = true;
+              break;
+            case NSNumericPadKeyMask:
+              keyCode = kVK_ANSI_KeypadClear;
+              dispatchKeyDown = true;
+              break;
+            case NSHelpKeyMask:
+              // NSHelpKeyMask change here must be a deactivation.
+              MOZ_ASSERT(!(flag & [aNativeEvent modifierFlags]));
+              keyCode = kVK_Help;
+              break;
+            case NSFunctionKeyMask:
+              // NSFunctionKeyMask change here must be a deactivation.
+              MOZ_ASSERT(!(flag & [aNativeEvent modifierFlags]));
+              // We don't dispatch function key event for now.
+              continue;
+            default:
+              // The other cases (NSShiftKeyMask, NSControlKeyMask,
+              // NSAlternateKeyMask and NSCommandKeyMask) are handled by the
+              // other branch of the if statement, below (which handles device
+              // dependent flags).
+              continue;
+          }
+        } else {
+          // Any modifier change here must be a deactivation.
+          MOZ_ASSERT(!(flag & [aNativeEvent modifierFlags]));
+          ModifierKey* modifierKey =
+            GetModifierKeyForDeviceDependentFlags(flag);
+          if (!modifierKey) {
+            continue;
+          }
+          keyCode = modifierKey->keyCode;
+        }
+
+        // Remove flags
+        modifiers &= ~flag;
+        switch (keyCode) {
+          case kVK_Shift: {
+            ModifierKey* modifierKey =
+              GetModifierKeyForNativeKeyCode(kVK_RightShift);
+            if (!modifierKey ||
+                !(modifiers & modifierKey->GetDeviceDependentFlags())) {
+              modifiers &= ~NSShiftKeyMask;
+            }
+            break;
+          }
+          case kVK_RightShift: {
+            ModifierKey* modifierKey =
+              GetModifierKeyForNativeKeyCode(kVK_Shift);
+            if (!modifierKey ||
+                !(modifiers & modifierKey->GetDeviceDependentFlags())) {
+              modifiers &= ~NSShiftKeyMask;
+            }
+            break;
+          }
+          case kVK_Command: {
+            ModifierKey* modifierKey =
+              GetModifierKeyForNativeKeyCode(kVK_RightCommand);
+            if (!modifierKey ||
+                !(modifiers & modifierKey->GetDeviceDependentFlags())) {
+              modifiers &= ~NSCommandKeyMask;
+            }
+            break;
+          }
+          case kVK_RightCommand: {
+            ModifierKey* modifierKey =
+              GetModifierKeyForNativeKeyCode(kVK_Command);
+            if (!modifierKey ||
+                !(modifiers & modifierKey->GetDeviceDependentFlags())) {
+              modifiers &= ~NSCommandKeyMask;
+            }
+            break;
+          }
+          case kVK_Control: {
+            ModifierKey* modifierKey =
+              GetModifierKeyForNativeKeyCode(kVK_RightControl);
+            if (!modifierKey ||
+                !(modifiers & modifierKey->GetDeviceDependentFlags())) {
+              modifiers &= ~NSControlKeyMask;
+            }
+            break;
+          }
+          case kVK_RightControl: {
+            ModifierKey* modifierKey =
+              GetModifierKeyForNativeKeyCode(kVK_Control);
+            if (!modifierKey ||
+                !(modifiers & modifierKey->GetDeviceDependentFlags())) {
+              modifiers &= ~NSControlKeyMask;
+            }
+            break;
+          }
+          case kVK_Option: {
+            ModifierKey* modifierKey =
+              GetModifierKeyForNativeKeyCode(kVK_RightOption);
+            if (!modifierKey ||
+                !(modifiers & modifierKey->GetDeviceDependentFlags())) {
+              modifiers &= ~NSAlternateKeyMask;
+            }
+            break;
+          }
+          case kVK_RightOption: {
+            ModifierKey* modifierKey =
+              GetModifierKeyForNativeKeyCode(kVK_Option);
+            if (!modifierKey ||
+                !(modifiers & modifierKey->GetDeviceDependentFlags())) {
+              modifiers &= ~NSAlternateKeyMask;
+            }
+            break;
+          }
+          case kVK_Help:
+            modifiers &= ~NSHelpKeyMask;
+            break;
+          default:
+            break;
+        }
+
+        NSEvent* event =
+          [NSEvent keyEventWithType:NSFlagsChanged
+                           location:[aNativeEvent locationInWindow]
+                      modifierFlags:modifiers
+                          timestamp:[aNativeEvent timestamp]
+                       windowNumber:[aNativeEvent windowNumber]
+                            context:[aNativeEvent context]
+                         characters:nil
+        charactersIgnoringModifiers:nil
+                          isARepeat:NO
+                            keyCode:keyCode];
+        DispatchKeyEventForFlagsChanged(event, dispatchKeyDown);
         if (Destroyed()) {
-          return;
+          break;
         }
 
         // Stop if focus has changed.
         // Check to see if mView is still the first responder.
         if (![mView isFirstResponder]) {
           break;
         }
+
       }
+      break;
     }
-
-    sLastModifierState = modifiers;
   }
 
+  // Be aware, the widget may have been destroyed.
+  sLastModifierState = [aNativeEvent modifierFlags];
+
   NS_OBJC_END_TRY_ABORT_BLOCK;
 }
 
+TextInputHandler::ModifierKey*
+TextInputHandler::GetModifierKeyForNativeKeyCode(unsigned short aKeyCode) const
+{
+  for (ModifierKeyArray::index_type i = 0; i < mModifierKeys.Length(); ++i) {
+    if (mModifierKeys[i].keyCode == aKeyCode) {
+      return &((ModifierKey&)mModifierKeys[i]);
+    }
+  }
+  return nullptr;
+}
+
+TextInputHandler::ModifierKey*
+TextInputHandler::GetModifierKeyForDeviceDependentFlags(NSUInteger aFlags) const
+{
+  for (ModifierKeyArray::index_type i = 0; i < mModifierKeys.Length(); ++i) {
+    if (mModifierKeys[i].GetDeviceDependentFlags() ==
+          (aFlags & ~NSDeviceIndependentModifierFlagsMask)) {
+      return &((ModifierKey&)mModifierKeys[i]);
+    }
+  }
+  return nullptr;
+}
+
 void
 TextInputHandler::DispatchKeyEventForFlagsChanged(NSEvent* aNativeEvent,
                                                   bool aDispatchKeyDown)
 {
   NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
 
   if (Destroyed()) {
     return;
@@ -3768,24 +3983,24 @@ TextInputHandlerBase::SynthesizeNativeKe
                         uint32_t aModifierFlags,
                         const nsAString& aCharacters,
                         const nsAString& aUnmodifiedCharacters)
 {
   NS_OBJC_BEGIN_TRY_ABORT_BLOCK_NSRESULT;
 
   static const uint32_t sModifierFlagMap[][2] = {
     { nsIWidget::CAPS_LOCK,       NSAlphaShiftKeyMask },
-    { nsIWidget::SHIFT_L,         NSShiftKeyMask },
-    { nsIWidget::SHIFT_R,         NSShiftKeyMask },
-    { nsIWidget::CTRL_L,          NSControlKeyMask },
-    { nsIWidget::CTRL_R,          NSControlKeyMask },
-    { nsIWidget::ALT_L,           NSAlternateKeyMask },
-    { nsIWidget::ALT_R,           NSAlternateKeyMask },
-    { nsIWidget::COMMAND_L,       NSCommandKeyMask },
-    { nsIWidget::COMMAND_R,       NSCommandKeyMask },
+    { nsIWidget::SHIFT_L,         NSShiftKeyMask      | 0x0002 },
+    { nsIWidget::SHIFT_R,         NSShiftKeyMask      | 0x0004 },
+    { nsIWidget::CTRL_L,          NSControlKeyMask    | 0x0001 },
+    { nsIWidget::CTRL_R,          NSControlKeyMask    | 0x2000 },
+    { nsIWidget::ALT_L,           NSAlternateKeyMask  | 0x0020 },
+    { nsIWidget::ALT_R,           NSAlternateKeyMask  | 0x0040 },
+    { nsIWidget::COMMAND_L,       NSCommandKeyMask    | 0x0008 },
+    { nsIWidget::COMMAND_R,       NSCommandKeyMask    | 0x0010 },
     { nsIWidget::NUMERIC_KEY_PAD, NSNumericPadKeyMask },
     { nsIWidget::HELP,            NSHelpKeyMask },
     { nsIWidget::FUNCTION,        NSFunctionKeyMask }
   };
 
   uint32_t modifierFlags = 0;
   for (uint32_t i = 0; i < ArrayLength(sModifierFlagMap); ++i) {
     if (aModifierFlags & sModifierFlagMap[i][0]) {
@@ -3849,16 +4064,17 @@ TextInputHandlerBase::IsSpecialGeckoKey(
     case kVK_Command:
     case kVK_RightCommand:
     case kVK_CapsLock:
     case kVK_Control:
     case kVK_RightControl:
     case kVK_Option:
     case kVK_RightOption:
     case kVK_ANSI_KeypadClear:
+    case kVK_Function:
 
     // function keys
     case kVK_F1:
     case kVK_F2:
     case kVK_F3:
     case kVK_F4:
     case kVK_F5:
     case kVK_F6:
@@ -3924,12 +4140,13 @@ TextInputHandlerBase::IsModifierKey(UInt
     case kVK_RightCommand:
     case kVK_Command:
     case kVK_Shift:
     case kVK_Option:
     case kVK_Control:
     case kVK_RightShift:
     case kVK_RightOption:
     case kVK_RightControl:
+    case kVK_Function:
       return true;
   }
   return false;
 }
--- a/widget/cocoa/nsCocoaFeatures.h
+++ b/widget/cocoa/nsCocoaFeatures.h
@@ -1,16 +1,17 @@
 /* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef nsCocoaFeatures_h_
 #define nsCocoaFeatures_h_
 
+#include "mozilla/StandardInteger.h"
 #include "prtypes.h"
 
 class nsCocoaFeatures {
 public:
   static int32_t OSXVersion();
   static bool OnSnowLeopardOrLater();
   static bool OnLionOrLater();
   static bool SupportCoreAnimationPlugins();
--- a/widget/windows/nsWindow.cpp
+++ b/widget/windows/nsWindow.cpp
@@ -1079,16 +1079,23 @@ NS_METHOD nsWindow::Show(bool bState)
         sDropShadowEnabled = false;
       }
     } else {
       if (!sDropShadowEnabled) {
         ::SetClassLongA(mWnd, GCL_STYLE, CS_DROPSHADOW);
         sDropShadowEnabled = true;
       }
     }
+
+    // WS_EX_COMPOSITED conflicts with the WS_EX_LAYERED style and causes
+    // some popup menus to become invisible.
+    LONG_PTR exStyle = ::GetWindowLongPtrW(mWnd, GWL_EXSTYLE);
+    if (exStyle & WS_EX_LAYERED) {
+      ::SetWindowLongPtrW(mWnd, GWL_EXSTYLE, exStyle & ~WS_EX_COMPOSITED);
+    }
   }
 
   bool syncInvalidate = false;
 
   bool wasVisible = mIsVisible;
   // Set the status now so that anyone asking during ShowWindow or
   // SetWindowPos would get the correct answer.
   mIsVisible = bState;
--- a/xpcom/base/NSPRFormatTime.h
+++ b/xpcom/base/NSPRFormatTime.h
@@ -1,9 +1,12 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 // Temporarily undefine to build successfully with NO_NSPR_10_SUPPORT
+#ifdef prtime_h___
+#error NSPRFormatTime.h must be included before any header that includes prtime.h
+#endif
 #undef NO_NSPR_10_SUPPORT
 #include "prtime.h"
 #define NO_NSPR_10_SUPPORT
--- a/xpcom/glue/nsCRTGlue.cpp
+++ b/xpcom/glue/nsCRTGlue.cpp
@@ -247,17 +247,17 @@ static const char table[] = {
   '4','5','6','7','8','9'
 };
 
 void NS_MakeRandomString(char *aBuf, int32_t aBufLen)
 {
   // turn PR_Now() into milliseconds since epoch
   // and salt rand with that.
   double fpTime = double(PR_Now());
-  srand((uint)(fpTime * 1e-6 + 0.5));   // use 1e-6, granularity of PR_Now() on the mac is seconds
+  srand((unsigned int)(fpTime * 1e-6 + 0.5));   // use 1e-6, granularity of PR_Now() on the mac is seconds
 
   int32_t i;
   for (i=0;i<aBufLen;i++) {
     *aBuf++ = table[rand()%TABLE_SIZE];
   }
   *aBuf = 0;
 }
 
--- a/xpcom/reflect/xptcall/src/md/os2/xptcstubs_gcc_x86_os2.cpp
+++ b/xpcom/reflect/xptcall/src/md/os2/xptcstubs_gcc_x86_os2.cpp
@@ -7,17 +7,17 @@
 
 #include "xptcprivate.h"
 #include "xptiprivate.h"
 #include "xptc_gcc_x86_unix.h"
 
 extern "C" {
 static nsresult ATTRIBUTE_USED
 __attribute__ ((regparm (3)))
-PrepareAndDispatch(uint32 methodIndex, nsXPTCStubBase* self, uint32_t* args)
+PrepareAndDispatch(uint32_t methodIndex, nsXPTCStubBase* self, uint32_t* args)
 {
 #define PARAM_BUFFER_COUNT     16
 
     nsXPTCMiniVariant paramBuffer[PARAM_BUFFER_COUNT];
     nsXPTCMiniVariant* dispatchParams = NULL;
     const nsXPTMethodInfo* info;
     uint8_t paramCount;
     uint8_t i;
--- a/xpcom/reflect/xptcall/src/md/unix/xptcinvoke_amd64_openbsd.cpp
+++ b/xpcom/reflect/xptcall/src/md/unix/xptcinvoke_amd64_openbsd.cpp
@@ -19,17 +19,17 @@ static inline void
 invoke_count_words(uint32_t paramCount, nsXPTCVariant * s,
                    uint32_t & nr_gpr, uint32_t & nr_fpr, uint32_t & nr_stack)
 {
     nr_gpr = 1; // skip one GP register for 'that'
     nr_fpr = 0;
     nr_stack = 0;
 
     /* Compute number of eightbytes of class MEMORY.  */
-    for (uint32 i = 0; i < paramCount; i++, s++) {
+    for (uint32_t i = 0; i < paramCount; i++, s++) {
         if (!s->IsPtrData()
             && (s->type == nsXPTType::T_FLOAT || s->type == nsXPTType::T_DOUBLE)) {
             if (nr_fpr < FPR_COUNT)
                 nr_fpr++;
             else
                 nr_stack++;
         }
         else {
@@ -44,17 +44,17 @@ invoke_count_words(uint32_t paramCount, 
 static void
 invoke_copy_to_stack(uint64_t * d, uint32_t paramCount, nsXPTCVariant * s,
                      uint64_t * gpregs, double * fpregs)
 {
     uint32_t nr_gpr = 1; // skip one GP register for 'that'
     uint32_t nr_fpr = 0;
     uint64_t value;
 
-    for (uint32 i = 0; i < paramCount; i++, s++) {
+    for (uint32_t i = 0; i < paramCount; i++, s++) {
         if (s->IsPtrData())
             value = (uint64_t) s->ptr;
         else {
             switch (s->type) {
             case nsXPTType::T_FLOAT:                                break;
             case nsXPTType::T_DOUBLE:                               break;
             case nsXPTType::T_I8:     value = s->val.i8;            break;
             case nsXPTType::T_I16:    value = s->val.i16;           break;
--- a/xpcom/reflect/xptcall/src/md/unix/xptcinvoke_mips.cpp
+++ b/xpcom/reflect/xptcall/src/md/unix/xptcinvoke_mips.cpp
@@ -8,17 +8,17 @@
 /* This code is for MIPS using the O32 ABI. */
 
 /* Platform specific code to invoke XPCOM methods on native objects */
 
 #include "xptcprivate.h"
 
 #include "mozilla/StandardInteger.h"
 
-extern "C" uint32
+extern "C" uint32_t
 invoke_count_words(uint32_t paramCount, nsXPTCVariant* s)
 {
     // Count a word for a0 even though it's never stored or loaded
     // We do this only for alignment of register pairs.
     uint32_t result = 1;
     for (uint32_t i = 0; i < paramCount; i++, result++, s++)
     {
         if (s->IsPtrData())
--- a/xpcom/reflect/xptcall/src/md/unix/xptcinvoke_mips64.cpp
+++ b/xpcom/reflect/xptcall/src/md/unix/xptcinvoke_mips64.cpp
@@ -6,17 +6,17 @@
 /* Platform specific code to invoke XPCOM methods on native objects */
 
 #include "xptcprivate.h"
 
 #if (_MIPS_SIM != _ABIN32)
 #error "This code is for MIPS N32 only"
 #endif
 
-extern "C" uint32
+extern "C" uint32_t
 invoke_count_words(uint32_t paramCount, nsXPTCVariant* s)
 {
     return paramCount;
 }
 
 extern "C" void
 invoke_copy_to_stack(uint64_t* d, uint32_t paramCount,
                      nsXPTCVariant* s, uint64_t *regs)
--- a/xpcom/reflect/xptcall/src/md/unix/xptcinvoke_nto_shle.cpp
+++ b/xpcom/reflect/xptcall/src/md/unix/xptcinvoke_nto_shle.cpp
@@ -93,17 +93,17 @@ XPTC_InvokeByIndex(nsISupports* that, ui
 	   all the hard work will be done by copy_to_stack above.  We pass to it
 	   a chunk of memory, the top of which will be copied to registers r5 to r7
 	   and fr4 to fr11 before calling the target function.
 	*/
 
  __asm__ __volatile__(
     /* Make space for parameters to be passed to the method.  Assume worst case 
 	   8 bytes per parameter.  Also leave space for 3 longs and 8 floats that
-	   will be put into registers.  The worst case is all int64 parameters
+	   will be put into registers.  The worst case is all int64_t parameters
 	   and even in this case 8 bytes are passed in registers so we can
 	   deduct this from our allocation.
 	*/
 	"mov.l	@(8,r14), r4 \n\t"	// copy_to_stack paramCount parameter
 	"mov	r4, r6 \n\t"
 	"mov	#3, r1 \n\t"
 	"shld	r1, r6 \n\t"
 	"add	#36, r6 \n\t"		// Space for 3 longs, 8 floats - 8 bytes
--- a/xpcom/reflect/xptcall/src/md/unix/xptcinvoke_pa32.cpp
+++ b/xpcom/reflect/xptcall/src/md/unix/xptcinvoke_pa32.cpp
@@ -90,35 +90,35 @@ invoke_copy_to_stack(uint32_t* d,
     case nsXPTType::T_I64   :
     case nsXPTType::T_U64   :
       if (regwords & 1)
       {
         /* align on double word boundary */
         --dest;
         ++regwords;
       }
-      *((uint32*) dest) = ((DU *) source)->lo;
-      *((uint32*) --dest) = ((DU *) source)->hi;
+      *((uint32_t*) dest) = ((DU *) source)->lo;
+      *((uint32_t*) --dest) = ((DU *) source)->hi;
       /* big endian - hi word in low addr */
       regwords += 2;
       continue;
     case nsXPTType::T_DOUBLE :
       if (regwords & 1)
       {
         /* align on double word boundary */
         --dest;
         ++regwords;
       }
       switch (regwords) /* load double precision float register */
       {
       case 2:
         floatflags |= 1;
       }
-      *((uint32*) dest) = ((DU *) source)->lo;
-      *((uint32*) --dest) = ((DU *) source)->hi;
+      *((uint32_t*) dest) = ((DU *) source)->lo;
+      *((uint32_t*) --dest) = ((DU *) source)->hi;
       /* big endian - hi word in low addr */
       regwords += 2;
       continue;
     case nsXPTType::T_FLOAT :
       switch (regwords) /* load single precision float register */
       {
       case 1:
         floatflags |= 2;
--- a/xpcom/reflect/xptcall/src/md/unix/xptcinvoke_ppc64_linux.cpp
+++ b/xpcom/reflect/xptcall/src/md/unix/xptcinvoke_ppc64_linux.cpp
@@ -36,17 +36,17 @@ extern "C" void
 invoke_copy_to_stack(uint64_t* gpregs,
                      double* fpregs,
                      uint32_t paramCount,
                      nsXPTCVariant* s, 
                      uint64_t* d)
 {
     uint64_t tempu64;
 
-    for(uint32 i = 0; i < paramCount; i++, s++) {
+    for(uint32_t i = 0; i < paramCount; i++, s++) {
         if(s->IsPtrData())
             tempu64 = (uint64_t) s->ptr;
         else {
             switch(s->type) {
             case nsXPTType::T_FLOAT:                                  break;
             case nsXPTType::T_DOUBLE:                                 break;
             case nsXPTType::T_I8:     tempu64 = s->val.i8;            break;
             case nsXPTType::T_I16:    tempu64 = s->val.i16;           break;
--- a/xpcom/reflect/xptcall/src/md/unix/xptcinvoke_ppc_aix.cpp
+++ b/xpcom/reflect/xptcall/src/md/unix/xptcinvoke_ppc_aix.cpp
@@ -20,55 +20,55 @@ invoke_copy_to_stack(uint32_t* d, uint32
     we're trying to populate.
 */
     uint32_t *l_d = d;
     nsXPTCVariant *l_s = s;
     uint32_t l_paramCount = paramCount, fpCount = 0;
     double *l_fprData = fprData;
 
     typedef struct {
-        uint32 hi;
-        uint32 lo;
+        uint32_t hi;
+        uint32_t lo;
     } DU;               // have to move 64 bit entities as 32 bit halves since
                         // stack slots are not guaranteed 16 byte aligned
 
-    for(uint32 i = 0; i < l_paramCount; i++, l_d++, l_s++)
+    for(uint32_t i = 0; i < l_paramCount; i++, l_d++, l_s++)
     {
         if(l_s->IsPtrData())
         {
             *((void**)l_d) = l_s->ptr;
             continue;
         }
         switch(l_s->type)
         {
-        case nsXPTType::T_I8     : *((int32*)  l_d) = l_s->val.i8;          break;
-        case nsXPTType::T_I16    : *((int32*)  l_d) = l_s->val.i16;         break;
-        case nsXPTType::T_I32    : *((int32*)  l_d) = l_s->val.i32;         break;
+        case nsXPTType::T_I8     : *((int32_t*)  l_d) = l_s->val.i8;          break;
+        case nsXPTType::T_I16    : *((int32_t*)  l_d) = l_s->val.i16;         break;
+        case nsXPTType::T_I32    : *((int32_t*)  l_d) = l_s->val.i32;         break;
         case nsXPTType::T_I64    : 
         case nsXPTType::T_U64    :
-            *((uint32*) l_d++) = ((DU *)l_s)->hi;
-            *((uint32*) l_d) = ((DU *)l_s)->lo;
+            *((uint32_t*) l_d++) = ((DU *)l_s)->hi;
+            *((uint32_t*) l_d) = ((DU *)l_s)->lo;
             break;
         case nsXPTType::T_DOUBLE :
-            *((uint32*) l_d++) = ((DU *)l_s)->hi;
-            *((uint32*) l_d) = ((DU *)l_s)->lo;
+            *((uint32_t*) l_d++) = ((DU *)l_s)->hi;
+            *((uint32_t*) l_d) = ((DU *)l_s)->lo;
             if(fpCount < 13)
                 l_fprData[fpCount++] = l_s->val.d;
             break;
-        case nsXPTType::T_U8     : *((uint32*) l_d) = l_s->val.u8;          break;
-        case nsXPTType::T_U16    : *((uint32*) l_d) = l_s->val.u16;         break;
-        case nsXPTType::T_U32    : *((uint32*) l_d) = l_s->val.u32;         break;
+        case nsXPTType::T_U8     : *((uint32_t*) l_d) = l_s->val.u8;          break;
+        case nsXPTType::T_U16    : *((uint32_t*) l_d) = l_s->val.u16;         break;
+        case nsXPTType::T_U32    : *((uint32_t*) l_d) = l_s->val.u32;         break;
         case nsXPTType::T_FLOAT  :
             *((float*)  l_d) = l_s->val.f;
             if(fpCount < 13)
                 l_fprData[fpCount++] = l_s->val.f;
             break;
-        case nsXPTType::T_BOOL   : *((uint32*) l_d) = l_s->val.b;           break;
-        case nsXPTType::T_CHAR   : *((uint32*) l_d) = l_s->val.c;           break;
-        case nsXPTType::T_WCHAR  : *((int32*)  l_d) = l_s->val.wc;          break;
+        case nsXPTType::T_BOOL   : *((uint32_t*) l_d) = l_s->val.b;           break;
+        case nsXPTType::T_CHAR   : *((uint32_t*) l_d) = l_s->val.c;           break;
+        case nsXPTType::T_WCHAR  : *((int32_t*)  l_d) = l_s->val.wc;          break;
         default:
             // all the others are plain pointer types
             *((void**)l_d) = l_s->val.p;
             break;
         }
     }
 }
 
--- a/xpcom/reflect/xptcall/src/md/unix/xptcinvoke_ppc_linux.cpp
+++ b/xpcom/reflect/xptcall/src/md/unix/xptcinvoke_ppc_linux.cpp
@@ -39,17 +39,17 @@ invoke_copy_to_stack(uint32_t* d,
 {
     uint32_t gpr = 1; // skip one GP reg for 'that'
 #ifndef __NO_FPRS__
     uint32_t fpr = 0;
 #endif
     uint32_t tempu32;
     uint64_t tempu64;
     
-    for(uint32 i = 0; i < paramCount; i++, s++) {
+    for(uint32_t i = 0; i < paramCount; i++, s++) {
         if(s->IsPtrData())
             tempu32 = (uint32_t) s->ptr;
         else {
             switch(s->type) {
             case nsXPTType::T_FLOAT:                                  break;
             case nsXPTType::T_DOUBLE:                                 break;
             case nsXPTType::T_I8:     tempu32 = s->val.i8;            break;
             case nsXPTType::T_I16:    tempu32 = s->val.i16;           break;
--- a/xpcom/reflect/xptcall/src/md/unix/xptcinvoke_ppc_netbsd.cpp
+++ b/xpcom/reflect/xptcall/src/md/unix/xptcinvoke_ppc_netbsd.cpp
@@ -35,17 +35,17 @@ invoke_copy_to_stack(uint32_t* d,
                      uint32_t* gpregs,
                      double* fpregs)
 {
     uint32_t gpr = 1; // skip one GP reg for 'that'
     uint32_t fpr = 0;
     uint32_t tempu32;
     uint64_t tempu64;
     
-    for(uint32 i = 0; i < paramCount; i++, s++) {
+    for(uint32_t i = 0; i < paramCount; i++, s++) {
         if(s->IsPtrData())
             tempu32 = (uint32_t) s->ptr;
         else {
             switch(s->type) {
             case nsXPTType::T_FLOAT:                                  break;
             case nsXPTType::T_DOUBLE:                                 break;
             case nsXPTType::T_I8:     tempu32 = s->val.i8;            break;
             case nsXPTType::T_I16:    tempu32 = s->val.i16;           break;
--- a/xpcom/reflect/xptcall/src/md/unix/xptcinvoke_ppc_openbsd.cpp
+++ b/xpcom/reflect/xptcall/src/md/unix/xptcinvoke_ppc_openbsd.cpp
@@ -35,17 +35,17 @@ invoke_copy_to_stack(uint32_t* d,
                      uint32_t* gpregs,
                      double* fpregs)
 {
     uint32_t gpr = 1; // skip one GP reg for 'that'
     uint32_t fpr = 0;
     uint32_t tempu32;
     uint64_t tempu64;
     
-    for(uint32 i = 0; i < paramCount; i++, s++) {
+    for(uint32_t i = 0; i < paramCount; i++, s++) {
         if(s->IsPtrData())
             tempu32 = (uint32_t) s->ptr;
         else {
             switch(s->type) {
             case nsXPTType::T_FLOAT:                                  break;
             case nsXPTType::T_DOUBLE:                                 break;
             case nsXPTType::T_I8:     tempu32 = s->val.i8;            break;
             case nsXPTType::T_I16:    tempu32 = s->val.i16;           break;
--- a/xpcom/reflect/xptcall/src/md/unix/xptcinvoke_ppc_rhapsody.cpp
+++ b/xpcom/reflect/xptcall/src/md/unix/xptcinvoke_ppc_rhapsody.cpp
@@ -2,17 +2,17 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 /* Platform specific code to invoke XPCOM methods on native objects */
 
 #include "xptcprivate.h"
 
-extern "C" uint32
+extern "C" uint32_t
 invoke_count_words(uint32_t paramCount, nsXPTCVariant* s)
 {
     uint32_t result = 0;
     /*    fprintf(stderr,"invoke_count_words(%d,%p)\n",paramCount, s);*/
 
     for(uint32_t i = 0; i < paramCount; i++, s++)
     {
         if(s->IsPtrData())
--- a/xpcom/reflect/xptcall/src/md/unix/xptcinvoke_sparc_netbsd.cpp
+++ b/xpcom/reflect/xptcall/src/md/unix/xptcinvoke_sparc_netbsd.cpp
@@ -71,53 +71,53 @@ invoke_count_words(uint32_t paramCount, 
 extern "C" uint32_t
 invoke_copy_to_stack(uint32_t* d, uint32_t paramCount, nsXPTCVariant* s)
 {
 /*
     We need to copy the parameters for this function to locals and use them
     from there since the parameters occupy the same stack space as the stack
     we're trying to populate.
 */
-    uint32 *l_d = d;
+    uint32_t *l_d = d;
     nsXPTCVariant *l_s = s;
-    uint32 l_paramCount = paramCount;
-    uint32 regCount = 0;	// return the number of registers to load from the stack
+    uint32_t l_paramCount = paramCount;
+    uint32_t regCount = 0;	// return the number of registers to load from the stack
 
     typedef struct {
-        uint32 hi;
-        uint32 lo;
+        uint32_t hi;
+        uint32_t lo;
     } DU;               // have to move 64 bit entities as 32 bit halves since
                         // stack slots are not guaranteed 16 byte aligned
 
-    for(uint32 i = 0; i < l_paramCount; i++, l_d++, l_s++)
+    for(uint32_t i = 0; i < l_paramCount; i++, l_d++, l_s++)
     {
 	if (regCount < 5) regCount++;
         if(l_s->IsPtrData())
         {
             *((void**)l_d) = l_s->ptr;
             continue;
         }
         switch(l_s->type)
         {
-        case nsXPTType::T_I8     : *((int32*)   l_d) = l_s->val.i8;          break;
-        case nsXPTType::T_I16    : *((int32*)  l_d) = l_s->val.i16;         break;
-        case nsXPTType::T_I32    : *((int32*)  l_d) = l_s->val.i32;         break;
+        case nsXPTType::T_I8     : *((int32_t*)   l_d) = l_s->val.i8;          break;
+        case nsXPTType::T_I16    : *((int32_t*)  l_d) = l_s->val.i16;         break;
+        case nsXPTType::T_I32    : *((int32_t*)  l_d) = l_s->val.i32;         break;
         case nsXPTType::T_I64    : 
         case nsXPTType::T_U64    : 
-        case nsXPTType::T_DOUBLE : *((uint32*) l_d++) = ((DU *)l_s)->hi;
+        case nsXPTType::T_DOUBLE : *((uint32_t*) l_d++) = ((DU *)l_s)->hi;
 				   if (regCount < 5) regCount++;
-                                   *((uint32*) l_d) = ((DU *)l_s)->lo;
+                                   *((uint32_t*) l_d) = ((DU *)l_s)->lo;
                                    break;
-        case nsXPTType::T_U8     : *((uint32*) l_d) = l_s->val.u8;          break;
-        case nsXPTType::T_U16    : *((uint32*) l_d) = l_s->val.u16;         break;
-        case nsXPTType::T_U32    : *((uint32*) l_d) = l_s->val.u32;         break;
+        case nsXPTType::T_U8     : *((uint32_t*) l_d) = l_s->val.u8;          break;
+        case nsXPTType::T_U16    : *((uint32_t*) l_d) = l_s->val.u16;         break;
+        case nsXPTType::T_U32    : *((uint32_t*) l_d) = l_s->val.u32;         break;
         case nsXPTType::T_FLOAT  : *((float*)  l_d) = l_s->val.f;           break;
-        case nsXPTType::T_BOOL   : *((uint32*) l_d) = l_s->val.b;           break;
-        case nsXPTType::T_CHAR   : *((uint32*) l_d) = l_s->val.c;           break;
-        case nsXPTType::T_WCHAR  : *((int32*)  l_d) = l_s->val.wc;          break;
+        case nsXPTType::T_BOOL   : *((uint32_t*) l_d) = l_s->val.b;           break;
+        case nsXPTType::T_CHAR   : *((uint32_t*) l_d) = l_s->val.c;           break;
+        case nsXPTType::T_WCHAR  : *((int32_t*)  l_d) = l_s->val.wc;          break;
         default:
             // all the others are plain pointer types
             *((void**)l_d) = l_s->val.p;
             break;
         }
     }
     return regCount;
 }
--- a/xpcom/reflect/xptcall/src/md/unix/xptcinvoke_sparc_openbsd.cpp
+++ b/xpcom/reflect/xptcall/src/md/unix/xptcinvoke_sparc_openbsd.cpp
@@ -68,53 +68,53 @@ invoke_count_words(uint32_t paramCount, 
 extern "C" uint32_t
 invoke_copy_to_stack(uint32_t* d, uint32_t paramCount, nsXPTCVariant* s)
 {
 /*
     We need to copy the parameters for this function to locals and use them
     from there since the parameters occupy the same stack space as the stack
     we're trying to populate.
 */
-    uint32 *l_d = d;
+    uint32_t *l_d = d;
     nsXPTCVariant *l_s = s;
-    uint32 l_paramCount = paramCount;
-    uint32 regCount = 0;	// return the number of registers to load from the stack
+    uint32_t l_paramCount = paramCount;
+    uint32_t regCount = 0;	// return the number of registers to load from the stack
 
     typedef struct {
-        uint32 hi;
-        uint32 lo;
+        uint32_t hi;
+        uint32_t lo;
     } DU;               // have to move 64 bit entities as 32 bit halves since
                         // stack slots are not guaranteed 16 byte aligned
 
-    for(uint32 i = 0; i < l_paramCount; i++, l_d++, l_s++)
+    for(uint32_t i = 0; i < l_paramCount; i++, l_d++, l_s++)
     {
 	if (regCount < 5) regCount++;
         if(l_s->IsPtrData())
         {
             *((void**)l_d) = l_s->ptr;
             continue;
         }
         switch(l_s->type)
         {
-        case nsXPTType::T_I8     : *((int32*)  l_d) = l_s->val.i8;          break;
-        case nsXPTType::T_I16    : *((int32*)  l_d) = l_s->val.i16;         break;
-        case nsXPTType::T_I32    : *((int32*)  l_d) = l_s->val.i32;         break;
+        case nsXPTType::T_I8     : *((int32_t*)  l_d) = l_s->val.i8;          break;
+        case nsXPTType::T_I16    : *((int32_t*)  l_d) = l_s->val.i16;         break;
+        case nsXPTType::T_I32    : *((int32_t*)  l_d) = l_s->val.i32;         break;
         case nsXPTType::T_I64    : 
         case nsXPTType::T_U64    : 
-        case nsXPTType::T_DOUBLE : *((uint32*) l_d++) = ((DU *)l_s)->hi;
+        case nsXPTType::T_DOUBLE : *((uint32_t*) l_d++) = ((DU *)l_s)->hi;
 				   if (regCount < 5) regCount++;
-                                   *((uint32*) l_d) = ((DU *)l_s)->lo;
+                                   *((uint32_t*) l_d) = ((DU *)l_s)->lo;
                                    break;
-        case nsXPTType::T_U8     : *((uint32*) l_d) = l_s->val.u8;          break;
-        case nsXPTType::T_U16    : *((uint32*) l_d) = l_s->val.u16;         break;
-        case nsXPTType::T_U32    : *((uint32*) l_d) = l_s->val.u32;         break;
+        case nsXPTType::T_U8     : *((uint32_t*) l_d) = l_s->val.u8;          break;
+        case nsXPTType::T_U16    : *((uint32_t*) l_d) = l_s->val.u16;         break;
+        case nsXPTType::T_U32    : *((uint32_t*) l_d) = l_s->val.u32;         break;
         case nsXPTType::T_FLOAT  : *((float*)  l_d) = l_s->val.f;           break;
-        case nsXPTType::T_BOOL   : *((uint32*) l_d) = l_s->val.b;           break;
-        case nsXPTType::T_CHAR   : *((uint32*) l_d) = l_s->val.c;           break;
-        case nsXPTType::T_WCHAR  : *((int32*)  l_d) = l_s->val.wc;          break;
+        case nsXPTType::T_BOOL   : *((uint32_t*) l_d) = l_s->val.b;           break;
+        case nsXPTType::T_CHAR   : *((uint32_t*) l_d) = l_s->val.c;           break;
+        case nsXPTType::T_WCHAR  : *((int32_t*)  l_d) = l_s->val.wc;          break;
         default:
             // all the others are plain pointer types
             *((void**)l_d) = l_s->val.p;
             break;
         }
     }
     return regCount;
 }
--- a/xpcom/reflect/xptcall/src/md/unix/xptcinvoke_sparc_solaris.cpp
+++ b/xpcom/reflect/xptcall/src/md/unix/xptcinvoke_sparc_solaris.cpp
@@ -71,53 +71,53 @@ invoke_count_words(uint32_t paramCount, 
 extern "C" uint32_t
 invoke_copy_to_stack(uint32_t* d, uint32_t paramCount, nsXPTCVariant* s)
 {
 /*
     We need to copy the parameters for this function to locals and use them
     from there since the parameters occupy the same stack space as the stack
     we're trying to populate.
 */
-    uint32 *l_d = d;
+    uint32_t *l_d = d;
     nsXPTCVariant *l_s = s;
-    uint32 l_paramCount = paramCount;
-    uint32 regCount = 0;	// return the number of registers to load from the stack
+    uint32_t l_paramCount = paramCount;
+    uint32_t regCount = 0;	// return the number of registers to load from the stack
 
     typedef struct {
-        uint32 hi;
-        uint32 lo;
+        uint32_t hi;
+        uint32_t lo;
     } DU;               // have to move 64 bit entities as 32 bit halves since
                         // stack slots are not guaranteed 16 byte aligned
 
-    for(uint32 i = 0; i < l_paramCount; i++, l_d++, l_s++)
+    for(uint32_t i = 0; i < l_paramCount; i++, l_d++, l_s++)
     {
 	if (regCount < 5) regCount++;
         if(l_s->IsPtrData())
         {
             *((void**)l_d) = l_s->ptr;
             continue;
         }
         switch(l_s->type)
         {
-        case nsXPTType::T_I8     : *((int32*)   l_d) = l_s->val.i8;          break;
-        case nsXPTType::T_I16    : *((int32*)  l_d) = l_s->val.i16;         break;
-        case nsXPTType::T_I32    : *((int32*)  l_d) = l_s->val.i32;         break;
+        case nsXPTType::T_I8     : *((int32_t*)   l_d) = l_s->val.i8;          break;
+        case nsXPTType::T_I16    : *((int32_t*)  l_d) = l_s->val.i16;         break;
+        case nsXPTType::T_I32    : *((int32_t*)  l_d) = l_s->val.i32;         break;
         case nsXPTType::T_I64    : 
         case nsXPTType::T_U64    : 
-        case nsXPTType::T_DOUBLE : *((uint32*) l_d++) = ((DU *)l_s)->hi;
+        case nsXPTType::T_DOUBLE : *((uint32_t*) l_d++) = ((DU *)l_s)->hi;
 				   if (regCount < 5) regCount++;
-                                   *((uint32*) l_d) = ((DU *)l_s)->lo;
+                                   *((uint32_t*) l_d) = ((DU *)l_s)->lo;
                                    break;
-        case nsXPTType::T_U8     : *((uint32*) l_d) = l_s->val.u8;          break;
-        case nsXPTType::T_U16    : *((uint32*) l_d) = l_s->val.u16;         break;
-        case nsXPTType::T_U32    : *((uint32*) l_d) = l_s->val.u32;         break;
+        case nsXPTType::T_U8     : *((uint32_t*) l_d) = l_s->val.u8;          break;
+        case nsXPTType::T_U16    : *((uint32_t*) l_d) = l_s->val.u16;         break;
+        case nsXPTType::T_U32    : *((uint32_t*) l_d) = l_s->val.u32;         break;
         case nsXPTType::T_FLOAT  : *((float*)  l_d) = l_s->val.f;           break;
-        case nsXPTType::T_BOOL   : *((uint32*) l_d) = l_s->val.b;           break;
-        case nsXPTType::T_CHAR   : *((uint32*) l_d) = l_s->val.c;           break;
-        case nsXPTType::T_WCHAR  : *((int32*)  l_d) = l_s->val.wc;          break;
+        case nsXPTType::T_BOOL   : *((uint32_t*) l_d) = l_s->val.b;           break;
+        case nsXPTType::T_CHAR   : *((uint32_t*) l_d) = l_s->val.c;           break;
+        case nsXPTType::T_WCHAR  : *((int32_t*)  l_d) = l_s->val.wc;          break;
         default:
             // all the others are plain pointer types
             *((void**)l_d) = l_s->val.p;
             break;
         }
     }
     return regCount;
 }
--- a/xpcom/reflect/xptcall/src/md/unix/xptcinvoke_x86_64_solaris.cpp
+++ b/xpcom/reflect/xptcall/src/md/unix/xptcinvoke_x86_64_solaris.cpp
@@ -20,17 +20,17 @@ static inline void
 invoke_count_words(uint32_t paramCount, nsXPTCVariant * s,
                    uint32_t & nr_gpr, uint32_t & nr_fpr, uint32_t & nr_stack)
 {
     nr_gpr = 1; // skip one GP register for 'that'
     nr_fpr = 0;
     nr_stack = 0;
 
     /* Compute number of eightbytes of class MEMORY.  */
-    for (uint32 i = 0; i < paramCount; i++, s++) {
+    for (uint32_t i = 0; i < paramCount; i++, s++) {
         if (!s->IsPtrData()
             && (s->type == nsXPTType::T_FLOAT || s->type == nsXPTType::T_DOUBLE)) {
             if (nr_fpr < FPR_COUNT)
                 nr_fpr++;
             else
                 nr_stack++;
         }
         else {
@@ -45,17 +45,17 @@ invoke_count_words(uint32_t paramCount, 
 static void
 invoke_copy_to_stack(uint64_t * d, uint32_t paramCount, nsXPTCVariant * s,
                      uint64_t * gpregs, double * fpregs)
 {
     uint32_t nr_gpr = 1; // skip one GP register for 'that'
     uint32_t nr_fpr = 0;
     uint64_t value;
 
-    for (uint32 i = 0; i < paramCount; i++, s++) {
+    for (uint32_t i = 0; i < paramCount; i++, s++) {
         if (s->IsPtrData())
             value = (uint64_t) s->ptr;
         else {
             switch (s->type) {
             case nsXPTType::T_FLOAT:                                break;
             case nsXPTType::T_DOUBLE:                               break;
             case nsXPTType::T_I8:     value = s->val.i8;            break;
             case nsXPTType::T_I16:    value = s->val.i16;           break;
--- a/xpcom/reflect/xptcall/src/md/unix/xptcinvoke_x86_64_unix.cpp
+++ b/xpcom/reflect/xptcall/src/md/unix/xptcinvoke_x86_64_unix.cpp
@@ -21,17 +21,17 @@ invoke_count_words(uint32_t paramCount, 
 {
     uint32_t nr_gpr;
     uint32_t nr_fpr;
     nr_gpr = 1; // skip one GP register for 'that'
     nr_fpr = 0;
     nr_stack = 0;
 
     /* Compute number of eightbytes of class MEMORY.  */
-    for (uint32 i = 0; i < paramCount; i++, s++) {
+    for (uint32_t i = 0; i < paramCount; i++, s++) {
         if (!s->IsPtrData()
             && (s->type == nsXPTType::T_FLOAT || s->type == nsXPTType::T_DOUBLE)) {
             if (nr_fpr < FPR_COUNT)
                 nr_fpr++;
             else
                 nr_stack++;
         }
         else {
@@ -46,17 +46,17 @@ invoke_count_words(uint32_t paramCount, 
 static void
 invoke_copy_to_stack(uint64_t * d, uint32_t paramCount, nsXPTCVariant * s,
                      uint64_t * gpregs, double * fpregs)
 {
     uint32_t nr_gpr = 1; // skip one GP register for 'that'
     uint32_t nr_fpr = 0;
     uint64_t value;
 
-    for (uint32 i = 0; i < paramCount; i++, s++) {
+    for (uint32_t i = 0; i < paramCount; i++, s++) {
         if (s->IsPtrData())
             value = (uint64_t) s->ptr;
         else {
             switch (s->type) {
             case nsXPTType::T_FLOAT:                                break;
             case nsXPTType::T_DOUBLE:                               break;
             case nsXPTType::T_I8:     value = s->val.i8;            break;
             case nsXPTType::T_I16:    value = s->val.i16;           break;
--- a/xpcom/reflect/xptcall/src/md/unix/xptcstubs_alpha_openbsd.cpp
+++ b/xpcom/reflect/xptcall/src/md/unix/xptcstubs_alpha_openbsd.cpp
@@ -5,21 +5,21 @@
 
 /* Implement shared vtbl methods. */
 
 #include "xptcprivate.h"
 #include "xptiprivate.h"
 
 /* Prototype specifies unmangled function name and disables unused warning */
 static nsresult
-PrepareAndDispatch(nsXPTCStubBase* self, uint32 methodIndex, uint64_t* args)
+PrepareAndDispatch(nsXPTCStubBase* self, uint32_t methodIndex, uint64_t* args)
 __asm__("PrepareAndDispatch") __attribute__((used));
 
 static nsresult
-PrepareAndDispatch(nsXPTCStubBase* self, uint32 methodIndex, uint64_t* args)
+PrepareAndDispatch(nsXPTCStubBase* self, uint32_t methodIndex, uint64_t* args)
 {
     const uint8_t PARAM_BUFFER_COUNT = 16;
     const uint8_t NUM_ARG_REGS = 6-1;        // -1 for "this" pointer
 
     nsXPTCMiniVariant paramBuffer[PARAM_BUFFER_COUNT];
     nsXPTCMiniVariant* dispatchParams = NULL;
     const nsXPTMethodInfo* info;
     uint8_t paramCount;
--- a/xpcom/reflect/xptcall/src/md/unix/xptcstubs_arm.cpp
+++ b/xpcom/reflect/xptcall/src/md/unix/xptcstubs_arm.cpp
@@ -20,34 +20,34 @@
 #else
 /* This tells older gccs not to warn about unused vairables.
  * @see http://docs.freebsd.org/info/gcc/gcc.info.Variable_Attributes.html
  */
 #define DONT_DROP_OR_WARN __attribute__((unused))
 #endif
 
 /* Specify explicitly a symbol for this function, don't try to guess the c++ mangled symbol.  */
-static nsresult PrepareAndDispatch(nsXPTCStubBase* self, uint32 methodIndex, uint32_t* args) asm("_PrepareAndDispatch")
+static nsresult PrepareAndDispatch(nsXPTCStubBase* self, uint32_t methodIndex, uint32_t* args) asm("_PrepareAndDispatch")
 DONT_DROP_OR_WARN;
 
 #ifdef __ARM_EABI__
 #define DOUBLEWORD_ALIGN(p) ((uint32_t *)((((uint32_t)(p)) + 7) & 0xfffffff8))
 #else
 #define DOUBLEWORD_ALIGN(p) (p)
 #endif
 
 // Apple's iOS toolchain is lame and does not support .cfi directives.
 #ifdef __APPLE__
 #define CFI(str)
 #else
 #define CFI(str) str
 #endif
 
 static nsresult
-PrepareAndDispatch(nsXPTCStubBase* self, uint32 methodIndex, uint32_t* args)
+PrepareAndDispatch(nsXPTCStubBase* self, uint32_t methodIndex, uint32_t* args)
 {
 #define PARAM_BUFFER_COUNT     16
 
     nsXPTCMiniVariant paramBuffer[PARAM_BUFFER_COUNT];
     nsXPTCMiniVariant* dispatchParams = NULL;
     const nsXPTMethodInfo* info;
     uint8_t paramCount;
     uint8_t i;
--- a/xpcom/reflect/xptcall/src/md/unix/xptcstubs_arm_netbsd.cpp
+++ b/xpcom/reflect/xptcall/src/md/unix/xptcstubs_arm_netbsd.cpp
@@ -3,17 +3,17 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 /* Implement shared vtbl methods. */
 
 #include "xptcprivate.h"
 
 nsresult
-PrepareAndDispatch(nsXPTCStubBase* self, uint32 methodIndex, uint32_t* args)
+PrepareAndDispatch(nsXPTCStubBase* self, uint32_t methodIndex, uint32_t* args)
 {
 #define PARAM_BUFFER_COUNT     16
 
     nsXPTCMiniVariant paramBuffer[PARAM_BUFFER_COUNT];
     nsXPTCMiniVariant* dispatchParams = NULL;
     nsIInterfaceInfo* iface_info = NULL;
     const nsXPTMethodInfo* info;
     uint8_t paramCount;
--- a/xpcom/reflect/xptcall/src/md/unix/xptcstubs_arm_openbsd.cpp
+++ b/xpcom/reflect/xptcall/src/md/unix/xptcstubs_arm_openbsd.cpp
@@ -16,21 +16,21 @@
 #else
 /* This tells older gccs not to warn about unused vairables.
  * @see http://docs.freebsd.org/info/gcc/gcc.info.Variable_Attributes.html
  */
 #define DONT_DROP_OR_WARN __attribute__((unused))
 #endif
 
 /* Specify explicitly a symbol for this function, don't try to guess the c++ mangled symbol.  */
-static nsresult PrepareAndDispatch(nsXPTCStubBase* self, uint32 methodIndex, uint32_t* args) asm("_PrepareAndDispatch")
+static nsresult PrepareAndDispatch(nsXPTCStubBase* self, uint32_t methodIndex, uint32_t* args) asm("_PrepareAndDispatch")
 DONT_DROP_OR_WARN;
 
 static nsresult
-PrepareAndDispatch(nsXPTCStubBase* self, uint32 methodIndex, uint32_t* args)
+PrepareAndDispatch(nsXPTCStubBase* self, uint32_t methodIndex, uint32_t* args)
 {
 #define PARAM_BUFFER_COUNT     16
 
     nsXPTCMiniVariant paramBuffer[PARAM_BUFFER_COUNT];
     nsXPTCMiniVariant* dispatchParams = NULL;
     const nsXPTMethodInfo* info;
     uint8_t paramCount;
     uint8_t i;
--- a/xpcom/reflect/xptcall/src/md/unix/xptcstubs_gcc_x86_unix.cpp
+++ b/xpcom/reflect/xptcall/src/md/unix/xptcstubs_gcc_x86_unix.cpp
@@ -7,17 +7,17 @@
 
 #include "xptcprivate.h"
 #include "xptiprivate.h"
 #include "xptc_gcc_x86_unix.h"
 
 extern "C" {
 static nsresult ATTRIBUTE_USED
 __attribute__ ((regparm (3)))
-PrepareAndDispatch(uint32 methodIndex, nsXPTCStubBase* self, uint32_t* args)
+PrepareAndDispatch(uint32_t methodIndex, nsXPTCStubBase* self, uint32_t* args)
 {
 #define PARAM_BUFFER_COUNT     16
 
     nsXPTCMiniVariant paramBuffer[PARAM_BUFFER_COUNT];
     nsXPTCMiniVariant* dispatchParams = NULL;
     const nsXPTMethodInfo* info;
     uint8_t paramCount;
     uint8_t i;
--- a/xpcom/reflect/xptcall/src/md/unix/xptcstubs_linux_alpha.cpp
+++ b/xpcom/reflect/xptcall/src/md/unix/xptcstubs_linux_alpha.cpp
@@ -5,21 +5,21 @@
 
 /* Implement shared vtbl methods. */
 
 #include "xptcprivate.h"
 #include "xptiprivate.h"
 
 /* Prototype specifies unmangled function name and disables unused warning */
 static nsresult
-PrepareAndDispatch(nsXPTCStubBase* self, uint32 methodIndex, uint64_t* args)
+PrepareAndDispatch(nsXPTCStubBase* self, uint32_t methodIndex, uint64_t* args)
 __asm__("PrepareAndDispatch") __attribute__((used));
 
 static nsresult
-PrepareAndDispatch(nsXPTCStubBase* self, uint32 methodIndex, uint64_t* args)
+PrepareAndDispatch(nsXPTCStubBase* self, uint32_t methodIndex, uint64_t* args)
 {
     const uint8_t PARAM_BUFFER_COUNT = 16;
     const uint8_t NUM_ARG_REGS = 6-1;        // -1 for "this" pointer
 
     nsXPTCMiniVariant paramBuffer[PARAM_BUFFER_COUNT];
     nsXPTCMiniVariant* dispatchParams = NULL;
     const nsXPTMethodInfo* info;
     uint8_t paramCount;
--- a/xpcom/reflect/xptcall/src/md/unix/xptcstubs_linux_m68k.cpp
+++ b/xpcom/reflect/xptcall/src/md/unix/xptcstubs_linux_m68k.cpp
@@ -5,17 +5,17 @@
 
 /* Implement shared vtbl methods. */
 
 #include "xptcprivate.h"
 #include "xptiprivate.h"
 
 extern "C" {
     nsresult
-    PrepareAndDispatch(nsXPTCStubBase* self, uint32 methodIndex, uint32* args)
+    PrepareAndDispatch(nsXPTCStubBase* self, uint32_t methodIndex, uint32_t* args)
     {
 #define PARAM_BUFFER_COUNT     16
 
         nsXPTCMiniVariant paramBuffer[PARAM_BUFFER_COUNT];
         nsXPTCMiniVariant* dispatchParams = NULL;
         const nsXPTMethodInfo* info;
         uint8_t paramCount;
         uint8_t i;
@@ -80,17 +80,17 @@ extern "C" {
         return result;
     }
 }
 
 #define STUB_ENTRY(n) \
 nsresult nsXPTCStubBase::Stub##n() \
 { \
   void *frame = __builtin_frame_address(0); \
-  return PrepareAndDispatch(this, n, (uint32*)frame + 3); \
+  return PrepareAndDispatch(this, n, (uint32_t*)frame + 3); \
 }
 
 #define SENTINEL_ENTRY(n) \
 nsresult nsXPTCStubBase::Sentinel##n() \
 { \
     NS_ERROR("nsXPTCStubBase::Sentinel called"); \
     return NS_ERROR_NOT_IMPLEMENTED; \
 }
--- a/xpcom/reflect/xptcall/src/md/unix/xptcstubs_linux_s390.cpp
+++ b/xpcom/reflect/xptcall/src/md/unix/xptcstubs_linux_s390.cpp
@@ -5,17 +5,17 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 /* Implement shared vtbl methods. */
 
 #include "xptcprivate.h"
 #include "xptiprivate.h"
 
 static nsresult
-PrepareAndDispatch(nsXPTCStubBase* self, uint32 methodIndex, 
+PrepareAndDispatch(nsXPTCStubBase* self, uint32_t methodIndex, 
                    uint32_t* a_gpr, uint64_t *a_fpr, uint32_t *a_ov)
 {
 #define PARAM_BUFFER_COUNT     16
 
     nsXPTCMiniVariant paramBuffer[PARAM_BUFFER_COUNT];
     nsXPTCMiniVariant* dispatchParams = NULL;
     const nsXPTMethodInfo* info;
     uint8_t paramCount;
--- a/xpcom/reflect/xptcall/src/md/unix/xptcstubs_linux_s390x.cpp
+++ b/xpcom/reflect/xptcall/src/md/unix/xptcstubs_linux_s390x.cpp
@@ -5,17 +5,17 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 /* Implement shared vtbl methods. */
 
 #include "xptcprivate.h"
 #include "xptiprivate.h"
 
 static nsresult
-PrepareAndDispatch(nsXPTCStubBase* self, uint32 methodIndex, 
+PrepareAndDispatch(nsXPTCStubBase* self, uint32_t methodIndex, 
                    uint64_t* a_gpr, uint64_t *a_fpr, uint64_t *a_ov)
 {
 #define PARAM_BUFFER_COUNT     16
 
     nsXPTCMiniVariant paramBuffer[PARAM_BUFFER_COUNT];
     nsXPTCMiniVariant* dispatchParams = NULL;
     const nsXPTMethodInfo* info;
     uint8_t paramCount;
--- a/xpcom/reflect/xptcall/src/md/unix/xptcstubs_netbsd_m68k.cpp
+++ b/xpcom/reflect/xptcall/src/md/unix/xptcstubs_netbsd_m68k.cpp
@@ -8,17 +8,17 @@
 #include "xptcprivate.h"
 
 #if !defined(__NetBSD__) || !defined(__m68k__)
 #error This code is for NetBSD/m68k only
 #endif
 
 extern "C" {
     static nsresult
-    PrepareAndDispatch(nsXPTCStubBase* self, uint32 methodIndex, uint32* args)
+    PrepareAndDispatch(nsXPTCStubBase* self, uint32_t methodIndex, uint32_t* args)
     {
 #define PARAM_BUFFER_COUNT     16
 
         nsXPTCMiniVariant paramBuffer[PARAM_BUFFER_COUNT];
         nsXPTCMiniVariant* dispatchParams = NULL;
         nsIInterfaceInfo* iface_info = NULL;
         const nsXPTMethodInfo* info;
         uint8_t paramCount;
--- a/xpcom/reflect/xptcall/src/md/unix/xptcstubs_nto_arm.cpp
+++ b/xpcom/reflect/xptcall/src/md/unix/xptcstubs_nto_arm.cpp
@@ -7,20 +7,20 @@
 
 #include "xptcprivate.h"
 
 #if !defined(__QNXNTO__) || !defined(__arm__)
 #error "This code is for Neutrino ARM only. Please check if it works for you, too.\nDepends strongly on gcc behaviour."
 #endif
 
 /* Specify explicitly a symbol for this function, don't try to guess the c++ mangled symbol.  */
-static nsresult PrepareAndDispatch(nsXPTCStubBase* self, uint32 methodIndex, uint32_t* args) asm("_PrepareAndDispatch");
+static nsresult PrepareAndDispatch(nsXPTCStubBase* self, uint32_t methodIndex, uint32_t* args) asm("_PrepareAndDispatch");
 
 static nsresult
-PrepareAndDispatch(nsXPTCStubBase* self, uint32 methodIndex, uint32_t* args)
+PrepareAndDispatch(nsXPTCStubBase* self, uint32_t methodIndex, uint32_t* args)
 {
 #define PARAM_BUFFER_COUNT     16
 
     nsXPTCMiniVariant paramBuffer[PARAM_BUFFER_COUNT];
     nsXPTCMiniVariant* dispatchParams = NULL;
     nsIInterfaceInfo* iface_info = NULL;
     const nsXPTMethodInfo* info;
     uint8_t paramCount;
--- a/xpcom/reflect/xptcall/src/md/unix/xptcstubs_pa32.cpp
+++ b/xpcom/reflect/xptcall/src/md/unix/xptcstubs_pa32.cpp
@@ -15,18 +15,18 @@
 #endif
 
 extern "C" nsresult
 PrepareAndDispatch(nsXPTCStubBase* self, uint32_t methodIndex,
   uint32_t* args, uint32_t* floatargs)
 {
 
   typedef struct {
-    uint32 hi;
-    uint32 lo;
+    uint32_t hi;
+    uint32_t lo;
   } DU;
 
 #define PARAM_BUFFER_COUNT     16
 
   nsXPTCMiniVariant paramBuffer[PARAM_BUFFER_COUNT];
   nsXPTCMiniVariant* dispatchParams = NULL;
   const nsXPTMethodInfo* info;
   int32_t regwords = 1; /* self pointer is not in the variant records */
--- a/xpcom/reflect/xptcall/src/md/unix/xptcstubs_ppc_aix.cpp
+++ b/xpcom/reflect/xptcall/src/md/unix/xptcstubs_ppc_aix.cpp
@@ -15,18 +15,18 @@
         arrive in a separate chunk of data that has been loaded from the registers. 
         The args pointer has been set to the start of the parameters BEYOND the ones
         arriving in registers
 */
 extern "C" nsresult
 PrepareAndDispatch(nsXPTCStubBase* self, uint32_t methodIndex, uint32_t* args, uint32_t *gprData, double *fprData)
 {
     typedef struct {
-        uint32 hi;
-        uint32 lo;      // have to move 64 bit entities as 32 bit halves since
+        uint32_t hi;
+        uint32_t lo;      // have to move 64 bit entities as 32 bit halves since
     } DU;               // stack slots are not guaranteed 16 byte aligned
 
 #define PARAM_BUFFER_COUNT     16
 #define PARAM_GPR_COUNT         7  
 
     nsXPTCMiniVariant paramBuffer[PARAM_BUFFER_COUNT];
     nsXPTCMiniVariant* dispatchParams = NULL;
     const nsXPTMethodInfo* info = NULL;
--- a/xpcom/reflect/xptcall/src/md/unix/xptcstubs_sparc_netbsd.cpp
+++ b/xpcom/reflect/xptcall/src/md/unix/xptcstubs_sparc_netbsd.cpp
@@ -5,22 +5,22 @@
 
 /* Implement shared vtbl methods. */
 
 #include "xptcprivate.h"
 
 #if defined(sparc) || defined(__sparc__)
 
 extern "C" nsresult
-PrepareAndDispatch(nsXPTCStubBase* self, uint32 methodIndex, uint32* args)
+PrepareAndDispatch(nsXPTCStubBase* self, uint32_t methodIndex, uint32_t* args)
 {
 
     typedef struct {
-        uint32 hi;
-        uint32 lo;
+        uint32_t hi;
+        uint32_t lo;
     } DU;               // have to move 64 bit entities as 32 bit halves since
                         // stack slots are not guaranteed 16 byte aligned
 
 #define PARAM_BUFFER_COUNT     16
 
     nsXPTCMiniVariant paramBuffer[PARAM_BUFFER_COUNT];
     nsXPTCMiniVariant* dispatchParams = NULL;
     nsIInterfaceInfo* iface_info = NULL;
--- a/xpcom/reflect/xptcall/src/md/unix/xptcstubs_sparc_openbsd.cpp
+++ b/xpcom/reflect/xptcall/src/md/unix/xptcstubs_sparc_openbsd.cpp
@@ -5,22 +5,22 @@
 
 /* Implement shared vtbl methods. */
 
 #include "xptcprivate.h"
 
 #if defined(sparc) || defined(__sparc__)
 
 extern "C" nsresult
-PrepareAndDispatch(nsXPTCStubBase* self, uint32 methodIndex, uint32* args)
+PrepareAndDispatch(nsXPTCStubBase* self, uint32_t methodIndex, uint32_t* args)
 {
 
     typedef struct {
-        uint32 hi;
-        uint32 lo;
+        uint32_t hi;
+        uint32_t lo;
     } DU;               // have to move 64 bit entities as 32 bit halves since
                         // stack slots are not guaranteed 16 byte aligned
 
 #define PARAM_BUFFER_COUNT     16
 
     nsXPTCMiniVariant paramBuffer[PARAM_BUFFER_COUNT];
     nsXPTCMiniVariant* dispatchParams = NULL;
     nsIInterfaceInfo* iface_info = NULL;
--- a/xpcom/reflect/xptcall/src/md/unix/xptcstubs_sparc_solaris.cpp
+++ b/xpcom/reflect/xptcall/src/md/unix/xptcstubs_sparc_solaris.cpp
@@ -6,22 +6,22 @@
 /* Implement shared vtbl methods. */
 
 #include "xptcprivate.h"
 #include "xptiprivate.h"
 
 #if defined(sparc) || defined(__sparc__)
 
 extern "C" nsresult
-PrepareAndDispatch(nsXPTCStubBase* self, uint32 methodIndex, uint32* args)
+PrepareAndDispatch(nsXPTCStubBase* self, uint32_t methodIndex, uint32_t* args)
 {
 
     typedef struct {
-        uint32 hi;
-        uint32 lo;
+        uint32_t hi;
+        uint32_t lo;
     } DU;               // have to move 64 bit entities as 32 bit halves since
                         // stack slots are not guaranteed 16 byte aligned
 
 #define PARAM_BUFFER_COUNT     16
 
     nsXPTCMiniVariant paramBuffer[PARAM_BUFFER_COUNT];
     nsXPTCMiniVariant* dispatchParams = NULL;
     const nsXPTMethodInfo* info;
--- a/xpcom/reflect/xptcall/src/md/unix/xptcstubs_x86_solaris.cpp
+++ b/xpcom/reflect/xptcall/src/md/unix/xptcstubs_x86_solaris.cpp
@@ -5,17 +5,17 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 /* Implement shared vtbl methods. */
 
 #include "xptcprivate.h"
 #include "xptiprivate.h"
 
 nsresult
-PrepareAndDispatch(nsXPTCStubBase* self, uint32 methodIndex, uint32_t* args)
+PrepareAndDispatch(nsXPTCStubBase* self, uint32_t methodIndex, uint32_t* args)
 {
 #define PARAM_BUFFER_COUNT     16
 
     nsXPTCMiniVariant paramBuffer[PARAM_BUFFER_COUNT];
     nsXPTCMiniVariant* dispatchParams = NULL;
     const nsXPTMethodInfo* info;
     uint8_t paramCount;
     uint8_t i;
--- a/xpcom/reflect/xptinfo/src/xptiInterfaceInfo.cpp
+++ b/xpcom/reflect/xptinfo/src/xptiInterfaceInfo.cpp
@@ -152,39 +152,39 @@ xptiInterfaceEntry::IsFunction(bool* res
     if(!EnsureResolved())
         return NS_ERROR_UNEXPECTED;
 
     *result = XPT_ID_IS_FUNCTION(mDescriptor->flags);
     return NS_OK;
 }
 
 nsresult
-xptiInterfaceEntry::GetMethodCount(uint16* count)
+xptiInterfaceEntry::GetMethodCount(uint16_t* count)
 {
     if(!EnsureResolved())
         return NS_ERROR_UNEXPECTED;
     
     *count = mMethodBaseIndex + 
              mDescriptor->num_methods;
     return NS_OK;
 }
 
 nsresult
-xptiInterfaceEntry::GetConstantCount(uint16* count)
+xptiInterfaceEntry::GetConstantCount(uint16_t* count)
 {
     if(!EnsureResolved())
         return NS_ERROR_UNEXPECTED;
 
     *count = mConstantBaseIndex + 
              mDescriptor->num_constants;
     return NS_OK;
 }
 
 nsresult
-xptiInterfaceEntry::GetMethodInfo(uint16 index, const nsXPTMethodInfo** info)
+xptiInterfaceEntry::GetMethodInfo(uint16_t index, const nsXPTMethodInfo** info)
 {
     if(!EnsureResolved())
         return NS_ERROR_UNEXPECTED;
 
     if(index < mMethodBaseIndex)
         return mParent->GetMethodInfo(index, info);
 
     if(index >= mMethodBaseIndex + 
@@ -197,24 +197,24 @@ xptiInterfaceEntry::GetMethodInfo(uint16
 
     // else...
     *info = reinterpret_cast<nsXPTMethodInfo*>
        (&mDescriptor->method_descriptors[index - mMethodBaseIndex]);
     return NS_OK;
 }
 
 nsresult
-xptiInterfaceEntry::GetMethodInfoForName(const char* methodName, uint16 *index,
+xptiInterfaceEntry::GetMethodInfoForName(const char* methodName, uint16_t *index,
                                          const nsXPTMethodInfo** result)
 {
     if(!EnsureResolved())
         return NS_ERROR_UNEXPECTED;
 
     // This is a slow algorithm, but this is not expected to be called much.
-    for(uint16 i = 0; i < mDescriptor->num_methods; ++i)
+    for(uint16_t i = 0; i < mDescriptor->num_methods; ++i)
     {
         const nsXPTMethodInfo* info;
         info = reinterpret_cast<nsXPTMethodInfo*>
                                (&mDescriptor->
                                         method_descriptors[i]);
         if (PL_strcmp(methodName, info->GetName()) == 0) {
             *index = i + mMethodBaseIndex;
             *result = info;
@@ -228,17 +228,17 @@ xptiInterfaceEntry::GetMethodInfoForName
     {
         *index = 0;
         *result = 0;
         return NS_ERROR_INVALID_ARG;
     }
 }
 
 nsresult
-xptiInterfaceEntry::GetConstant(uint16 index, const nsXPTConstant** constant)
+xptiInterfaceEntry::GetConstant(uint16_t index, const nsXPTConstant** constant)
 {
     if(!EnsureResolved())
         return NS_ERROR_UNEXPECTED;
 
     if(index < mConstantBaseIndex)
         return mParent->GetConstant(index, constant);
 
     if(index >= mConstantBaseIndex + 
@@ -300,17 +300,17 @@ xptiInterfaceEntry::GetEntryForParam(uin
         return NS_ERROR_FAILURE;
     }
 
     *entry = theEntry;
     return NS_OK;
 }
 
 nsresult
-xptiInterfaceEntry::GetInfoForParam(uint16 methodIndex,
+xptiInterfaceEntry::GetInfoForParam(uint16_t methodIndex,
                                     const nsXPTParamInfo *param,
                                     nsIInterfaceInfo** info)
 {
     xptiInterfaceEntry* entry;
     nsresult rv = GetEntryForParam(methodIndex, param, &entry);
     if(NS_FAILED(rv))
         return rv;
 
@@ -319,17 +319,17 @@ xptiInterfaceEntry::GetInfoForParam(uint
     if(NS_FAILED(rv))
         return rv;
 
     *info = static_cast<nsIInterfaceInfo*>(theInfo);
     return NS_OK;
 }
 
 nsresult
-xptiInterfaceEntry::GetIIDForParam(uint16 methodIndex,
+xptiInterfaceEntry::GetIIDForParam(uint16_t methodIndex,
                                    const nsXPTParamInfo* param, nsIID** iid)
 {
     xptiInterfaceEntry* entry;
     nsresult rv = GetEntryForParam(methodIndex, param, &entry);
     if(NS_FAILED(rv))
         return rv;
     return entry->GetIID(iid);
 }
@@ -345,41 +345,41 @@ xptiInterfaceEntry::GetIIDForParamNoAllo
         return rv;
     *iid = entry->mIID;    
     return NS_OK;
 }
 
 // this is a private helper
 nsresult
 xptiInterfaceEntry::GetTypeInArray(const nsXPTParamInfo* param,
-                                  uint16 dimension,
+                                  uint16_t dimension,
                                   const XPTTypeDescriptor** type)
 {
     NS_ASSERTION(IsFullyResolved(), "bad state");
 
     const XPTTypeDescriptor *td = &param->type;
     const XPTTypeDescriptor *additional_types =
                 mDescriptor->additional_types;
 
-    for (uint16 i = 0; i < dimension; i++) {
+    for (uint16_t i = 0; i < dimension; i++) {
         if(XPT_TDP_TAG(td->prefix) != TD_ARRAY) {
             NS_ERROR("bad dimension");
             return NS_ERROR_INVALID_ARG;
         }
         td = &additional_types[td->type.additional_type];
     }
 
     *type = td;
     return NS_OK;
 }
 
 nsresult
-xptiInterfaceEntry::GetTypeForParam(uint16 methodIndex,
+xptiInterfaceEntry::GetTypeForParam(uint16_t methodIndex,
                                     const nsXPTParamInfo* param,
-                                    uint16 dimension,
+                                    uint16_t dimension,
                                     nsXPTType* type)
 {
     if(!EnsureResolved())
         return NS_ERROR_UNEXPECTED;
 
     if(methodIndex < mMethodBaseIndex)
         return mParent->
             GetTypeForParam(methodIndex, param, dimension, type);
@@ -401,20 +401,20 @@ xptiInterfaceEntry::GetTypeForParam(uint
     else
         td = &param->type;
 
     *type = nsXPTType(td->prefix);
     return NS_OK;
 }
 
 nsresult
-xptiInterfaceEntry::GetSizeIsArgNumberForParam(uint16 methodIndex,
+xptiInterfaceEntry::GetSizeIsArgNumberForParam(uint16_t methodIndex,
                                                const nsXPTParamInfo* param,
-                                               uint16 dimension,
-                                               uint8* argnum)
+                                               uint16_t dimension,
+                                               uint8_t* argnum)
 {
     if(!EnsureResolved())
         return NS_ERROR_UNEXPECTED;
 
     if(methodIndex < mMethodBaseIndex)
         return mParent->
             GetSizeIsArgNumberForParam(methodIndex, param, dimension, argnum);
 
@@ -446,19 +446,19 @@ xptiInterfaceEntry::GetSizeIsArgNumberFo
         return NS_ERROR_INVALID_ARG;
     }
 
     *argnum = td->argnum;
     return NS_OK;
 }
 
 nsresult
-xptiInterfaceEntry::GetInterfaceIsArgNumberForParam(uint16 methodIndex,
+xptiInterfaceEntry::GetInterfaceIsArgNumberForParam(uint16_t methodIndex,
                                                     const nsXPTParamInfo* param,
-                                                    uint8* argnum)
+                                                    uint8_t* argnum)
 {
     if(!EnsureResolved())
         return NS_ERROR_UNEXPECTED;
 
     if(methodIndex < mMethodBaseIndex)
         return mParent->
             GetInterfaceIsArgNumberForParam(methodIndex, param, argnum);
 
--- a/xpcom/reflect/xptinfo/tests/TestInterfaceInfo.cpp
+++ b/xpcom/reflect/xptinfo/tests/TestInterfaceInfo.cpp
@@ -71,17 +71,17 @@ int main (int argc, char **argv) {
 #endif
 
     // XXX: nsIServiceManager is no more; what do we test with?
     if (info5 == NULL) {
         fprintf(stderr, "\nNo nsIComponentManager; cannot continue.\n");
         return 1;
     }
 
-    uint16 methodcount;
+    uint16_t methodcount;
     info5->GetMethodCount(&methodcount);
     const nsXPTMethodInfo *mi;
     for (i = 0; i < methodcount; i++) {
         info5->GetMethodInfo(i, &mi);
         fprintf(stderr, "method %d, name %s\n", i, mi->GetName());
     }
 
     // 4 is getServiceByContractID, which has juicy params.
@@ -100,17 +100,17 @@ int main (int argc, char **argv) {
     fprintf(stderr, "\nNow check the last param\n");
     const nsXPTParamInfo& param3 = mi->GetParam(3);
 
     if (param3.GetType().TagPart() != nsXPTType::T_INTERFACE_IS) {
         fprintf(stderr, "Param 3 is not type interface is\n");
         // Not returning an error, because this could legitamately change
     }
     // lets see what arg this refers to
-    uint8 argnum;
+    uint8_t argnum;
     info5->GetInterfaceIsArgNumberForParam(6, &param3, &argnum);
     fprintf(stderr, "param 3 referrs to param %d of method 6 - createInstanceByContractID\n", (uint32_t)argnum);
     // Get the type of the parameter referred to
     const nsXPTParamInfo& arg_param = mi->GetParam(argnum);
     const nsXPTType& arg_type = arg_param.GetType();
     // Check to make sure it refers to the proper param
     if(!arg_type.IsPointer() || arg_type.TagPart() != nsXPTType::T_IID) {
         fprintf(stderr, "Param 3 of method 6 refers to a non IID parameter\n"); 
--- a/xpcom/string/src/nsUTF8UtilsSSE2.cpp
+++ b/xpcom/string/src/nsUTF8UtilsSSE2.cpp
@@ -32,19 +32,19 @@ LossyConvertEncoding16to8::write_sse2(co
 
     __m128i source3 = _mm_load_si128(reinterpret_cast<const __m128i*>(aSource + i + 16));
     source3 = _mm_and_si128(source3, vectmask);
 
     __m128i source4 = _mm_load_si128(reinterpret_cast<const __m128i*>(aSource + i + 24));
     source4 = _mm_and_si128(source4, vectmask);
 
 
-    // Pack the source data.  SSE2 views this as a saturating uint16 to
-    // uint8 conversion, but since we masked off the high-order byte of every
-    // uint16, we're really just grabbing the low-order bytes of source1 and
+    // Pack the source data.  SSE2 views this as a saturating uint16_t to
+    // uint8_t conversion, but since we masked off the high-order byte of every
+    // uint16_t, we're really just grabbing the low-order bytes of source1 and
     // source2.
     __m128i packed1 = _mm_packus_epi16(source1, source2);
     __m128i packed2 = _mm_packus_epi16(source3, source4);
 
     // This store needs to be unaligned since there's no guarantee that the
     // alignment we did above for the source will align the destination.
     _mm_storeu_si128(reinterpret_cast<__m128i*>(dest + i),      packed1);
     _mm_storeu_si128(reinterpret_cast<__m128i*>(dest + i + 16), packed2);
--- a/xpcom/typelib/xpt/public/xpt_struct.h
+++ b/xpcom/typelib/xpt/public/xpt_struct.h
@@ -371,22 +371,22 @@ struct XPTTypeDescriptor {
 
 /*
  * A ConstDescriptor is a variable-size record that records the name and 
  * value of a scoped interface constant. 
  *
  * The types of the method parameter are restricted to the following subset 
  * of TypeDescriptors: 
  *
- * int8, uint8, int16, uint16, int32, uint32, 
- * int64, uint64, wchar_t, char, string
+ * int8_t, uint8_t, int16_t, uint16_t, int32_t, uint32_t, 
+ * int64_t, uint64_t, wchar_t, char, string
  * 
  * The type (and thus the size) of the value record is determined by the 
  * contents of the associated TypeDescriptor record. For instance, if type 
- * corresponds to int16, then value is a two-byte record consisting of a 
+ * corresponds to int16_t, then value is a two-byte record consisting of a 
  * 16-bit signed integer.  For a ConstDescriptor type of string, the value 
  * record is of type String*, i.e. an offset within the data pool to a 
  * String record containing the constant string.
  */
 union XPTConstValue {
     int8_t    i8;
     uint8_t   ui8; 
     int16_t   i16; 
--- a/xpcom/typelib/xpt/tests/PrimitiveTest.c
+++ b/xpcom/typelib/xpt/tests/PrimitiveTest.c
@@ -24,19 +24,19 @@
   }
 
 #define TRY(msg, cond)		TRY_(msg, cond, 0)
 #define TRY_Q(msg, cond)	TRY_(msg, cond, 1);
 
 XPTString in_str = { 4, "bazz" };
 
 struct TestData {
-    uint32	bit32;
-    uint16      bit16;
-    uint8       bit8[2];
+    uint32_t	bit32;
+    uint16_t      bit16;
+    uint8_t       bit8[2];
     char	*cstr;
     XPTString   *str;
 } input = { 0xdeadbeef, 0xcafe, {0xba, 0xbe}, "foobar", &in_str},
   output = {0, 0, {0, 0}, NULL, NULL };
 
 void
 dump_struct(char *label, struct TestData *str)
 {
@@ -59,17 +59,17 @@ XDR(XPTArena *arena, XPTCursor *cursor, 
 
 int
 main(int argc, char **argv)
 {
     XPTArena *arena;
     XPTState *state;
     XPTCursor curs, *cursor = &curs;
     char *header, *data, *whole;
-    uint32 hlen, dlen, i;
+    uint32_t hlen, dlen, i;
 
     TRY("XPT_NewArena", (arena = XPT_NewArena(1024, sizeof(double), "main")));
     
     TRY("NewState (ENCODE)", (state = XPT_NewXDRState(XPT_ENCODE, NULL, 0)));
 
     XPT_SetDataOffset(state, sizeof input);
 
     TRY("MakeCursor", XPT_MakeCursor(state, XPT_HEADER, sizeof input, cursor));
@@ -79,26 +79,26 @@ main(int argc, char **argv)
     if (XDR(arena, cursor, &input))
 	return 1;
 
     fprintf(stderr, "ENCODE successful\n");
     XPT_GetXDRData(state, XPT_HEADER, &header, &hlen);
     fprintf(stderr, "XDR header %d bytes at %p:",
 	    hlen, header);
     for (i = 0; i < hlen; i++)
-	fprintf(stderr, "%c%02x", i ? ',' : ' ', (uint8)header[i]);
+	fprintf(stderr, "%c%02x", i ? ',' : ' ', (uint8_t)header[i]);
     fprintf(stderr, "\n");
 
     XPT_GetXDRData(state, XPT_DATA, &data, &dlen);
 
     fprintf(stderr, "XDR data %d bytes at %p:",
 	    dlen, data);
     for (i = 0; i < dlen; i++)
-	fprintf(stderr, "%c%02x/%c", i ? ',' : ' ', (uint8)data[i],
-		(uint8)data[i]);
+	fprintf(stderr, "%c%02x/%c", i ? ',' : ' ', (uint8_t)data[i],
+		(uint8_t)data[i]);
     fprintf(stderr, "\n");
 
     whole = malloc(dlen + hlen);
     if (!whole) {
 	fprintf(stderr, "malloc %d failed!\n", dlen + hlen);
 	return 1;
     }
 
--- a/xpcom/typelib/xpt/tests/SimpleTypeLib.c
+++ b/xpcom/typelib/xpt/tests/SimpleTypeLib.c
@@ -43,17 +43,17 @@ main(int argc, char **argv)
     XPTAnnotation *ann;
     XPTInterfaceDescriptor *id;
     XPTMethodDescriptor *meth;
 
     XPTState *state;
     XPTCursor curs, *cursor = &curs;
     char *data, *head;
     FILE *out;
-    uint32 len, header_sz;
+    uint32_t len, header_sz;
 
     PRBool ok;
 
     td_void.prefix.flags = TD_VOID;
 
     if (argc != 2) {
 	fprintf(stderr, "Usage: %s <filename.xpt>\n"
 		"       Creates a simple typelib file.\n", argv[0]);
@@ -86,17 +86,17 @@ main(int argc, char **argv)
 
     /* void method1(void) */
     meth = &id->method_descriptors[0];
     ok = XPT_FillMethodDescriptor(arena, meth, 0, "method1", 0);
     TRY("FillMethodDescriptor", ok);
     meth->result->flags = 0;
     meth->result->type.prefix.flags = TD_VOID;
 
-    /* wstring method2(in uint32, in bool) */
+    /* wstring method2(in uint32_t, in bool) */
     meth = &id->method_descriptors[1];
     ok = XPT_FillMethodDescriptor(arena, meth, 0, "method2", 2);
     TRY("FillMethodDescriptor", ok);
 
     meth->result->flags = 0;
     meth->result->type.prefix.flags = TD_PSTRING | XPT_TDP_POINTER;
     meth->params[0].type.prefix.flags = TD_UINT32;
     meth->params[0].flags = XPT_PD_IN;