Bug 1362194 - part 3 - make Base64Decode even more tolerant of allocation failures; r=mccr8

The lossy conversion to ASCII here can also fail; we should handle that
as well.  Rewriting the code to use MakeScopeExit also avoids tangled
logic and/or duplicating calls to ensure the destination string is
truncated on failure.
This commit is contained in:
Nathan Froyd 2017-05-05 11:33:36 -04:00
parent 8b000da91e
commit 880d162a51

View File

@ -6,6 +6,7 @@
#include "Base64.h"
#include "mozilla/ScopeExit.h"
#include "mozilla/UniquePtrExtensions.h"
#include "nsIInputStream.h"
#include "nsString.h"
@ -464,19 +465,26 @@ Base64Decode(const nsACString& aBase64, nsACString& aBinary)
nsresult
Base64Decode(const nsAString& aBase64, nsAString& aBinary)
{
NS_LossyConvertUTF16toASCII base64(aBase64);
auto truncater = mozilla::MakeScopeExit([&]() { aBinary.Truncate(); });
// XXX We should really consider decoding directly from the string, rather
// than making a separate copy here.
nsAutoCString base64;
if (!base64.SetCapacity(aBase64.Length(), mozilla::fallible)) {
return NS_ERROR_OUT_OF_MEMORY;
}
LossyCopyUTF16toASCII(aBase64, base64);
nsAutoCString binary;
nsresult rv = Base64Decode(base64, binary);
if (NS_SUCCEEDED(rv)) {
if (!CopyASCIItoUTF16(binary, aBinary, mozilla::fallible)) {
rv = NS_ERROR_OUT_OF_MEMORY;
}
NS_ENSURE_STATE(rv, rv);
if (!CopyASCIItoUTF16(binary, aBinary, mozilla::fallible)) {
return NS_ERROR_OUT_OF_MEMORY;
}
if (NS_FAILED(rv)) {
aBinary.Truncate();
}
truncater.release();
return rv;
}