diff --git a/parser/htmlparser/src/nsScanner.cpp b/parser/htmlparser/src/nsScanner.cpp
index 9e0473811b0..b004aea3346 100644
--- a/parser/htmlparser/src/nsScanner.cpp
+++ b/parser/htmlparser/src/nsScanner.cpp
@@ -358,6 +358,15 @@ nsresult nsScanner::Append(const char* aBuffer, PRUint32 aLen){
if(NS_FAILED(res)) {
// if we failed, we consume one byte, replace it with U+FFFD
// and try the conversion again.
+
+ // This is only needed because some decoders don't follow the
+ // nsIUnicodeDecoder contract: they return a failure when *aDestLength
+ // is 0 rather than the correct NS_OK_UDEC_MOREOUTPUT. See bug 244177
+ if ((unichars + unicharLength) >= buffer->DataEnd()) {
+ NS_ERROR("Unexpected end of destination buffer");
+ break;
+ }
+
unichars[unicharLength++] = (PRUnichar)0xFFFD;
unichars = unichars + unicharLength;
unicharLength = unicharBufLen - (++totalChars);