Bug 1131348 - Use fallible Append in content serializers. r=smaug, r=nfroyd, a=sledru
authorWilliam Chen <wchen@mozilla.com>
Tue, 17 Mar 2015 01:55:22 -0700
changeset 257916 d6d3d4e918ebffa236ea3bec7119c1e4a4d31675
parent 257915 04dc5ff4b2a9ed5033df3535d5eeae6ce006ad79
child 257917 aa0d8e209af65056db2e423c7ae4ba3233d2ebf8
push id4610
push userjlund@mozilla.com
push dateMon, 30 Mar 2015 18:32:55 +0000
treeherdermozilla-beta@4df54044d9ef [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewerssmaug, nfroyd, sledru
bugs1131348
milestone38.0a2
Bug 1131348 - Use fallible Append in content serializers. r=smaug, r=nfroyd, a=sledru
dom/base/nsHTMLContentSerializer.cpp
dom/base/nsHTMLContentSerializer.h
dom/base/nsXHTMLContentSerializer.cpp
dom/base/nsXHTMLContentSerializer.h
dom/base/nsXMLContentSerializer.cpp
dom/base/nsXMLContentSerializer.h
xpcom/string/nsReadableUtils.cpp
xpcom/string/nsReadableUtils.h
xpcom/string/nsTSubstring.cpp
xpcom/string/nsTSubstring.h
--- a/dom/base/nsHTMLContentSerializer.cpp
+++ b/dom/base/nsHTMLContentSerializer.cpp
@@ -62,28 +62,28 @@ nsHTMLContentSerializer::~nsHTMLContentS
 
 NS_IMETHODIMP
 nsHTMLContentSerializer::AppendDocumentStart(nsIDocument *aDocument,
                                              nsAString& aStr)
 {
   return NS_OK;
 }
 
-void 
+bool
 nsHTMLContentSerializer::SerializeHTMLAttributes(nsIContent* aContent,
                                                  nsIContent *aOriginalElement,
                                                  nsAString& aTagPrefix,
                                                  const nsAString& aTagNamespaceURI,
                                                  nsIAtom* aTagName,
                                                  int32_t aNamespace,
                                                  nsAString& aStr)
 {
   int32_t count = aContent->GetAttrCount();
   if (!count)
-    return;
+    return true;
 
   nsresult rv;
   nsAutoString valueStr;
   NS_NAMED_LITERAL_STRING(_mozStr, "_moz");
 
   for (int32_t index = count; index > 0;) {
     --index;
     const nsAttrName* name = aContent->GetAttrNameAt(index);
@@ -164,74 +164,82 @@ nsHTMLContentSerializer::SerializeHTMLAt
 
     // Expand shorthand attribute.
     if (aNamespace == kNameSpaceID_XHTML &&
         namespaceID == kNameSpaceID_None &&
         IsShorthandAttr(attrName, aTagName) &&
         valueStr.IsEmpty()) {
       valueStr = nameStr;
     }
-    SerializeAttr(prefix, nameStr, valueStr, aStr, !isJS);
+    NS_ENSURE_TRUE(SerializeAttr(prefix, nameStr, valueStr,
+                                 aStr, !isJS), false);
   }
+
+  return true;
 }
 
 NS_IMETHODIMP
 nsHTMLContentSerializer::AppendElementStart(Element* aElement,
                                             Element* aOriginalElement,
                                             nsAString& aStr)
 {
   NS_ENSURE_ARG(aElement);
 
   nsIContent* content = aElement;
 
   bool forceFormat = false;
-  if (!CheckElementStart(content, forceFormat, aStr)) {
-    return NS_OK;
+  nsresult rv = NS_OK;
+  if (!CheckElementStart(content, forceFormat, aStr, rv)) {
+    return rv;
   }
 
+  NS_ENSURE_SUCCESS(rv, rv);
+
   nsIAtom *name = content->Tag();
   int32_t ns = content->GetNameSpaceID();
 
   bool lineBreakBeforeOpen = LineBreakBeforeOpen(ns, name);
 
   if ((mDoFormat || forceFormat) && !mDoRaw && !PreLevel()) {
     if (mColPos && lineBreakBeforeOpen) {
-      AppendNewLineToString(aStr);
+      NS_ENSURE_TRUE(AppendNewLineToString(aStr), NS_ERROR_OUT_OF_MEMORY);
     }
     else {
-      MaybeAddNewlineForRootNode(aStr);
+      NS_ENSURE_TRUE(MaybeAddNewlineForRootNode(aStr), NS_ERROR_OUT_OF_MEMORY);
     }
     if (!mColPos) {
-      AppendIndentation(aStr);
+      NS_ENSURE_TRUE(AppendIndentation(aStr), NS_ERROR_OUT_OF_MEMORY);
     }
     else if (mAddSpace) {
-      AppendToString(char16_t(' '), aStr);
+      bool result = AppendToString(char16_t(' '), aStr);
       mAddSpace = false;
+      NS_ENSURE_TRUE(result, NS_ERROR_OUT_OF_MEMORY);
     }
   }
   else if (mAddSpace) {
-    AppendToString(char16_t(' '), aStr);
+    bool result = AppendToString(char16_t(' '), aStr);
     mAddSpace = false;
+    NS_ENSURE_TRUE(result, NS_ERROR_OUT_OF_MEMORY);
   }
   else {
-    MaybeAddNewlineForRootNode(aStr);
+    NS_ENSURE_TRUE(MaybeAddNewlineForRootNode(aStr), NS_ERROR_OUT_OF_MEMORY);
   }
   // Always reset to avoid false newlines in case MaybeAddNewlineForRootNode wasn't
   // called
   mAddNewlineForRootNode = false;
-  
-  AppendToString(kLessThan, aStr);
 
-  AppendToString(nsDependentAtomString(name), aStr);
+  NS_ENSURE_TRUE(AppendToString(kLessThan, aStr), NS_ERROR_OUT_OF_MEMORY);
+
+  NS_ENSURE_TRUE(AppendToString(nsDependentAtomString(name), aStr), NS_ERROR_OUT_OF_MEMORY);
 
   MaybeEnterInPreContent(content);
 
   // for block elements, we increase the indentation
   if ((mDoFormat || forceFormat) && !mDoRaw && !PreLevel())
-    IncrIndentation(name);
+    NS_ENSURE_TRUE(IncrIndentation(name), NS_ERROR_OUT_OF_MEMORY);
 
   // Need to keep track of OL and LI elements in order to get ordinal number 
   // for the LI.
   if (mIsCopying && name == nsGkAtoms::ol && ns == kNameSpaceID_XHTML){
     // We are copying and current node is an OL;
     // Store its start attribute value in olState->startVal.
     nsAutoString start;
     int32_t startAttrVal = 0;
@@ -250,47 +258,47 @@ nsHTMLContentSerializer::AppendElementSt
     }
     mOLStateStack.AppendElement(olState(startAttrVal, true));
   }
 
   if (mIsCopying && name == nsGkAtoms::li && ns == kNameSpaceID_XHTML) {
     mIsFirstChildOfOL = IsFirstChildOfOL(aOriginalElement);
     if (mIsFirstChildOfOL){
       // If OL is parent of this LI, serialize attributes in different manner.
-      SerializeLIValueAttribute(aElement, aStr);
+      NS_ENSURE_TRUE(SerializeLIValueAttribute(aElement, aStr), NS_ERROR_OUT_OF_MEMORY);
     }
   }
 
   // Even LI passed above have to go through this 
   // for serializing attributes other than "value".
   nsAutoString dummyPrefix;
-  SerializeHTMLAttributes(content,
-                          aOriginalElement,
-                          dummyPrefix,
-                          EmptyString(),
-                          name,
-                          ns,
-                          aStr);
+  NS_ENSURE_TRUE(SerializeHTMLAttributes(content,
+                                         aOriginalElement,
+                                         dummyPrefix,
+                                         EmptyString(),
+                                         name,
+                                         ns,
+                                         aStr), NS_ERROR_OUT_OF_MEMORY);
 
-  AppendToString(kGreaterThan, aStr);
+  NS_ENSURE_TRUE(AppendToString(kGreaterThan, aStr), NS_ERROR_OUT_OF_MEMORY);
 
   if (ns == kNameSpaceID_XHTML &&
       (name == nsGkAtoms::script ||
        name == nsGkAtoms::style ||
        name == nsGkAtoms::noscript ||
        name == nsGkAtoms::noframes)) {
     ++mDisableEntityEncoding;
   }
 
   if ((mDoFormat || forceFormat) && !mDoRaw && !PreLevel() &&
     LineBreakAfterOpen(ns, name)) {
-    AppendNewLineToString(aStr);
+    NS_ENSURE_TRUE(AppendNewLineToString(aStr), NS_ERROR_OUT_OF_MEMORY);
   }
 
-  AfterElementStart(content, aOriginalElement, aStr);
+  NS_ENSURE_TRUE(AfterElementStart(content, aOriginalElement, aStr), NS_ERROR_OUT_OF_MEMORY);
 
   return NS_OK;
 }
   
 NS_IMETHODIMP 
 nsHTMLContentSerializer::AppendElementEnd(Element* aElement,
                                           nsAString& aStr)
 {
@@ -351,40 +359,42 @@ nsHTMLContentSerializer::AppendElementEn
     }
   }
 
   if ((mDoFormat || forceFormat) && !mDoRaw && !PreLevel()) {
 
     bool lineBreakBeforeClose = LineBreakBeforeClose(ns, name);
 
     if (mColPos && lineBreakBeforeClose) {
-      AppendNewLineToString(aStr);
+      NS_ENSURE_TRUE(AppendNewLineToString(aStr), NS_ERROR_OUT_OF_MEMORY);
     }
     if (!mColPos) {
-      AppendIndentation(aStr);
+      NS_ENSURE_TRUE(AppendIndentation(aStr), NS_ERROR_OUT_OF_MEMORY);
     }
     else if (mAddSpace) {
-      AppendToString(char16_t(' '), aStr);
+      bool result = AppendToString(char16_t(' '), aStr);
       mAddSpace = false;
+      NS_ENSURE_TRUE(result, NS_ERROR_OUT_OF_MEMORY);
     }
   }
   else if (mAddSpace) {
-    AppendToString(char16_t(' '), aStr);
+    bool result = AppendToString(char16_t(' '), aStr);
     mAddSpace = false;
+    NS_ENSURE_TRUE(result, NS_ERROR_OUT_OF_MEMORY);
   }
 
-  AppendToString(kEndTag, aStr);
-  AppendToString(nsDependentAtomString(name), aStr);
-  AppendToString(kGreaterThan, aStr);
+  NS_ENSURE_TRUE(AppendToString(kEndTag, aStr), NS_ERROR_OUT_OF_MEMORY);
+  NS_ENSURE_TRUE(AppendToString(nsDependentAtomString(name), aStr), NS_ERROR_OUT_OF_MEMORY);
+  NS_ENSURE_TRUE(AppendToString(kGreaterThan, aStr), NS_ERROR_OUT_OF_MEMORY);
 
   MaybeLeaveFromPreContent(content);
 
   if ((mDoFormat || forceFormat)&& !mDoRaw  && !PreLevel()
       && LineBreakAfterClose(ns, name)) {
-    AppendNewLineToString(aStr);
+    NS_ENSURE_TRUE(AppendNewLineToString(aStr), NS_ERROR_OUT_OF_MEMORY);
   }
   else {
     MaybeFlagNewlineForRootNode(aElement);
   }
 
   if (name == nsGkAtoms::body && ns == kNameSpaceID_XHTML) {
     --mInBody;
   }
@@ -446,27 +456,26 @@ uint32_t FindNextBasicEntity(const nsASt
     if (val <= kValNBSP && aEntityTable[val]) {
       *aEntity = aEntityTable[val];
       return aIndex;
     }
   }
   return aIndex;
 }
 
-void
+bool
 nsHTMLContentSerializer::AppendAndTranslateEntities(const nsAString& aStr,
                                                      nsAString& aOutputStr)
 {
   if (mBodyOnly && !mInBody) {
-    return;
+    return true;
   }
 
   if (mDisableEntityEncoding) {
-    aOutputStr.Append(aStr);
-    return;
+    return aOutputStr.Append(aStr, mozilla::fallible);
   }
 
   bool nonBasicEntities =
     !!(mFlags & (nsIDocumentEncoder::OutputEncodeLatin1Entities |
                  nsIDocumentEncoder::OutputEncodeHTMLEntities   |
                  nsIDocumentEncoder::OutputEncodeW3CEntities));
 
   if (!nonBasicEntities &&
@@ -474,30 +483,31 @@ nsHTMLContentSerializer::AppendAndTransl
     const char **entityTable = mInAttribute ? kAttrEntities : kEntities;
     uint32_t start = 0;
     const uint32_t len = aStr.Length();
     for (uint32_t i = 0; i < len; ++i) {
       const char* entity = nullptr;
       i = FindNextBasicEntity(aStr, len, i, entityTable, &entity);
       uint32_t normalTextLen = i - start; 
       if (normalTextLen) {
-        aOutputStr.Append(Substring(aStr, start, normalTextLen));
+        NS_ENSURE_TRUE(aOutputStr.Append(Substring(aStr, start, normalTextLen),
+                                         mozilla::fallible), false);
       }
       if (entity) {
-        aOutputStr.AppendASCII(entity);
+        NS_ENSURE_TRUE(aOutputStr.AppendASCII(entity, mozilla::fallible), false);
         start = i + 1;
       }
     }
-    return;
+    return true;
   } else if (nonBasicEntities) {
     nsIParserService* parserService = nsContentUtils::GetParserService();
 
     if (!parserService) {
       NS_ERROR("Can't get parser service");
-      return;
+      return true;
     }
 
     nsReadingIterator<char16_t> done_reading;
     aStr.EndReading(done_reading);
 
     // for each chunk of |aString|...
     uint32_t advanceLength = 0;
     nsReadingIterator<char16_t> iter;
@@ -558,30 +568,34 @@ nsHTMLContentSerializer::AppendAndTransl
                                 nsIEntityConverter::entityW3C, 
                                 &fullEntityText))) {
             lengthReplaced = 1;
             break;
           }
         }
       }
 
-      aOutputStr.Append(fragmentStart, advanceLength);
+      bool result = aOutputStr.Append(fragmentStart, advanceLength, mozilla::fallible);
       if (entityText) {
-        aOutputStr.Append(char16_t('&'));
-        AppendASCIItoUTF16(entityText, aOutputStr);
-        aOutputStr.Append(char16_t(';'));
+        NS_ENSURE_TRUE(aOutputStr.Append(char16_t('&'), mozilla::fallible), false);
+        NS_ENSURE_TRUE(AppendASCIItoUTF16(entityText, aOutputStr, mozilla::fallible), false);
+        NS_ENSURE_TRUE(aOutputStr.Append(char16_t(';'), mozilla::fallible), false);
         advanceLength++;
       }
       else if (fullConstEntityText) {
-        aOutputStr.AppendASCII(fullConstEntityText);
+        NS_ENSURE_TRUE(aOutputStr.AppendASCII(fullConstEntityText, mozilla::fallible), false);
         ++advanceLength;
       }
       // if it comes from nsIEntityConverter, it already has '&' and ';'
       else if (fullEntityText) {
-        AppendASCIItoUTF16(fullEntityText, aOutputStr);
+        bool ok = AppendASCIItoUTF16(fullEntityText, aOutputStr, mozilla::fallible);
         nsMemory::Free(fullEntityText);
         advanceLength += lengthReplaced;
+        NS_ENSURE_TRUE(ok, false);
       }
+      NS_ENSURE_TRUE(result, false);
     }
   } else {
-    nsXMLContentSerializer::AppendAndTranslateEntities(aStr, aOutputStr);
+    NS_ENSURE_TRUE(nsXMLContentSerializer::AppendAndTranslateEntities(aStr, aOutputStr), false);
   }
+
+  return true;
 }
--- a/dom/base/nsHTMLContentSerializer.h
+++ b/dom/base/nsHTMLContentSerializer.h
@@ -31,25 +31,27 @@ class nsHTMLContentSerializer : public n
 
   NS_IMETHOD AppendElementEnd(mozilla::dom::Element* aElement,
                               nsAString& aStr) MOZ_OVERRIDE;
 
   NS_IMETHOD AppendDocumentStart(nsIDocument *aDocument,
                                  nsAString& aStr) MOZ_OVERRIDE;
  protected:
 
-  virtual void SerializeHTMLAttributes(nsIContent* aContent,
+  NS_WARN_UNUSED_RESULT
+  virtual bool SerializeHTMLAttributes(nsIContent* aContent,
                                        nsIContent *aOriginalElement,
                                        nsAString& aTagPrefix,
                                        const nsAString& aTagNamespaceURI,
                                        nsIAtom* aTagName,
                                        int32_t aNamespace,
                                        nsAString& aStr);
 
-  virtual void AppendAndTranslateEntities(const nsAString& aStr,
+  NS_WARN_UNUSED_RESULT
+  virtual bool AppendAndTranslateEntities(const nsAString& aStr,
                                           nsAString& aOutputStr) MOZ_OVERRIDE;
 
 };
 
 nsresult
 NS_NewHTMLContentSerializer(nsIContentSerializer** aSerializer);
 
 #endif
--- a/dom/base/nsXHTMLContentSerializer.cpp
+++ b/dom/base/nsXHTMLContentSerializer.cpp
@@ -129,34 +129,35 @@ nsXHTMLContentSerializer::AppendText(nsI
   nsAutoString data;
   nsresult rv;
 
   rv = AppendTextData(aText, aStartOffset, aEndOffset, data, true);
   if (NS_FAILED(rv))
     return NS_ERROR_FAILURE;
 
   if (mDoRaw || PreLevel() > 0) {
-    AppendToStringConvertLF(data, aStr);
+    NS_ENSURE_TRUE(AppendToStringConvertLF(data, aStr), NS_ERROR_OUT_OF_MEMORY);
   }
   else if (mDoFormat) {
-    AppendToStringFormatedWrapped(data, aStr);
+    NS_ENSURE_TRUE(AppendToStringFormatedWrapped(data, aStr), NS_ERROR_OUT_OF_MEMORY);
   }
   else if (mDoWrap) {
-    AppendToStringWrapped(data, aStr);
+    NS_ENSURE_TRUE(AppendToStringWrapped(data, aStr), NS_ERROR_OUT_OF_MEMORY);
   }
   else {
     int32_t lastNewlineOffset = kNotFound;
     if (HasLongLines(data, lastNewlineOffset)) {
       // We have long lines, rewrap
       mDoWrap = true;
-      AppendToStringWrapped(data, aStr);
+      bool result = AppendToStringWrapped(data, aStr);
       mDoWrap = false;
+      NS_ENSURE_TRUE(result, NS_ERROR_OUT_OF_MEMORY);
     }
     else {
-      AppendToStringConvertLF(data, aStr);
+      NS_ENSURE_TRUE(AppendToStringConvertLF(data, aStr), NS_ERROR_OUT_OF_MEMORY);
     }
   }
 
   return NS_OK;
 }
 
 nsresult
 nsXHTMLContentSerializer::EscapeURI(nsIContent* aContent, const nsAString& aURI, nsAString& aEscapedURI)
@@ -217,17 +218,17 @@ nsXHTMLContentSerializer::EscapeURI(nsIC
       escapedURI.Adopt(nsEscape(NS_ConvertUTF16toUTF8(part).get(), url_Path));
     }
     AppendASCIItoUTF16(escapedURI, aEscapedURI);
   }
 
   return rv;
 }
 
-void
+bool
 nsXHTMLContentSerializer::SerializeAttributes(nsIContent* aContent,
                                               nsIContent *aOriginalElement,
                                               nsAString& aTagPrefix,
                                               const nsAString& aTagNamespaceURI,
                                               nsIAtom* aTagName,
                                               nsAString& aStr,
                                               uint32_t aSkipAttr,
                                               bool aAddNSAttr)
@@ -266,30 +267,34 @@ nsXHTMLContentSerializer::SerializeAttri
       }
       olState state (startAttrVal, true);
       mOLStateStack.AppendElement(state);
     }
     else if (aTagName == nsGkAtoms::li) {
       mIsFirstChildOfOL = IsFirstChildOfOL(aOriginalElement);
       if (mIsFirstChildOfOL) {
         // If OL is parent of this LI, serialize attributes in different manner.
-        SerializeLIValueAttribute(aContent, aStr);
+        NS_ENSURE_TRUE(SerializeLIValueAttribute(aContent, aStr), false);
       }
     }
   }
 
   // If we had to add a new namespace declaration, serialize
   // and push it on the namespace stack
   if (aAddNSAttr) {
     if (aTagPrefix.IsEmpty()) {
       // Serialize default namespace decl
-      SerializeAttr(EmptyString(), xmlnsStr, aTagNamespaceURI, aStr, true);
+      NS_ENSURE_TRUE(SerializeAttr(EmptyString(), xmlnsStr,
+                                   aTagNamespaceURI,
+                                   aStr, true), false);
     } else {
       // Serialize namespace decl
-      SerializeAttr(xmlnsStr, aTagPrefix, aTagNamespaceURI, aStr, true);
+      NS_ENSURE_TRUE(SerializeAttr(xmlnsStr, aTagPrefix,
+                                   aTagNamespaceURI,
+                                   aStr, true), false);
     }
     PushNameSpaceDecl(aTagPrefix, aTagNamespaceURI, aOriginalElement);
   }
 
   NS_NAMED_LITERAL_STRING(_mozStr, "_moz");
 
   count = aContent->GetAttrCount();
 
@@ -390,42 +395,43 @@ nsXHTMLContentSerializer::SerializeAttri
       if (namespaceID == kNameSpaceID_None && IsShorthandAttr(attrName, aTagName) && valueStr.IsEmpty()) {
         valueStr = nameStr;
       }
     }
     else {
       isJS = IsJavaScript(aContent, attrName, namespaceID, valueStr);
     }
 
-    SerializeAttr(prefixStr, nameStr, valueStr, aStr, !isJS);
+    NS_ENSURE_TRUE(SerializeAttr(prefixStr, nameStr, valueStr, aStr, !isJS), false);
 
     if (addNSAttr) {
       NS_ASSERTION(!prefixStr.IsEmpty(),
                    "Namespaced attributes must have a prefix");
-      SerializeAttr(xmlnsStr, prefixStr, uriStr, aStr, true);
+      NS_ENSURE_TRUE(SerializeAttr(xmlnsStr, prefixStr, uriStr, aStr, true), false);
       PushNameSpaceDecl(prefixStr, uriStr, aOriginalElement);
     }
   }
+
+  return true;
 }
 
 
-void 
+bool
 nsXHTMLContentSerializer::AppendEndOfElementStart(nsIContent *aOriginalElement,
                                                   nsIAtom * aName,
                                                   int32_t aNamespaceID,
                                                   nsAString& aStr)
 {
   // this method is not called by nsHTMLContentSerializer
   // so we don't have to check HTML element, just XHTML
   NS_ASSERTION(!mIsHTMLSerializer, "nsHTMLContentSerializer shouldn't call this method !");
 
   if (kNameSpaceID_XHTML != aNamespaceID) {
-    nsXMLContentSerializer::AppendEndOfElementStart(aOriginalElement, aName,
-                                                    aNamespaceID, aStr);
-    return;
+    return nsXMLContentSerializer::AppendEndOfElementStart(aOriginalElement, aName,
+                                                           aNamespaceID, aStr);
   }
 
   nsIContent* content = aOriginalElement;
 
   // for non empty elements, even if they are not a container, we always
   // serialize their content, because the XHTML element could contain non XHTML
   // nodes useful in some context, like in an XSLT stylesheet
   if (HasNoChildren(content)) {
@@ -436,27 +442,26 @@ nsXHTMLContentSerializer::AppendEndOfEle
       bool isContainer;
       parserService->
         IsContainer(parserService->HTMLCaseSensitiveAtomTagToId(aName),
                     isContainer);
       if (!isContainer) {
         // for backward compatibility with HTML 4 user agents
         // only non-container HTML elements can be closed immediatly,
         // and a space is added before />
-        AppendToString(NS_LITERAL_STRING(" />"), aStr);
-        return;
+        return AppendToString(NS_LITERAL_STRING(" />"), aStr);
       }
     }
   }
-  AppendToString(kGreaterThan, aStr);
+  return AppendToString(kGreaterThan, aStr);
 }
 
-void
-nsXHTMLContentSerializer::AfterElementStart(nsIContent * aContent,
-                                            nsIContent *aOriginalElement,
+bool
+nsXHTMLContentSerializer::AfterElementStart(nsIContent* aContent,
+                                            nsIContent* aOriginalElement,
                                             nsAString& aStr)
 {
   nsIAtom *name = aContent->Tag();
   if (aContent->GetNameSpaceID() == kNameSpaceID_XHTML &&
       mRewriteEncodingDeclaration &&
       name == nsGkAtoms::head) {
 
     // Check if there already are any content-type meta children.
@@ -474,30 +479,32 @@ nsXHTMLContentSerializer::AfterElementSt
         if (header.LowerCaseEqualsLiteral("content-type")) {
           hasMeta = true;
           break;
         }
       }
     }
 
     if (!hasMeta) {
-      AppendNewLineToString(aStr);
+      NS_ENSURE_TRUE(AppendNewLineToString(aStr), false);
       if (mDoFormat) {
-        AppendIndentation(aStr);
+        NS_ENSURE_TRUE(AppendIndentation(aStr), false);
       }
-      AppendToString(NS_LITERAL_STRING("<meta http-equiv=\"content-type\""),
-                    aStr);
-      AppendToString(NS_LITERAL_STRING(" content=\"text/html; charset="), aStr);
-      AppendToString(NS_ConvertASCIItoUTF16(mCharset), aStr);
-      if (mIsHTMLSerializer)
-        AppendToString(NS_LITERAL_STRING("\">"), aStr);
-      else
-        AppendToString(NS_LITERAL_STRING("\" />"), aStr);
+      NS_ENSURE_TRUE(AppendToString(NS_LITERAL_STRING("<meta http-equiv=\"content-type\""), aStr), false);
+      NS_ENSURE_TRUE(AppendToString(NS_LITERAL_STRING(" content=\"text/html; charset="), aStr), false);
+      NS_ENSURE_TRUE(AppendToString(NS_ConvertASCIItoUTF16(mCharset), aStr), false);
+      if (mIsHTMLSerializer) {
+        NS_ENSURE_TRUE(AppendToString(NS_LITERAL_STRING("\">"), aStr), false);
+      } else {
+        NS_ENSURE_TRUE(AppendToString(NS_LITERAL_STRING("\" />"), aStr), false);
+      }
     }
   }
+
+  return true;
 }
 
 void
 nsXHTMLContentSerializer::AfterElementEnd(nsIContent * aContent,
                                           nsAString& aStr)
 {
   NS_ASSERTION(!mIsHTMLSerializer, "nsHTMLContentSerializer shouldn't call this method !");
 
@@ -520,32 +527,35 @@ nsXHTMLContentSerializer::AppendDocument
     return nsXMLContentSerializer::AppendDocumentStart(aDocument, aStr);
 
   return NS_OK;
 }
 
 bool
 nsXHTMLContentSerializer::CheckElementStart(nsIContent * aContent,
                                             bool & aForceFormat,
-                                            nsAString& aStr)
+                                            nsAString& aStr,
+                                            nsresult& aResult)
 {
+  aResult = NS_OK;
+
   // The _moz_dirty attribute is emitted by the editor to
   // indicate that this element should be pretty printed
   // even if we're not in pretty printing mode
   aForceFormat = !(mFlags & nsIDocumentEncoder::OutputIgnoreMozDirty) &&
                  aContent->HasAttr(kNameSpaceID_None, nsGkAtoms::mozdirty);
 
   nsIAtom *name = aContent->Tag();
   int32_t namespaceID = aContent->GetNameSpaceID();
 
   if (namespaceID == kNameSpaceID_XHTML) {
     if (name == nsGkAtoms::br &&
         (mFlags & nsIDocumentEncoder::OutputNoFormattingInPre) &&
         PreLevel() > 0) {
-      AppendNewLineToString(aStr);
+      aResult = AppendNewLineToString(aStr) ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
       return false;
     }
 
     if (name == nsGkAtoms::body) {
       ++mInBody;
     }
   }
   return true;
@@ -597,30 +607,29 @@ nsXHTMLContentSerializer::CheckElementEn
     // nsXMLContentSerializer::CheckElementEnd
     return true;
   }
 
   bool dummyFormat;
   return nsXMLContentSerializer::CheckElementEnd(aContent, dummyFormat, aStr);
 }
 
-void
+bool
 nsXHTMLContentSerializer::AppendAndTranslateEntities(const nsAString& aStr,
                                                      nsAString& aOutputStr)
 {
   if (mBodyOnly && !mInBody) {
-    return;
+    return true;
   }
 
   if (mDisableEntityEncoding) {
-    aOutputStr.Append(aStr);
-    return;
+    return aOutputStr.Append(aStr, mozilla::fallible);
   }
- 
-  nsXMLContentSerializer::AppendAndTranslateEntities(aStr, aOutputStr);
+
+  return nsXMLContentSerializer::AppendAndTranslateEntities(aStr, aOutputStr);
 }
 
 bool
 nsXHTMLContentSerializer::IsShorthandAttr(const nsIAtom* aAttrName,
                                           const nsIAtom* aElementName)
 {
   // checked
   if ((aAttrName == nsGkAtoms::checked) &&
@@ -895,17 +904,17 @@ nsXHTMLContentSerializer::IsElementPrefo
                                                          nullptr, nullptr);
   if (styleContext) {
     const nsStyleText* textStyle = styleContext->StyleText();
     return textStyle->WhiteSpaceOrNewlineIsSignificant();
   }
   return false;
 }
 
-void 
+bool
 nsXHTMLContentSerializer::SerializeLIValueAttribute(nsIContent* aElement,
                                                     nsAString& aStr)
 {
   // We are copying and we are at the "first" LI node of OL in selected range.
   // It may not be the first LI child of OL but it's first in the selected range.
   // Note that we get into this condition only once per a OL.
   bool found = false;
   nsCOMPtr<nsIDOMNode> currNode = do_QueryInterface(aElement);
@@ -947,33 +956,37 @@ nsXHTMLContentSerializer::SerializeLIVal
     currNode->GetPreviousSibling(getter_AddRefs(tmp));
     currNode.swap(tmp);
   }
   // If LI was not having "value", Set the "value" attribute for it.
   // Note that We are at the first LI in the selected range of OL.
   if (offset == 0 && found) {
     // offset = 0 => LI itself has the value attribute and we did not need to traverse back.
     // Just serialize value attribute like other tags.
-    SerializeAttr(EmptyString(), NS_LITERAL_STRING("value"), valueStr, aStr, false);
+    NS_ENSURE_TRUE(SerializeAttr(EmptyString(), NS_LITERAL_STRING("value"),
+                                 valueStr, aStr, false), false);
   }
   else if (offset == 1 && !found) {
     /*(offset = 1 && !found) means either LI is the first child node of OL
     and LI is not having "value" attribute.
     In that case we would not like to set "value" attribute to reduce the changes.
     */
     //do nothing...
   }
   else if (offset > 0) {
     // Set value attribute.
     nsAutoString valueStr;
 
     //As serializer needs to use this valueAttr we are creating here, 
     valueStr.AppendInt(startVal + offset);
-    SerializeAttr(EmptyString(), NS_LITERAL_STRING("value"), valueStr, aStr, false);
+    NS_ENSURE_TRUE(SerializeAttr(EmptyString(), NS_LITERAL_STRING("value"),
+                                 valueStr, aStr, false), false);
   }
+
+  return true;
 }
 
 bool
 nsXHTMLContentSerializer::IsFirstChildOfOL(nsIContent* aElement)
 {
   nsCOMPtr<nsIDOMNode> node = do_QueryInterface(aElement);
   nsAutoString parentName;
 
--- a/dom/base/nsXHTMLContentSerializer.h
+++ b/dom/base/nsXHTMLContentSerializer.h
@@ -38,26 +38,29 @@ class nsXHTMLContentSerializer : public 
   NS_IMETHOD AppendDocumentStart(nsIDocument *aDocument,
                                  nsAString& aStr) MOZ_OVERRIDE;
 
  protected:
 
 
   virtual bool CheckElementStart(nsIContent * aContent,
                           bool & aForceFormat,
-                          nsAString& aStr) MOZ_OVERRIDE;
+                          nsAString& aStr,
+                          nsresult& aResult) MOZ_OVERRIDE;
 
-  virtual void AppendEndOfElementStart(nsIContent *aOriginalElement,
+  NS_WARN_UNUSED_RESULT
+  virtual bool AppendEndOfElementStart(nsIContent *aOriginalElement,
                                nsIAtom * aName,
                                int32_t aNamespaceID,
                                nsAString& aStr) MOZ_OVERRIDE;
 
-  virtual void AfterElementStart(nsIContent * aContent,
-                         nsIContent *aOriginalElement,
-                         nsAString& aStr) MOZ_OVERRIDE;
+  NS_WARN_UNUSED_RESULT
+  virtual bool AfterElementStart(nsIContent* aContent,
+                                 nsIContent* aOriginalElement,
+                                 nsAString& aStr) MOZ_OVERRIDE;
 
   virtual bool CheckElementEnd(nsIContent * aContent,
                           bool & aForceFormat,
                           nsAString& aStr) MOZ_OVERRIDE;
 
   virtual void AfterElementEnd(nsIContent * aContent,
                                nsAString& aStr) MOZ_OVERRIDE;
 
@@ -67,33 +70,38 @@ class nsXHTMLContentSerializer : public 
   virtual bool LineBreakAfterClose(int32_t aNamespaceID, nsIAtom* aName) MOZ_OVERRIDE;
 
   bool HasLongLines(const nsString& text, int32_t& aLastNewlineOffset);
 
   // functions to check if we enter in or leave from a preformated content
   virtual void MaybeEnterInPreContent(nsIContent* aNode) MOZ_OVERRIDE;
   virtual void MaybeLeaveFromPreContent(nsIContent* aNode) MOZ_OVERRIDE;
 
-  virtual void SerializeAttributes(nsIContent* aContent,
+  NS_WARN_UNUSED_RESULT
+  virtual bool SerializeAttributes(nsIContent* aContent,
                            nsIContent *aOriginalElement,
                            nsAString& aTagPrefix,
                            const nsAString& aTagNamespaceURI,
                            nsIAtom* aTagName,
                            nsAString& aStr,
                            uint32_t aSkipAttr,
                            bool aAddNSAttr) MOZ_OVERRIDE;
 
   bool IsFirstChildOfOL(nsIContent* aElement);
 
-  void SerializeLIValueAttribute(nsIContent* aElement,
+  NS_WARN_UNUSED_RESULT
+  bool SerializeLIValueAttribute(nsIContent* aElement,
                                  nsAString& aStr);
   bool IsShorthandAttr(const nsIAtom* aAttrName,
                          const nsIAtom* aElementName);
-  virtual void AppendAndTranslateEntities(const nsAString& aStr,
+
+  NS_WARN_UNUSED_RESULT
+  virtual bool AppendAndTranslateEntities(const nsAString& aStr,
                                           nsAString& aOutputStr) MOZ_OVERRIDE;
+
   nsresult EscapeURI(nsIContent* aContent,
                      const nsAString& aURI,
                      nsAString& aEscapedURI);
 
 private:
   bool IsElementPreformatted(nsIContent* aNode);
 
 protected:
--- a/dom/base/nsXMLContentSerializer.cpp
+++ b/dom/base/nsXMLContentSerializer.cpp
@@ -149,28 +149,32 @@ nsXMLContentSerializer::AppendTextData(n
     // XXX Zero is a legal value, maybe non-zero values should be an
     // error.
     return NS_OK;
   }
     
   if (frag->Is2b()) {
     const char16_t *strStart = frag->Get2b() + aStartOffset;
     if (aTranslateEntities) {
-      AppendAndTranslateEntities(Substring(strStart, strStart + length), aStr);
+      NS_ENSURE_TRUE(AppendAndTranslateEntities(Substring(strStart, strStart + length), aStr),
+                     NS_ERROR_OUT_OF_MEMORY);
     }
     else {
-      aStr.Append(Substring(strStart, strStart + length));
+      NS_ENSURE_TRUE(aStr.Append(Substring(strStart, strStart + length), mozilla::fallible),
+                     NS_ERROR_OUT_OF_MEMORY);
     }
   }
   else {
     if (aTranslateEntities) {
-      AppendAndTranslateEntities(NS_ConvertASCIItoUTF16(frag->Get1b()+aStartOffset, length), aStr);
+      NS_ENSURE_TRUE(AppendAndTranslateEntities(NS_ConvertASCIItoUTF16(frag->Get1b()+aStartOffset, length), aStr),
+                     NS_ERROR_OUT_OF_MEMORY);
     }
     else {
-      aStr.Append(NS_ConvertASCIItoUTF16(frag->Get1b()+aStartOffset, length));
+      NS_ENSURE_TRUE(aStr.Append(NS_ConvertASCIItoUTF16(frag->Get1b()+aStartOffset, length), mozilla::fallible),
+                     NS_ERROR_OUT_OF_MEMORY);
     }
   }
 
   return NS_OK;
 }
 
 NS_IMETHODIMP 
 nsXMLContentSerializer::AppendText(nsIContent* aText,
@@ -183,26 +187,26 @@ nsXMLContentSerializer::AppendText(nsICo
   nsAutoString data;
   nsresult rv;
 
   rv = AppendTextData(aText, aStartOffset, aEndOffset, data, true);
   if (NS_FAILED(rv))
     return NS_ERROR_FAILURE;
 
   if (mDoRaw || PreLevel() > 0) {
-    AppendToStringConvertLF(data, aStr);
+    NS_ENSURE_TRUE(AppendToStringConvertLF(data, aStr), NS_ERROR_OUT_OF_MEMORY);
   }
   else if (mDoFormat) {
-    AppendToStringFormatedWrapped(data, aStr);
+    NS_ENSURE_TRUE(AppendToStringFormatedWrapped(data, aStr), NS_ERROR_OUT_OF_MEMORY);
   }
   else if (mDoWrap) {
-    AppendToStringWrapped(data, aStr);
+    NS_ENSURE_TRUE(AppendToStringWrapped(data, aStr), NS_ERROR_OUT_OF_MEMORY);
   }
   else {
-    AppendToStringConvertLF(data, aStr);
+    NS_ENSURE_TRUE(AppendToStringConvertLF(data, aStr), NS_ERROR_OUT_OF_MEMORY);
   }
 
   return NS_OK;
 }
 
 NS_IMETHODIMP 
 nsXMLContentSerializer::AppendCDATASection(nsIContent* aCDATASection,
                                            int32_t aStartOffset,
@@ -210,82 +214,82 @@ nsXMLContentSerializer::AppendCDATASecti
                                            nsAString& aStr)
 {
   NS_ENSURE_ARG(aCDATASection);
   nsresult rv;
 
   NS_NAMED_LITERAL_STRING(cdata , "<![CDATA[");
 
   if (mDoRaw || PreLevel() > 0) {
-    AppendToString(cdata, aStr);
+    NS_ENSURE_TRUE(AppendToString(cdata, aStr), NS_ERROR_OUT_OF_MEMORY);
   }
   else if (mDoFormat) {
-    AppendToStringFormatedWrapped(cdata, aStr);
+    NS_ENSURE_TRUE(AppendToStringFormatedWrapped(cdata, aStr), NS_ERROR_OUT_OF_MEMORY);
   }
   else if (mDoWrap) {
-    AppendToStringWrapped(cdata, aStr);
+    NS_ENSURE_TRUE(AppendToStringWrapped(cdata, aStr), NS_ERROR_OUT_OF_MEMORY);
   }
   else {
-    AppendToString(cdata, aStr);
+    NS_ENSURE_TRUE(AppendToString(cdata, aStr), NS_ERROR_OUT_OF_MEMORY);
   }
 
   nsAutoString data;
   rv = AppendTextData(aCDATASection, aStartOffset, aEndOffset, data, false);
   if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
 
-  AppendToStringConvertLF(data, aStr);
+  NS_ENSURE_TRUE(AppendToStringConvertLF(data, aStr), NS_ERROR_OUT_OF_MEMORY);
 
-  AppendToString(NS_LITERAL_STRING("]]>"), aStr);
+  NS_ENSURE_TRUE(AppendToString(NS_LITERAL_STRING("]]>"), aStr), NS_ERROR_OUT_OF_MEMORY);
 
   return NS_OK;
 }
 
 NS_IMETHODIMP 
 nsXMLContentSerializer::AppendProcessingInstruction(nsIContent* aPI,
                                                     int32_t aStartOffset,
                                                     int32_t aEndOffset,
                                                     nsAString& aStr)
 {
   nsCOMPtr<nsIDOMProcessingInstruction> pi = do_QueryInterface(aPI);
   NS_ENSURE_ARG(pi);
   nsresult rv;
   nsAutoString target, data, start;
 
-  MaybeAddNewlineForRootNode(aStr);
+  NS_ENSURE_TRUE(MaybeAddNewlineForRootNode(aStr), NS_ERROR_OUT_OF_MEMORY);
 
   rv = pi->GetTarget(target);
   if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
 
   rv = pi->GetData(data);
   if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
 
-  start.AppendLiteral("<?");
-  start.Append(target);
+  NS_ENSURE_TRUE(start.AppendLiteral("<?", mozilla::fallible), NS_ERROR_OUT_OF_MEMORY);
+  NS_ENSURE_TRUE(start.Append(target, mozilla::fallible), NS_ERROR_OUT_OF_MEMORY);
 
   if (mDoRaw || PreLevel() > 0) {
-    AppendToString(start, aStr);
+    NS_ENSURE_TRUE(AppendToString(start, aStr), NS_ERROR_OUT_OF_MEMORY);
   }
   else if (mDoFormat) {
     if (mAddSpace) {
-      AppendNewLineToString(aStr);
+      NS_ENSURE_TRUE(AppendNewLineToString(aStr), NS_ERROR_OUT_OF_MEMORY);
     }
-    AppendToStringFormatedWrapped(start, aStr);
+    NS_ENSURE_TRUE(AppendToStringFormatedWrapped(start, aStr), NS_ERROR_OUT_OF_MEMORY);
   }
   else if (mDoWrap) {
-    AppendToStringWrapped(start, aStr);
+    NS_ENSURE_TRUE(AppendToStringWrapped(start, aStr), NS_ERROR_OUT_OF_MEMORY);
   }
   else {
-    AppendToString(start, aStr);
+    NS_ENSURE_TRUE(AppendToString(start, aStr), NS_ERROR_OUT_OF_MEMORY);
   }
 
   if (!data.IsEmpty()) {
-    AppendToString(char16_t(' '), aStr);
-    AppendToStringConvertLF(data, aStr);
+    NS_ENSURE_TRUE(AppendToString(char16_t(' '), aStr), NS_ERROR_OUT_OF_MEMORY);
+    NS_ENSURE_TRUE(AppendToStringConvertLF(data, aStr), NS_ERROR_OUT_OF_MEMORY);
   }
-  AppendToString(NS_LITERAL_STRING("?>"), aStr);
+  NS_ENSURE_TRUE(AppendToString(NS_LITERAL_STRING("?>"), aStr), NS_ERROR_OUT_OF_MEMORY);
 
   MaybeFlagNewlineForRootNode(aPI);
 
   return NS_OK;
 }
 
 NS_IMETHODIMP 
 nsXMLContentSerializer::AppendComment(nsIContent* aComment,
@@ -309,40 +313,40 @@ nsXMLContentSerializer::AppendComment(ns
 
     nsAutoString frag;
     if (length > 0) {
       data.Mid(frag, aStartOffset, length);
     }
     data.Assign(frag);
   }
 
-  MaybeAddNewlineForRootNode(aStr);
+  NS_ENSURE_TRUE(MaybeAddNewlineForRootNode(aStr), NS_ERROR_OUT_OF_MEMORY);
 
   NS_NAMED_LITERAL_STRING(startComment, "<!--");
 
   if (mDoRaw || PreLevel() > 0) {
-    AppendToString(startComment, aStr);
+    NS_ENSURE_TRUE(AppendToString(startComment, aStr), NS_ERROR_OUT_OF_MEMORY);
   }
   else if (mDoFormat) {
     if (mAddSpace) {
-      AppendNewLineToString(aStr);
+      NS_ENSURE_TRUE(AppendNewLineToString(aStr), NS_ERROR_OUT_OF_MEMORY);
     }
-    AppendToStringFormatedWrapped(startComment, aStr);
+    NS_ENSURE_TRUE(AppendToStringFormatedWrapped(startComment, aStr), NS_ERROR_OUT_OF_MEMORY);
   }
   else if (mDoWrap) {
-    AppendToStringWrapped(startComment, aStr);
+    NS_ENSURE_TRUE(AppendToStringWrapped(startComment, aStr), NS_ERROR_OUT_OF_MEMORY);
   }
   else {
-    AppendToString(startComment, aStr);
+    NS_ENSURE_TRUE(AppendToString(startComment, aStr), NS_ERROR_OUT_OF_MEMORY);
   }
 
   // Even if mDoformat, we don't format the content because it
   // could have been preformated by the author
-  AppendToStringConvertLF(data, aStr);
-  AppendToString(NS_LITERAL_STRING("-->"), aStr);
+  NS_ENSURE_TRUE(AppendToStringConvertLF(data, aStr), NS_ERROR_OUT_OF_MEMORY);
+  NS_ENSURE_TRUE(AppendToString(NS_LITERAL_STRING("-->"), aStr), NS_ERROR_OUT_OF_MEMORY);
 
   MaybeFlagNewlineForRootNode(aComment);
 
   return NS_OK;
 }
 
 NS_IMETHODIMP 
 nsXMLContentSerializer::AppendDoctype(nsIContent* aDocType,
@@ -357,67 +361,67 @@ nsXMLContentSerializer::AppendDoctype(ns
   if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
   rv = docType->GetPublicId(publicId);
   if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
   rv = docType->GetSystemId(systemId);
   if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
   rv = docType->GetInternalSubset(internalSubset);
   if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
 
-  MaybeAddNewlineForRootNode(aStr);
+  NS_ENSURE_TRUE(MaybeAddNewlineForRootNode(aStr), NS_ERROR_OUT_OF_MEMORY);
 
-  AppendToString(NS_LITERAL_STRING("<!DOCTYPE "), aStr);
-  AppendToString(name, aStr);
+  NS_ENSURE_TRUE(AppendToString(NS_LITERAL_STRING("<!DOCTYPE "), aStr), NS_ERROR_OUT_OF_MEMORY);
+  NS_ENSURE_TRUE(AppendToString(name, aStr), NS_ERROR_OUT_OF_MEMORY);
 
   char16_t quote;
   if (!publicId.IsEmpty()) {
-    AppendToString(NS_LITERAL_STRING(" PUBLIC "), aStr);
+    NS_ENSURE_TRUE(AppendToString(NS_LITERAL_STRING(" PUBLIC "), aStr), NS_ERROR_OUT_OF_MEMORY);
     if (publicId.FindChar(char16_t('"')) == -1) {
       quote = char16_t('"');
     }
     else {
       quote = char16_t('\'');
     }
-    AppendToString(quote, aStr);
-    AppendToString(publicId, aStr);
-    AppendToString(quote, aStr);
+    NS_ENSURE_TRUE(AppendToString(quote, aStr), NS_ERROR_OUT_OF_MEMORY);
+    NS_ENSURE_TRUE(AppendToString(publicId, aStr), NS_ERROR_OUT_OF_MEMORY);
+    NS_ENSURE_TRUE(AppendToString(quote, aStr), NS_ERROR_OUT_OF_MEMORY);
 
     if (!systemId.IsEmpty()) {
-      AppendToString(char16_t(' '), aStr);
+      NS_ENSURE_TRUE(AppendToString(char16_t(' '), aStr), NS_ERROR_OUT_OF_MEMORY);
       if (systemId.FindChar(char16_t('"')) == -1) {
         quote = char16_t('"');
       }
       else {
         quote = char16_t('\'');
       }
-      AppendToString(quote, aStr);
-      AppendToString(systemId, aStr);
-      AppendToString(quote, aStr);
+      NS_ENSURE_TRUE(AppendToString(quote, aStr), NS_ERROR_OUT_OF_MEMORY);
+      NS_ENSURE_TRUE(AppendToString(systemId, aStr), NS_ERROR_OUT_OF_MEMORY);
+      NS_ENSURE_TRUE(AppendToString(quote, aStr), NS_ERROR_OUT_OF_MEMORY);
     }
   }
   else if (!systemId.IsEmpty()) {
     if (systemId.FindChar(char16_t('"')) == -1) {
       quote = char16_t('"');
     }
     else {
       quote = char16_t('\'');
     }
-    AppendToString(NS_LITERAL_STRING(" SYSTEM "), aStr);
-    AppendToString(quote, aStr);
-    AppendToString(systemId, aStr);
-    AppendToString(quote, aStr);
+    NS_ENSURE_TRUE(AppendToString(NS_LITERAL_STRING(" SYSTEM "), aStr), NS_ERROR_OUT_OF_MEMORY);
+    NS_ENSURE_TRUE(AppendToString(quote, aStr), NS_ERROR_OUT_OF_MEMORY);
+    NS_ENSURE_TRUE(AppendToString(systemId, aStr), NS_ERROR_OUT_OF_MEMORY);
+    NS_ENSURE_TRUE(AppendToString(quote, aStr), NS_ERROR_OUT_OF_MEMORY);
   }
   
   if (!internalSubset.IsEmpty()) {
-    AppendToString(NS_LITERAL_STRING(" ["), aStr);
-    AppendToString(internalSubset, aStr);
-    AppendToString(char16_t(']'), aStr);
+    NS_ENSURE_TRUE(AppendToString(NS_LITERAL_STRING(" ["), aStr), NS_ERROR_OUT_OF_MEMORY);
+    NS_ENSURE_TRUE(AppendToString(internalSubset, aStr), NS_ERROR_OUT_OF_MEMORY);
+    NS_ENSURE_TRUE(AppendToString(char16_t(']'), aStr), NS_ERROR_OUT_OF_MEMORY);
   }
     
-  AppendToString(kGreaterThan, aStr);
+  NS_ENSURE_TRUE(AppendToString(kGreaterThan, aStr), NS_ERROR_OUT_OF_MEMORY);
   MaybeFlagNewlineForRootNode(aDocType);
 
   return NS_OK;
 }
 
 nsresult
 nsXMLContentSerializer::PushNameSpaceDecl(const nsAString& aPrefix,
                                           const nsAString& aURI,
@@ -601,48 +605,49 @@ void
 nsXMLContentSerializer::GenerateNewPrefix(nsAString& aPrefix)
 {
   aPrefix.Assign('a');
   char buf[128];
   PR_snprintf(buf, sizeof(buf), "%d", mPrefixIndex++);
   AppendASCIItoUTF16(buf, aPrefix);
 }
 
-void
+bool
 nsXMLContentSerializer::SerializeAttr(const nsAString& aPrefix,
                                       const nsAString& aName,
                                       const nsAString& aValue,
                                       nsAString& aStr,
                                       bool aDoEscapeEntities)
 {
   nsAutoString attrString_;
   // For innerHTML we can do faster appending without
   // temporary strings.
   bool rawAppend = mDoRaw && aDoEscapeEntities;
   nsAString& attrString = (rawAppend) ? aStr : attrString_;
 
-  attrString.Append(char16_t(' '));
+  NS_ENSURE_TRUE(attrString.Append(char16_t(' '), mozilla::fallible), false);
   if (!aPrefix.IsEmpty()) {
-    attrString.Append(aPrefix);
-    attrString.Append(char16_t(':'));
+    NS_ENSURE_TRUE(attrString.Append(aPrefix, mozilla::fallible), false);
+    NS_ENSURE_TRUE(attrString.Append(char16_t(':'), mozilla::fallible), false);
   }
-  attrString.Append(aName);
+  NS_ENSURE_TRUE(attrString.Append(aName, mozilla::fallible), false);
 
   if (aDoEscapeEntities) {
     // if problem characters are turned into character entity references
     // then there will be no problem with the value delimiter characters
-    attrString.AppendLiteral("=\"");
+    NS_ENSURE_TRUE(attrString.AppendLiteral("=\"", mozilla::fallible), false);
 
     mInAttribute = true;
-    AppendAndTranslateEntities(aValue, attrString);
+    bool result = AppendAndTranslateEntities(aValue, attrString);
     mInAttribute = false;
+    NS_ENSURE_TRUE(result, false);
 
-    attrString.Append(char16_t('"'));
+    NS_ENSURE_TRUE(attrString.Append(char16_t('"'), mozilla::fallible), false);
     if (rawAppend) {
-      return;
+      return true;
     }
   }
   else {
     // Depending on whether the attribute value contains quotes or apostrophes we
     // need to select the delimiter character and escape characters using
     // character entity references, ignoring the value of aDoEscapeEntities.
     // See http://www.w3.org/TR/REC-html40/appendix/notes.html#h-B.3.2.2 for
     // the standard on character entity references in values.  We also have to
@@ -676,40 +681,42 @@ nsXMLContentSerializer::SerializeAttr(co
     // Delimiter and escaping is according to the following table
     //    bIncludesDouble     bIncludesSingle     Delimiter       Escape Double Quote
     //    FALSE               FALSE               "               FALSE
     //    FALSE               TRUE                "               FALSE
     //    TRUE                FALSE               '               FALSE
     //    TRUE                TRUE                "               TRUE
     char16_t cDelimiter = 
         (bIncludesDouble && !bIncludesSingle) ? char16_t('\'') : char16_t('"');
-    attrString.Append(char16_t('='));
-    attrString.Append(cDelimiter);
+    NS_ENSURE_TRUE(attrString.Append(char16_t('='), mozilla::fallible), false);
+    NS_ENSURE_TRUE(attrString.Append(cDelimiter, mozilla::fallible), false);
     nsAutoString sValue(aValue);
-    sValue.ReplaceSubstring(NS_LITERAL_STRING("&"),
-                            NS_LITERAL_STRING("&amp;"));
+    NS_ENSURE_TRUE(sValue.ReplaceSubstring(NS_LITERAL_STRING("&"),
+                                           NS_LITERAL_STRING("&amp;"), mozilla::fallible), false);
     if (bIncludesDouble && bIncludesSingle) {
-      sValue.ReplaceSubstring(NS_LITERAL_STRING("\""),
-                              NS_LITERAL_STRING("&quot;"));
+      NS_ENSURE_TRUE(sValue.ReplaceSubstring(NS_LITERAL_STRING("\""),
+                                             NS_LITERAL_STRING("&quot;"), mozilla::fallible), false);
     }
-    attrString.Append(sValue);
-    attrString.Append(cDelimiter);
+    NS_ENSURE_TRUE(attrString.Append(sValue, mozilla::fallible), false);
+    NS_ENSURE_TRUE(attrString.Append(cDelimiter, mozilla::fallible), false);
   }
   if (mDoRaw || PreLevel() > 0) {
-    AppendToStringConvertLF(attrString, aStr);
+    NS_ENSURE_TRUE(AppendToStringConvertLF(attrString, aStr), false);
   }
   else if (mDoFormat) {
-    AppendToStringFormatedWrapped(attrString, aStr);
+    NS_ENSURE_TRUE(AppendToStringFormatedWrapped(attrString, aStr), false);
   }
   else if (mDoWrap) {
-    AppendToStringWrapped(attrString, aStr);
+    NS_ENSURE_TRUE(AppendToStringWrapped(attrString, aStr), false);
   }
   else {
-    AppendToStringConvertLF(attrString, aStr);
+    NS_ENSURE_TRUE(AppendToStringConvertLF(attrString, aStr), false);
   }
+
+  return true;
 }
 
 uint32_t 
 nsXMLContentSerializer::ScanNamespaceDeclarations(nsIContent* aContent,
                                                   nsIContent *aOriginalElement,
                                                   const nsAString& aTagNamespaceURI)
 {
   uint32_t index, count;
@@ -787,17 +794,17 @@ nsXMLContentSerializer::IsJavaScript(nsI
     else
       return false;
   }
 
   return aContent->IsEventAttributeName(aAttrNameAtom);
 }
 
 
-void 
+bool
 nsXMLContentSerializer::SerializeAttributes(nsIContent* aContent,
                                             nsIContent *aOriginalElement,
                                             nsAString& aTagPrefix,
                                             const nsAString& aTagNamespaceURI,
                                             nsIAtom* aTagName,
                                             nsAString& aStr,
                                             uint32_t aSkipAttr,
                                             bool aAddNSAttr)
@@ -808,21 +815,21 @@ nsXMLContentSerializer::SerializeAttribu
   xmlnsStr.AssignLiteral(kXMLNS);
   uint32_t index, count;
 
   // If we had to add a new namespace declaration, serialize
   // and push it on the namespace stack
   if (aAddNSAttr) {
     if (aTagPrefix.IsEmpty()) {
       // Serialize default namespace decl
-      SerializeAttr(EmptyString(), xmlnsStr, aTagNamespaceURI, aStr, true);
+      NS_ENSURE_TRUE(SerializeAttr(EmptyString(), xmlnsStr, aTagNamespaceURI, aStr, true), false);
     }
     else {
       // Serialize namespace decl
-      SerializeAttr(xmlnsStr, aTagPrefix, aTagNamespaceURI, aStr, true);
+      NS_ENSURE_TRUE(SerializeAttr(xmlnsStr, aTagPrefix, aTagNamespaceURI, aStr, true), false);
     }
     PushNameSpaceDecl(aTagPrefix, aTagNamespaceURI, aOriginalElement);
   }
 
   count = aContent->GetAttrCount();
 
   // Now serialize each of the attributes
   // XXX Unfortunately we need a namespace manager to get
@@ -857,125 +864,132 @@ nsXMLContentSerializer::SerializeAttribu
       addNSAttr = ConfirmPrefix(prefixStr, uriStr, aOriginalElement, true);
     }
     
     aContent->GetAttr(namespaceID, attrName, valueStr);
 
     nsDependentAtomString nameStr(attrName);
     bool isJS = IsJavaScript(aContent, attrName, namespaceID, valueStr);
 
-    SerializeAttr(prefixStr, nameStr, valueStr, aStr, !isJS);
+    NS_ENSURE_TRUE(SerializeAttr(prefixStr, nameStr, valueStr, aStr, !isJS), false);
     
     if (addNSAttr) {
       NS_ASSERTION(!prefixStr.IsEmpty(),
                    "Namespaced attributes must have a prefix");
-      SerializeAttr(xmlnsStr, prefixStr, uriStr, aStr, true);
+      NS_ENSURE_TRUE(SerializeAttr(xmlnsStr, prefixStr, uriStr, aStr, true), false);
       PushNameSpaceDecl(prefixStr, uriStr, aOriginalElement);
     }
   }
+
+  return true;
 }
 
 NS_IMETHODIMP 
 nsXMLContentSerializer::AppendElementStart(Element* aElement,
                                            Element* aOriginalElement,
                                            nsAString& aStr)
 {
   NS_ENSURE_ARG(aElement);
 
   nsIContent* content = aElement;
 
   bool forceFormat = false;
-  if (!CheckElementStart(content, forceFormat, aStr)) {
-    return NS_OK;
+  nsresult rv = NS_OK;
+  if (!CheckElementStart(content, forceFormat, aStr, rv)) {
+    return rv;
   }
 
+  NS_ENSURE_SUCCESS(rv, rv);
+
   nsAutoString tagPrefix, tagLocalName, tagNamespaceURI;
   aElement->NodeInfo()->GetPrefix(tagPrefix);
   aElement->NodeInfo()->GetName(tagLocalName);
   aElement->NodeInfo()->GetNamespaceURI(tagNamespaceURI);
 
   uint32_t skipAttr = ScanNamespaceDeclarations(content,
                           aOriginalElement, tagNamespaceURI);
 
   nsIAtom *name = content->Tag();
   bool lineBreakBeforeOpen = LineBreakBeforeOpen(content->GetNameSpaceID(), name);
 
   if ((mDoFormat || forceFormat) && !mDoRaw && !PreLevel()) {
     if (mColPos && lineBreakBeforeOpen) {
-      AppendNewLineToString(aStr);
+      NS_ENSURE_TRUE(AppendNewLineToString(aStr), NS_ERROR_OUT_OF_MEMORY);
     }
     else {
-      MaybeAddNewlineForRootNode(aStr);
+      NS_ENSURE_TRUE(MaybeAddNewlineForRootNode(aStr), NS_ERROR_OUT_OF_MEMORY);
     }
     if (!mColPos) {
-      AppendIndentation(aStr);
+      NS_ENSURE_TRUE(AppendIndentation(aStr), NS_ERROR_OUT_OF_MEMORY);
     }
     else if (mAddSpace) {
-      AppendToString(char16_t(' '), aStr);
+      NS_ENSURE_TRUE(AppendToString(char16_t(' '), aStr), NS_ERROR_OUT_OF_MEMORY);
       mAddSpace = false;
     }
   }
   else if (mAddSpace) {
-    AppendToString(char16_t(' '), aStr);
+    NS_ENSURE_TRUE(AppendToString(char16_t(' '), aStr), NS_ERROR_OUT_OF_MEMORY);
     mAddSpace = false;
   }
   else {
-    MaybeAddNewlineForRootNode(aStr);
+    NS_ENSURE_TRUE(MaybeAddNewlineForRootNode(aStr), NS_ERROR_OUT_OF_MEMORY);
   }
 
   // Always reset to avoid false newlines in case MaybeAddNewlineForRootNode wasn't
   // called
   mAddNewlineForRootNode = false;
 
   bool addNSAttr;
   addNSAttr = ConfirmPrefix(tagPrefix, tagNamespaceURI, aOriginalElement,
                             false);
 
   // Serialize the qualified name of the element
-  AppendToString(kLessThan, aStr);
+  NS_ENSURE_TRUE(AppendToString(kLessThan, aStr), NS_ERROR_OUT_OF_MEMORY);
   if (!tagPrefix.IsEmpty()) {
-    AppendToString(tagPrefix, aStr);
-    AppendToString(NS_LITERAL_STRING(":"), aStr);
+    NS_ENSURE_TRUE(AppendToString(tagPrefix, aStr), NS_ERROR_OUT_OF_MEMORY);
+    NS_ENSURE_TRUE(AppendToString(NS_LITERAL_STRING(":"), aStr), NS_ERROR_OUT_OF_MEMORY);
   }
-  AppendToString(tagLocalName, aStr);
+  NS_ENSURE_TRUE(AppendToString(tagLocalName, aStr), NS_ERROR_OUT_OF_MEMORY);
 
   MaybeEnterInPreContent(content);
 
   if ((mDoFormat || forceFormat) && !mDoRaw && !PreLevel()) {
-    IncrIndentation(name);
+    NS_ENSURE_TRUE(IncrIndentation(name), NS_ERROR_OUT_OF_MEMORY);
   }
 
-  SerializeAttributes(content, aOriginalElement, tagPrefix, tagNamespaceURI,
-                      name, aStr, skipAttr, addNSAttr);
+  NS_ENSURE_TRUE(SerializeAttributes(content, aOriginalElement, tagPrefix, tagNamespaceURI,
+                                     name, aStr, skipAttr, addNSAttr),
+                 NS_ERROR_OUT_OF_MEMORY);
 
-  AppendEndOfElementStart(aOriginalElement, name, content->GetNameSpaceID(),
-                          aStr);
+  NS_ENSURE_TRUE(AppendEndOfElementStart(aOriginalElement, name,
+                                         content->GetNameSpaceID(), aStr),
+                 NS_ERROR_OUT_OF_MEMORY);
 
   if ((mDoFormat || forceFormat) && !mDoRaw && !PreLevel()
     && LineBreakAfterOpen(content->GetNameSpaceID(), name)) {
-    AppendNewLineToString(aStr);
+    NS_ENSURE_TRUE(AppendNewLineToString(aStr), NS_ERROR_OUT_OF_MEMORY);
   }
 
-  AfterElementStart(content, aOriginalElement, aStr);
+  NS_ENSURE_TRUE(AfterElementStart(content, aOriginalElement, aStr), NS_ERROR_OUT_OF_MEMORY);
 
   return NS_OK;
 }
 
-void 
+bool
 nsXMLContentSerializer::AppendEndOfElementStart(nsIContent *aOriginalElement,
                                                 nsIAtom * aName,
                                                 int32_t aNamespaceID,
                                                 nsAString& aStr)
 {
   // We don't output a separate end tag for empty elements
   if (!aOriginalElement->GetChildCount()) {
-    AppendToString(NS_LITERAL_STRING("/>"), aStr);
+    return AppendToString(NS_LITERAL_STRING("/>"), aStr);
   }
   else {
-    AppendToString(kGreaterThan, aStr);
+    return AppendToString(kGreaterThan, aStr);
   }
 }
 
 NS_IMETHODIMP 
 nsXMLContentSerializer::AppendElementEnd(Element* aElement,
                                          nsAString& aStr)
 {
   NS_ENSURE_ARG(aElement);
@@ -1009,46 +1023,46 @@ nsXMLContentSerializer::AppendElementEnd
   ConfirmPrefix(tagPrefix, tagNamespaceURI, aElement, false);
   NS_ASSERTION(!debugNeedToPushNamespace, "Can't push namespaces in closing tag!");
 
   if ((mDoFormat || forceFormat) && !mDoRaw && !PreLevel()) {
 
     bool lineBreakBeforeClose = LineBreakBeforeClose(content->GetNameSpaceID(), name);
 
     if (mColPos && lineBreakBeforeClose) {
-      AppendNewLineToString(aStr);
+      NS_ENSURE_TRUE(AppendNewLineToString(aStr), NS_ERROR_OUT_OF_MEMORY);
     }
     if (!mColPos) {
-      AppendIndentation(aStr);
+      NS_ENSURE_TRUE(AppendIndentation(aStr), NS_ERROR_OUT_OF_MEMORY);
     }
     else if (mAddSpace) {
-      AppendToString(char16_t(' '), aStr);
+      NS_ENSURE_TRUE(AppendToString(char16_t(' '), aStr), NS_ERROR_OUT_OF_MEMORY);
       mAddSpace = false;
     }
   }
   else if (mAddSpace) {
-    AppendToString(char16_t(' '), aStr);
+    NS_ENSURE_TRUE(AppendToString(char16_t(' '), aStr), NS_ERROR_OUT_OF_MEMORY);
     mAddSpace = false;
   }
 
-  AppendToString(kEndTag, aStr);
+  NS_ENSURE_TRUE(AppendToString(kEndTag, aStr), NS_ERROR_OUT_OF_MEMORY);
   if (!tagPrefix.IsEmpty()) {
-    AppendToString(tagPrefix, aStr);
-    AppendToString(NS_LITERAL_STRING(":"), aStr);
+    NS_ENSURE_TRUE(AppendToString(tagPrefix, aStr), NS_ERROR_OUT_OF_MEMORY);
+    NS_ENSURE_TRUE(AppendToString(NS_LITERAL_STRING(":"), aStr), NS_ERROR_OUT_OF_MEMORY);
   }
-  AppendToString(tagLocalName, aStr);
-  AppendToString(kGreaterThan, aStr);
+  NS_ENSURE_TRUE(AppendToString(tagLocalName, aStr), NS_ERROR_OUT_OF_MEMORY);
+  NS_ENSURE_TRUE(AppendToString(kGreaterThan, aStr), NS_ERROR_OUT_OF_MEMORY);
 
   PopNameSpaceDeclsFor(aElement);
 
   MaybeLeaveFromPreContent(content);
 
   if ((mDoFormat || forceFormat) && !mDoRaw && !PreLevel()
       && LineBreakAfterClose(content->GetNameSpaceID(), name)) {
-    AppendNewLineToString(aStr);
+    NS_ENSURE_TRUE(AppendNewLineToString(aStr), NS_ERROR_OUT_OF_MEMORY);
   }
   else {
     MaybeFlagNewlineForRootNode(aElement);
   }
 
   AfterElementEnd(content, aStr);
 
   return NS_OK;
@@ -1081,61 +1095,63 @@ nsXMLContentSerializer::AppendDocumentSt
     NS_WARNING("Empty mCharset?  How come?");
   }
 #endif
 
   if (!standalone.IsEmpty()) {
     aStr += NS_LITERAL_STRING(" standalone=\"") + standalone + endQuote;
   }
 
-  aStr.AppendLiteral("?>");
+  NS_ENSURE_TRUE(aStr.AppendLiteral("?>", mozilla::fallible), NS_ERROR_OUT_OF_MEMORY);
   mAddNewlineForRootNode = true;
 
   return NS_OK;
 }
 
 bool
 nsXMLContentSerializer::CheckElementStart(nsIContent * aContent,
                                           bool & aForceFormat,
-                                          nsAString& aStr)
+                                          nsAString& aStr,
+                                          nsresult& aResult)
 {
+  aResult = NS_OK;
   aForceFormat = false;
   return true;
 }
 
 bool
 nsXMLContentSerializer::CheckElementEnd(nsIContent * aContent,
                                         bool & aForceFormat,
                                         nsAString& aStr)
 {
   // We don't output a separate end tag for empty element
   aForceFormat = false;
   return aContent->GetChildCount() > 0;
 }
 
-void 
+bool
 nsXMLContentSerializer::AppendToString(const char16_t aChar,
                                        nsAString& aOutputStr)
 {
   if (mBodyOnly && !mInBody) {
-    return;
+    return true;
   }
   mColPos += 1;
-  aOutputStr.Append(aChar);
+  return aOutputStr.Append(aChar, mozilla::fallible);
 }
 
-void
+bool
 nsXMLContentSerializer::AppendToString(const nsAString& aStr,
                                        nsAString& aOutputStr)
 {
   if (mBodyOnly && !mInBody) {
-    return;
+    return true;
   }
   mColPos += aStr.Length();
-  aOutputStr.Append(aStr);
+  return aOutputStr.Append(aStr, mozilla::fallible);
 }
 
 
 static const uint16_t kGTVal = 62;
 static const char* kEntities[] = {
   "", "", "", "", "", "", "", "", "", "",
   "", "", "", "", "", "", "", "", "", "",
   "", "", "", "", "", "", "", "", "", "",
@@ -1150,17 +1166,17 @@ static const char* kAttrEntities[] = {
   "", "", "", "", "", "", "", "", "", "",
   "", "", "", "", "", "", "", "", "", "",
   "", "", "", "", "&quot;", "", "", "", "&amp;", "",
   "", "", "", "", "", "", "", "", "", "",
   "", "", "", "", "", "", "", "", "", "",
   "&lt;", "", "&gt;"
 };
 
-void
+bool
 nsXMLContentSerializer::AppendAndTranslateEntities(const nsAString& aStr,
                                                    nsAString& aOutputStr)
 {
   nsReadingIterator<char16_t> done_reading;
   aStr.EndReading(done_reading);
 
   // for each chunk of |aString|...
   uint32_t advanceLength = 0;
@@ -1183,30 +1199,34 @@ nsXMLContentSerializer::AppendAndTransla
     for (; c < fragmentEnd; c++, advanceLength++) {
       char16_t val = *c;
       if ((val <= kGTVal) && (entityTable[val][0] != 0)) {
         entityText = entityTable[val];
         break;
       }
     }
 
-    aOutputStr.Append(fragmentStart, advanceLength);
+    NS_ENSURE_TRUE(aOutputStr.Append(fragmentStart, advanceLength, mozilla::fallible), false);
     if (entityText) {
-      AppendASCIItoUTF16(entityText, aOutputStr);
+      NS_ENSURE_TRUE(AppendASCIItoUTF16(entityText, aOutputStr, mozilla::fallible), false);
       advanceLength++;
     }
   }
+
+  return true;
 }
 
-void
+bool
 nsXMLContentSerializer::MaybeAddNewlineForRootNode(nsAString& aStr)
 {
   if (mAddNewlineForRootNode) {
-    AppendNewLineToString(aStr);
+    return AppendNewLineToString(aStr);
   }
+
+  return true;
 }
 
 void
 nsXMLContentSerializer::MaybeFlagNewlineForRootNode(nsINode* aNode)
 {
   nsINode* parent = aNode->GetParentNode();
   if (parent) {
     mAddNewlineForRootNode = parent->IsNodeOfType(nsINode::eDOCUMENT);
@@ -1234,46 +1254,50 @@ nsXMLContentSerializer::MaybeLeaveFromPr
       aNode->HasAttr(kNameSpaceID_XML, nsGkAtoms::space)) {
     nsAutoString space;
     aNode->GetAttr(kNameSpaceID_XML, nsGkAtoms::space, space);
     if (space.EqualsLiteral("preserve"))
       --PreLevel();
   }
 }
 
-void
+bool
 nsXMLContentSerializer::AppendNewLineToString(nsAString& aStr)
 {
-  AppendToString(mLineBreak, aStr);
+  bool result = AppendToString(mLineBreak, aStr);
   mMayIgnoreLineBreakSequence = true;
   mColPos = 0;
   mAddSpace = false;
   mIsIndentationAddedOnCurrentLine = false;
+  return result;
 }
 
-void
+bool
 nsXMLContentSerializer::AppendIndentation(nsAString& aStr)
 {
   mIsIndentationAddedOnCurrentLine = true;
-  AppendToString(mIndent, aStr);
+  bool result = AppendToString(mIndent, aStr);
   mAddSpace = false;
   mMayIgnoreLineBreakSequence = false;
+  return result;
 }
 
-void
+bool
 nsXMLContentSerializer::IncrIndentation(nsIAtom* aName)
 {
   // we want to keep the source readable
   if (mDoWrap &&
       mIndent.Length() >= uint32_t(mMaxColumn) - MIN_INDENTED_LINE_LENGTH) {
     ++mIndentOverflow;
   }
   else {
-    mIndent.AppendLiteral(INDENT_STRING);
+    return mIndent.AppendLiteral(INDENT_STRING, mozilla::fallible);
   }
+
+  return true;
 }
 
 void
 nsXMLContentSerializer::DecrIndentation(nsIAtom* aName)
 {
   if(mIndentOverflow)
     --mIndentOverflow;
   else
@@ -1299,53 +1323,55 @@ nsXMLContentSerializer::LineBreakBeforeC
 }
 
 bool 
 nsXMLContentSerializer::LineBreakAfterClose(int32_t aNamespaceID, nsIAtom* aName)
 {
   return false;
 }
 
-void
+bool
 nsXMLContentSerializer::AppendToStringConvertLF(const nsAString& aStr,
                                                 nsAString& aOutputStr)
 {
   if (mBodyOnly && !mInBody) {
-    return;
+    return true;
   }
 
   if (mDoRaw) {
-    AppendToString(aStr, aOutputStr);
+    NS_ENSURE_TRUE(AppendToString(aStr, aOutputStr), false);
   }
   else {
     // Convert line-endings to mLineBreak
     uint32_t start = 0;
     uint32_t theLen = aStr.Length();
     while (start < theLen) {
       int32_t eol = aStr.FindChar('\n', start);
       if (eol == kNotFound) {
         nsDependentSubstring dataSubstring(aStr, start, theLen - start);
-        AppendToString(dataSubstring, aOutputStr);
+        NS_ENSURE_TRUE(AppendToString(dataSubstring, aOutputStr), false);
         start = theLen;
         // if there was a line break before this substring
         // AppendNewLineToString was called, so we should reverse
         // this flag
         mMayIgnoreLineBreakSequence = false;
       }
       else {
         nsDependentSubstring dataSubstring(aStr, start, eol - start);
-        AppendToString(dataSubstring, aOutputStr);
-        AppendNewLineToString(aOutputStr);
+        NS_ENSURE_TRUE(AppendToString(dataSubstring, aOutputStr), false);
+        NS_ENSURE_TRUE(AppendNewLineToString(aOutputStr), false);
         start = eol + 1;
       }
     }
   }
+
+  return true;
 }
 
-void
+bool
 nsXMLContentSerializer::AppendFormatedWrapped_WhitespaceSequence(
                         nsASingleFragmentString::const_char_iterator &aPos,
                         const nsASingleFragmentString::const_char_iterator aEnd,
                         const nsASingleFragmentString::const_char_iterator aSequenceStart,
                         bool &aMayIgnoreStartOfLineWhitespaceSequence,
                         nsAString &aOutputStr)
 {
   // Handle the complete sequence of whitespace.
@@ -1388,39 +1414,42 @@ nsXMLContentSerializer::AppendFormatedWr
     // nothing to do
     aMayIgnoreStartOfLineWhitespaceSequence = false;
   }
   else {
     if (sawBlankOrTab) {
       if (mDoWrap && mColPos + 1 >= mMaxColumn) {
         // no much sense in delaying, we only have one slot left,
         // let's write a break now
-        aOutputStr.Append(mLineBreak);
+        bool result = aOutputStr.Append(mLineBreak, mozilla::fallible);
         mColPos = 0;
         mIsIndentationAddedOnCurrentLine = false;
         mMayIgnoreLineBreakSequence = true;
+        NS_ENSURE_TRUE(result, false);
       }
       else {
         // do not write out yet, we may write out either a space or a linebreak
         // let's delay writing it out until we know more
         mAddSpace = true;
         ++mColPos; // eat a slot of available space
       }
     }
     else {
       // Asian text usually does not contain spaces, therefore we should not
       // transform a linebreak into a space.
       // Since we only saw linebreaks, but no spaces or tabs,
       // let's write a linebreak now.
-      AppendNewLineToString(aOutputStr);
+      NS_ENSURE_TRUE(AppendNewLineToString(aOutputStr), false);
     }
   }
+
+  return true;
 }
 
-void
+bool
 nsXMLContentSerializer::AppendWrapped_NonWhitespaceSequence(
                         nsASingleFragmentString::const_char_iterator &aPos,
                         const nsASingleFragmentString::const_char_iterator aEnd,
                         const nsASingleFragmentString::const_char_iterator aSequenceStart,
                         bool &aMayIgnoreStartOfLineWhitespaceSequence,
                         bool &aSequenceStartAfterAWhiteSpace,
                         nsAString& aOutputStr)
 {
@@ -1471,42 +1500,43 @@ nsXMLContentSerializer::AppendWrapped_No
     // appending a new line etc.
     if (*aPos == ' ' || *aPos == '\t' || *aPos == '\n') {
       foundWhitespaceInLoop = true;
     }
 
     if (aPos == aEnd || foundWhitespaceInLoop) {
       // there is enough room for the complete block we found
       if (mDoFormat && !mColPos) {
-        AppendIndentation(aOutputStr);
+        NS_ENSURE_TRUE(AppendIndentation(aOutputStr), false);
       }
       else if (mAddSpace) {
-        aOutputStr.Append(char16_t(' '));
+        bool result = aOutputStr.Append(char16_t(' '), mozilla::fallible);
         mAddSpace = false;
+        NS_ENSURE_TRUE(result, false);
       }
 
       mColPos += length;
-      aOutputStr.Append(aSequenceStart, aPos - aSequenceStart);
+      NS_ENSURE_TRUE(aOutputStr.Append(aSequenceStart, aPos - aSequenceStart, mozilla::fallible), false);
 
       // We have not yet reached the max column, we will continue to
       // fill the current line in the next outer loop iteration
       // (this one in AppendToStringWrapped)
       // make sure we return in this outer loop
       onceAgainBecauseWeAddedBreakInFront = false;
     }
     else { // we reach the max column
       if (!thisSequenceStartsAtBeginningOfLine &&
           (mAddSpace || (!mDoFormat && aSequenceStartAfterAWhiteSpace))) { 
           // when !mDoFormat, mAddSpace is not used, mAddSpace is always false
           // so, in the case where mDoWrap && !mDoFormat, if we want to enter in this condition...
 
         // We can avoid to wrap. We try to add the whole block 
         // in an empty new line
 
-        AppendNewLineToString(aOutputStr);
+        NS_ENSURE_TRUE(AppendNewLineToString(aOutputStr), false);
         aPos = aSequenceStart;
         thisSequenceStartsAtBeginningOfLine = true;
         onceAgainBecauseWeAddedBreakInFront = true;
       }
       else {
         // we must wrap
         onceAgainBecauseWeAddedBreakInFront = false;
         bool foundWrapPosition = false;
@@ -1526,25 +1556,26 @@ nsXMLContentSerializer::AppendWrapped_No
                                            (aPos - aSequenceStart));
           if (wrapPosition != NS_LINEBREAKER_NEED_MORE_TEXT) {
             foundWrapPosition = true;
           }
         }
 
         if (foundWrapPosition) {
           if (!mColPos && mDoFormat) {
-            AppendIndentation(aOutputStr);
+            NS_ENSURE_TRUE(AppendIndentation(aOutputStr), false);
           }
           else if (mAddSpace) {
-            aOutputStr.Append(char16_t(' '));
+            bool result = aOutputStr.Append(char16_t(' '), mozilla::fallible);
             mAddSpace = false;
+            NS_ENSURE_TRUE(result, false);
           }
-          aOutputStr.Append(aSequenceStart, wrapPosition);
+          NS_ENSURE_TRUE(aOutputStr.Append(aSequenceStart, wrapPosition, mozilla::fallible), false);
 
-          AppendNewLineToString(aOutputStr);
+          NS_ENSURE_TRUE(AppendNewLineToString(aOutputStr), false);
           aPos = aSequenceStart + wrapPosition;
           aMayIgnoreStartOfLineWhitespaceSequence = true;
         }
         else {
           // try some simple fallback logic
           // go forward up to the next whitespace position,
           // in the worst case this will be all the rest of the data
 
@@ -1558,33 +1589,36 @@ nsXMLContentSerializer::AppendWrapped_No
               break;
             }
 
             ++aPos;
             ++mColPos;
           } while (aPos < aEnd);
 
           if (mAddSpace) {
-            aOutputStr.Append(char16_t(' '));
+            bool result = aOutputStr.Append(char16_t(' '), mozilla::fallible);
             mAddSpace = false;
+            NS_ENSURE_TRUE(result, false);
           }
-          aOutputStr.Append(aSequenceStart, aPos - aSequenceStart);
+          NS_ENSURE_TRUE(aOutputStr.Append(aSequenceStart, aPos - aSequenceStart, mozilla::fallible), false);
         }
       }
       aSequenceStartAfterAWhiteSpace = false;
     }
   } while (onceAgainBecauseWeAddedBreakInFront);
+
+  return true;
 }
 
-void 
+bool
 nsXMLContentSerializer::AppendToStringFormatedWrapped(const nsASingleFragmentString& aStr,
                                                       nsAString& aOutputStr)
 {
   if (mBodyOnly && !mInBody) {
-    return;
+    return true;
   }
 
   nsASingleFragmentString::const_char_iterator pos, end, sequenceStart;
 
   aStr.BeginReading(pos);
   aStr.EndReading(end);
 
   bool sequenceStartAfterAWhitespace = false;
@@ -1604,27 +1638,30 @@ nsXMLContentSerializer::AppendToStringFo
                   sequenceStartAfterAWhitespace &&
                   uint32_t(mColPos) == mIndent.Length()));
 
   while (pos < end) {
     sequenceStart = pos;
 
     // if beginning of a whitespace sequence
     if (*pos == ' ' || *pos == '\n' || *pos == '\t') {
-      AppendFormatedWrapped_WhitespaceSequence(pos, end, sequenceStart,
-        mayIgnoreStartOfLineWhitespaceSequence, aOutputStr);
+      NS_ENSURE_TRUE(AppendFormatedWrapped_WhitespaceSequence(pos, end, sequenceStart,
+        mayIgnoreStartOfLineWhitespaceSequence, aOutputStr), false);
     }
     else { // any other non-whitespace char
-      AppendWrapped_NonWhitespaceSequence(pos, end, sequenceStart,
-        mayIgnoreStartOfLineWhitespaceSequence, sequenceStartAfterAWhitespace, aOutputStr);
+      NS_ENSURE_TRUE(AppendWrapped_NonWhitespaceSequence(pos, end, sequenceStart,
+        mayIgnoreStartOfLineWhitespaceSequence, sequenceStartAfterAWhitespace,
+        aOutputStr), false);
     }
   }
+
+  return true;
 }
 
-void
+bool
 nsXMLContentSerializer::AppendWrapped_WhitespaceSequence(
                         nsASingleFragmentString::const_char_iterator &aPos,
                         const nsASingleFragmentString::const_char_iterator aEnd,
                         const nsASingleFragmentString::const_char_iterator aSequenceStart,
                         nsAString &aOutputStr)
 {
   // Handle the complete sequence of whitespace.
   // Continue to iterate until we find the first non-whitespace char.
@@ -1637,52 +1674,54 @@ nsXMLContentSerializer::AppendWrapped_Wh
 
   do {
     switch (*aPos) {
       case ' ':
       case '\t':
         // if there are too many spaces on a line, we wrap
         if (mColPos >= mMaxColumn) {
           if (lastPos != aPos) {
-            aOutputStr.Append(lastPos, aPos - lastPos);
+            NS_ENSURE_TRUE(aOutputStr.Append(lastPos, aPos - lastPos, mozilla::fallible), false);
           }
-          AppendToString(mLineBreak, aOutputStr);
+          NS_ENSURE_TRUE(AppendToString(mLineBreak, aOutputStr), false);
           mColPos = 0;
           lastPos = aPos;
         }
 
         ++mColPos;
         ++aPos;
         break;
       case '\n':
         if (lastPos != aPos) {
-          aOutputStr.Append(lastPos, aPos - lastPos);
+          NS_ENSURE_TRUE(aOutputStr.Append(lastPos, aPos - lastPos, mozilla::fallible), false);
         }
-        AppendToString(mLineBreak, aOutputStr);
+        NS_ENSURE_TRUE(AppendToString(mLineBreak, aOutputStr), false);
         mColPos = 0;
         ++aPos;
         lastPos = aPos;
         break;
       default:
         leaveLoop = true;
         break;
     }
   } while (!leaveLoop && aPos < aEnd);
 
   if (lastPos != aPos) {
-    aOutputStr.Append(lastPos, aPos - lastPos);
+    NS_ENSURE_TRUE(aOutputStr.Append(lastPos, aPos - lastPos, mozilla::fallible), false);
   }
+
+  return true;
 }
 
-void 
+bool
 nsXMLContentSerializer::AppendToStringWrapped(const nsASingleFragmentString& aStr,
                                               nsAString& aOutputStr)
 {
   if (mBodyOnly && !mInBody) {
-    return;
+    return true;
   }
 
   nsASingleFragmentString::const_char_iterator pos, end, sequenceStart;
 
   aStr.BeginReading(pos);
   aStr.EndReading(end);
 
   // not used in this case, but needed by AppendWrapped_NonWhitespaceSequence
@@ -1700,23 +1739,27 @@ nsXMLContentSerializer::AppendToStringWr
   }
 
   while (pos < end) {
     sequenceStart = pos;
 
     // if beginning of a whitespace sequence
     if (*pos == ' ' || *pos == '\n' || *pos == '\t') {
       sequenceStartAfterAWhitespace = true;
-      AppendWrapped_WhitespaceSequence(pos, end, sequenceStart, aOutputStr);
+      NS_ENSURE_TRUE(AppendWrapped_WhitespaceSequence(pos, end,
+        sequenceStart, aOutputStr), false);
     }
     else { // any other non-whitespace char
-      AppendWrapped_NonWhitespaceSequence(pos, end, sequenceStart,
-        mayIgnoreStartOfLineWhitespaceSequence, sequenceStartAfterAWhitespace, aOutputStr);
+      NS_ENSURE_TRUE(AppendWrapped_NonWhitespaceSequence(pos, end, sequenceStart,
+        mayIgnoreStartOfLineWhitespaceSequence,
+        sequenceStartAfterAWhitespace, aOutputStr), false);
     }
   }
+
+  return true;
 }
 
 bool
 nsXMLContentSerializer::ShouldMaintainPreLevel() const
 {
   // Only attempt to maintain the pre level for consumers who care about it.
   return !mDoRaw || (mFlags & nsIDocumentEncoder::OutputNoFormattingInPre);
 }
--- a/dom/base/nsXMLContentSerializer.h
+++ b/dom/base/nsXMLContentSerializer.h
@@ -67,83 +67,93 @@ class nsXMLContentSerializer : public ns
                                  nsAString& aStr) MOZ_OVERRIDE;
 
  protected:
   virtual ~nsXMLContentSerializer();
 
   /**
    * Appends a char16_t character and increments the column position
    */
-  void AppendToString(const char16_t aChar,
+  NS_WARN_UNUSED_RESULT
+  bool AppendToString(const char16_t aChar,
                       nsAString& aOutputStr);
 
   /**
    * Appends a nsAString string and increments the column position
    */
-  void AppendToString(const nsAString& aStr,
+  NS_WARN_UNUSED_RESULT
+  bool AppendToString(const nsAString& aStr,
                       nsAString& aOutputStr);
 
   /**
    * Appends a string by replacing all line-endings
    * by mLineBreak, except in the case of raw output.
    * It increments the column position.
    */
-  void AppendToStringConvertLF(const nsAString& aStr,
+  NS_WARN_UNUSED_RESULT
+  bool AppendToStringConvertLF(const nsAString& aStr,
                                nsAString& aOutputStr);
 
   /**
    * Appends a string by wrapping it when necessary.
    * It updates the column position.
    */
-  void AppendToStringWrapped(const nsASingleFragmentString& aStr,
+  NS_WARN_UNUSED_RESULT
+  bool AppendToStringWrapped(const nsASingleFragmentString& aStr,
                              nsAString& aOutputStr);
 
   /**
    * Appends a string by formating and wrapping it when necessary
    * It updates the column position.
    */
-  void AppendToStringFormatedWrapped(const nsASingleFragmentString& aStr,
+  NS_WARN_UNUSED_RESULT
+  bool AppendToStringFormatedWrapped(const nsASingleFragmentString& aStr,
                                      nsAString& aOutputStr);
 
   // used by AppendToStringWrapped
-  void AppendWrapped_WhitespaceSequence(
+  NS_WARN_UNUSED_RESULT
+  bool AppendWrapped_WhitespaceSequence(
           nsASingleFragmentString::const_char_iterator &aPos,
           const nsASingleFragmentString::const_char_iterator aEnd,
           const nsASingleFragmentString::const_char_iterator aSequenceStart,
           nsAString &aOutputStr);
 
   // used by AppendToStringFormatedWrapped
-  void AppendFormatedWrapped_WhitespaceSequence(
+  NS_WARN_UNUSED_RESULT
+  bool AppendFormatedWrapped_WhitespaceSequence(
           nsASingleFragmentString::const_char_iterator &aPos,
           const nsASingleFragmentString::const_char_iterator aEnd,
           const nsASingleFragmentString::const_char_iterator aSequenceStart,
           bool &aMayIgnoreStartOfLineWhitespaceSequence,
           nsAString &aOutputStr);
 
   // used by AppendToStringWrapped and AppendToStringFormatedWrapped
-  void AppendWrapped_NonWhitespaceSequence(
+  NS_WARN_UNUSED_RESULT
+  bool AppendWrapped_NonWhitespaceSequence(
           nsASingleFragmentString::const_char_iterator &aPos,
           const nsASingleFragmentString::const_char_iterator aEnd,
           const nsASingleFragmentString::const_char_iterator aSequenceStart,
           bool &aMayIgnoreStartOfLineWhitespaceSequence,
           bool &aSequenceStartAfterAWhiteSpace,
           nsAString &aOutputStr);
 
   /**
    * add mLineBreak to the string
    * It updates the column position and other flags.
    */
-  void AppendNewLineToString(nsAString& aOutputStr);
+  NS_WARN_UNUSED_RESULT
+  bool AppendNewLineToString(nsAString& aOutputStr);
 
 
   /**
    * Appends a string by translating entities
    * It doesn't increment the column position
    */
-  virtual void AppendAndTranslateEntities(const nsAString& aStr,
+  NS_WARN_UNUSED_RESULT
+  virtual bool AppendAndTranslateEntities(const nsAString& aStr,
                                           nsAString& aOutputStr);
 
   /**
    * retrieve the text content of the node and append it to the given string
    * It doesn't increment the column position
    */
   nsresult AppendTextData(nsIContent* aNode,
                           int32_t aStartOffset,
@@ -182,26 +192,28 @@ class nsXMLContentSerializer : public ns
    * GenerateNewPrefix generates a new prefix and writes it to aPrefix
    */
   void GenerateNewPrefix(nsAString& aPrefix);
 
   uint32_t ScanNamespaceDeclarations(nsIContent* aContent,
                                      nsIContent *aOriginalElement,
                                      const nsAString& aTagNamespaceURI);
 
-  virtual void SerializeAttributes(nsIContent* aContent,
+  NS_WARN_UNUSED_RESULT
+  virtual bool SerializeAttributes(nsIContent* aContent,
                                    nsIContent *aOriginalElement,
                                    nsAString& aTagPrefix,
                                    const nsAString& aTagNamespaceURI,
                                    nsIAtom* aTagName,
                                    nsAString& aStr,
                                    uint32_t aSkipAttr,
                                    bool aAddNSAttr);
 
-  void SerializeAttr(const nsAString& aPrefix,
+  NS_WARN_UNUSED_RESULT
+  bool SerializeAttr(const nsAString& aPrefix,
                      const nsAString& aName,
                      const nsAString& aValue,
                      nsAString& aStr,
                      bool aDoEscapeEntities);
 
   bool IsJavaScript(nsIContent * aContent,
                       nsIAtom* aAttrNameAtom,
                       int32_t aAttrNamespaceID,
@@ -212,35 +224,38 @@ class nsXMLContentSerializer : public ns
    * It is called when the serialization of the start tag is asked 
    * (AppendElementStart)
    * In this method you can also force the formating
    * by setting aForceFormat to true.
    * @return boolean  true if the element can be output
    */
   virtual bool CheckElementStart(nsIContent * aContent,
                                    bool & aForceFormat,
-                                   nsAString& aStr);
+                                   nsAString& aStr,
+                                   nsresult& aResult);
 
   /**
    * this method is responsible to finish the start tag,
    * in particulary to append the "greater than" sign
    */
-  virtual void AppendEndOfElementStart(nsIContent *aOriginalElement,
+  NS_WARN_UNUSED_RESULT
+  virtual bool AppendEndOfElementStart(nsIContent *aOriginalElement,
                                        nsIAtom * aName,
                                        int32_t aNamespaceID,
                                        nsAString& aStr);
 
   /**
    * This method can be redefine to serialize additional things just after
    * after the serialization ot the start tag.
    * (called at the end of AppendElementStart)
    */
-  virtual void AfterElementStart(nsIContent * aContent,
-                                 nsIContent *aOriginalElement,
-                                 nsAString& aStr) { };
+  NS_WARN_UNUSED_RESULT
+  virtual bool AfterElementStart(nsIContent* aContent,
+                                 nsIContent* aOriginalElement,
+                                 nsAString& aStr) { return true; };
 
   /**
    * This method can be redefined to check if the element can be serialized.
    * It is called when the serialization of the end tag is asked 
    * (AppendElementEnd)
    * In this method you can also force the formating
    * by setting aForceFormat to true.
    * @return boolean  true if the element can be output
@@ -276,23 +291,27 @@ class nsXMLContentSerializer : public ns
    * Returns true if a line break should be inserted after an element close tag
    */
   virtual bool LineBreakAfterClose(int32_t aNamespaceID, nsIAtom* aName);
 
   /**
    * add intendation. Call only in the case of formating and if the current
    * position is at 0. It updates the column position.
    */
-  void AppendIndentation(nsAString& aStr);
-  void IncrIndentation(nsIAtom* aName);
+  NS_WARN_UNUSED_RESULT
+  bool AppendIndentation(nsAString& aStr);
+
+  NS_WARN_UNUSED_RESULT
+  bool IncrIndentation(nsIAtom* aName);
   void DecrIndentation(nsIAtom* aName);
 
   // Functions to check for newlines that needs to be added between nodes in
   // the root of a document. See mAddNewlineForRootNode
-  void MaybeAddNewlineForRootNode(nsAString& aStr);
+  NS_WARN_UNUSED_RESULT
+  bool MaybeAddNewlineForRootNode(nsAString& aStr);
   void MaybeFlagNewlineForRootNode(nsINode* aNode);
 
   // Functions to check if we enter in or leave from a preformated content
   virtual void MaybeEnterInPreContent(nsIContent* aNode);
   virtual void MaybeLeaveFromPreContent(nsIContent* aNode);
 
   bool ShouldMaintainPreLevel() const;
   int32_t PreLevel() const {
--- a/xpcom/string/nsReadableUtils.cpp
+++ b/xpcom/string/nsReadableUtils.cpp
@@ -141,16 +141,26 @@ AppendASCIItoUTF16(const nsACString& aSo
 void
 LossyAppendUTF16toASCII(const char16_t* aSource, nsACString& aDest)
 {
   if (aSource) {
     LossyAppendUTF16toASCII(nsDependentString(aSource), aDest);
   }
 }
 
+bool
+AppendASCIItoUTF16(const char* aSource, nsAString& aDest, const mozilla::fallible_t& aFallible)
+{
+  if (aSource) {
+    return AppendASCIItoUTF16(nsDependentCString(aSource), aDest, aFallible);
+  }
+
+  return true;
+}
+
 void
 AppendASCIItoUTF16(const char* aSource, nsAString& aDest)
 {
   if (aSource) {
     AppendASCIItoUTF16(nsDependentCString(aSource), aDest);
   }
 }
 
--- a/xpcom/string/nsReadableUtils.h
+++ b/xpcom/string/nsReadableUtils.h
@@ -50,16 +50,19 @@ void CopyUTF8toUTF16(const char* aSource
 
 void LossyAppendUTF16toASCII(const nsAString& aSource, nsACString& aDest);
 void AppendASCIItoUTF16(const nsACString& aSource, nsAString& aDest);
 NS_WARN_UNUSED_RESULT bool AppendASCIItoUTF16(const nsACString& aSource,
                                               nsAString& aDest,
                                               const mozilla::fallible_t&);
 
 void LossyAppendUTF16toASCII(const char16_t* aSource, nsACString& aDest);
+NS_WARN_UNUSED_RESULT bool AppendASCIItoUTF16(const char* aSource,
+                                              nsAString& aDest,
+                                              const mozilla::fallible_t&);
 void AppendASCIItoUTF16(const char* aSource, nsAString& aDest);
 
 void AppendUTF16toUTF8(const nsAString& aSource, nsACString& aDest);
 NS_WARN_UNUSED_RESULT bool AppendUTF16toUTF8(const nsAString& aSource,
                                              nsACString& aDest,
                                              const mozilla::fallible_t&);
 void AppendUTF8toUTF16(const nsACString& aSource, nsAString& aDest);
 NS_WARN_UNUSED_RESULT bool AppendUTF8toUTF16(const nsACString& aSource,
--- a/xpcom/string/nsTSubstring.cpp
+++ b/xpcom/string/nsTSubstring.cpp
@@ -541,35 +541,51 @@ nsTSubstring_CharT::Replace(index_type a
 
   return true;
 }
 
 void
 nsTSubstring_CharT::ReplaceASCII(index_type aCutStart, size_type aCutLength,
                                  const char* aData, size_type aLength)
 {
+  if (!ReplaceASCII(aCutStart, aCutLength, aData, aLength, mozilla::fallible)) {
+    AllocFailed(Length() - aCutLength + 1);
+  }
+}
+
+bool
+nsTSubstring_CharT::ReplaceASCII(index_type aCutStart, size_type aCutLength,
+                                 const char* aData, size_type aLength,
+                                 const fallible_t& aFallible)
+{
   if (aLength == size_type(-1)) {
     aLength = strlen(aData);
   }
 
   // A Unicode string can't depend on an ASCII string buffer,
   // so this dependence check only applies to CStrings.
 #ifdef CharT_is_char
   if (IsDependentOn(aData, aData + aLength)) {
     nsTAutoString_CharT temp(aData, aLength);
-    Replace(aCutStart, aCutLength, temp);
-    return;
+    return Replace(aCutStart, aCutLength, temp, aFallible);
   }
 #endif
 
   aCutStart = XPCOM_MIN(aCutStart, Length());
 
-  if (ReplacePrep(aCutStart, aCutLength, aLength) && aLength > 0) {
+  bool ok = ReplacePrep(aCutStart, aCutLength, aLength);
+  if (!ok) {
+    return false;
+  }
+
+  if (aLength > 0) {
     char_traits::copyASCII(mData + aCutStart, aData, aLength);
   }
+
+  return true;
 }
 
 void
 nsTSubstring_CharT::Replace(index_type aCutStart, size_type aCutLength,
                             const substring_tuple_type& aTuple)
 {
   if (aTuple.IsDependentOn(mData, mData + mLength)) {
     nsTAutoString_CharT temp(aTuple);
--- a/xpcom/string/nsTSubstring.h
+++ b/xpcom/string/nsTSubstring.h
@@ -499,16 +499,21 @@ public:
   }
   void NS_FASTCALL Replace(index_type aCutStart, size_type aCutLength,
                            const substring_tuple_type& aTuple);
 
   void NS_FASTCALL ReplaceASCII(index_type aCutStart, size_type aCutLength,
                                 const char* aData,
                                 size_type aLength = size_type(-1));
 
+  NS_WARN_UNUSED_RESULT bool NS_FASTCALL ReplaceASCII(index_type aCutStart, size_type aCutLength,
+                                                      const char* aData,
+                                                      size_type aLength,
+                                                      const fallible_t&);
+
   // ReplaceLiteral must ONLY be applied to an actual literal string.
   // Do not attempt to use it with a regular char* pointer, or with a char
   // array variable. Use Replace or ReplaceASCII for those.
   template<int N>
   void ReplaceLiteral(index_type aCutStart, size_type aCutLength,
                       const char_type (&aStr)[N])
   {
     ReplaceLiteral(aCutStart, aCutLength, aStr, N - 1);
@@ -539,26 +544,40 @@ public:
     Append(static_cast<const char16_t*>(aData), aLength);
   }
 #endif
 
   void Append(const self_type& aStr)
   {
     Replace(mLength, 0, aStr);
   }
+  NS_WARN_UNUSED_RESULT bool Append(const self_type& aStr, const fallible_t& aFallible)
+  {
+    return Replace(mLength, 0, aStr, aFallible);
+  }
   void Append(const substring_tuple_type& aTuple)
   {
     Replace(mLength, 0, aTuple);
   }
 
   void AppendASCII(const char* aData, size_type aLength = size_type(-1))
   {
     ReplaceASCII(mLength, 0, aData, aLength);
   }
 
+  NS_WARN_UNUSED_RESULT bool AppendASCII(const char* aData, const fallible_t& aFallible)
+  {
+    return ReplaceASCII(mLength, 0, aData, size_type(-1), aFallible);
+  }
+
+  NS_WARN_UNUSED_RESULT bool AppendASCII(const char* aData, size_type aLength, const fallible_t& aFallible)
+  {
+    return ReplaceASCII(mLength, 0, aData, aLength, aFallible);
+  }
+
   /**
    * Append a formatted string to the current string. Uses the format
    * codes documented in prprf.h
    */
   void AppendPrintf(const char* aFormat, ...);
   void AppendPrintf(const char* aFormat, va_list aAp);
   void AppendInt(int32_t aInteger)
   {
@@ -613,16 +632,22 @@ public:
     ReplaceLiteral(mLength, 0, aStr, N - 1);
   }
 #ifdef CharT_is_PRUnichar
   template<int N>
   void AppendLiteral(const char (&aStr)[N])
   {
     AppendASCII(aStr, N - 1);
   }
+
+  template<int N>
+  NS_WARN_UNUSED_RESULT bool AppendLiteral(const char (&aStr)[N], const fallible_t& aFallible)
+  {
+    return AppendASCII(aStr, N - 1, aFallible);
+  }
 #endif
 
   self_type& operator+=(char_type aChar)
   {
     Append(aChar);
     return *this;
   }
   self_type& operator+=(const char_type* aData)