Files
palemoon27/xpcom/io/nsUnicharInputStream.cpp
roytam1 c5205b44c8 import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1240330 - mozAlarm debug messages are turned on r=khuey (aa938a4371)
- fix (cdc44e8bc8)
- Bug 1239788 - Don't include non-main-thread assertions in the constructor enabled check for [Exposed=System] WebIDL interfaces; r=bzbarsky (5d05b4066a)
- Bug 1247346. Slot indices on IDL interface members that get a slot should be per-interface, not a single per-member number. r=peterv (640231c37e)
- Bug 1157469 - null check wrapper in case WrapNode fails, r=bholley (9fd9b038db)
- Bug 1242211 - Mark MozMapRooter as final; r=baku (f3b5cc7728)
- Bug 1243438. Don't try to include the filename '<unknown>' when including headers for unions that have a built-in typedef they're referenced by. r=peterv (781d1ec0af)
- Bug 1241021 part 1: Refactor GenerateCSS2PropertiesWebIDL.py to invoke a helper function for each line. r=bz (258b031fd8)
- Bug 1241021 part 2: Make GenerateCSS2PropertiesWebIDL.py produce capitalized as well as uncapitalized WebkitFoo/webkitFoo DOM style accessors. r=bz (0bf2ec95ae)
- Bug 1241021 part 3: Refactor CSS mochitest test_initial_storage.html to perform its DOM accessor consistency-checks via a helper-function. r=bz (3a0c1a1678)
- Bug 1241021 part 4: Extend mochitest test_initial_storage.html to test that uppercase Webkit DOM accessors for css properties are functional. r=bz (5a6a23c7ab)
- Bug 1240592 - Remove unnecessary -Wno-uninitialized from dom/bindings. r=khuey (c854f7b397)
- Bug 1200341 - Implement HKDF for WebCrypto r=rbarnes,smaug (2c830d65a1)
- Bug 1200341 - Use BufferSource instead of CryptoOperationData in the SubtleCrypto WebIDL spec r=smaug (8cece95b5c)
- Bug 1191936 - Implement RSA-PSS key generation r=rbarnes (ec9654595c)
- Bug 1191936 - Implement RSA-PSS signing and verification r=rbarnes,smaug (7653bdfced)
- Bug 1204763 follow-up: Fix the comments, DONTBUILD (8b26e6f3a9)
- Reformat clang-plugin.cpp using clang-format, no bug (9346eda9f4)
- Bug 1214037 - Don't consider the result of an assignment expression MOZ_MUST_USE, r=ehsan (70c7830c3a)
- Bug 1242789 - Allow lambdas to capture raw pointers to refcounted objects by reference, r=ehsan (e7158a7746)
- Bug 1238042 - Add about:checkerboard. r=ehsan,botond (f234ce7fa0)
- Bug 1237177. Make the this-rebinding callable proxy sandboxes use return the prototype of its target, not its own null prototype. r=efaust (694a8081dc)
- Bug 1248521 - Pack PrefHashEntry better. r=froydnj. (55e9d609fe)
- Bug 1240453 - enable shared memory in xpconnect. r=bz (58db0b406e)
- Bug 1202014 - Don't use-after-move in ActorsChild.cpp, r=khuey (382e7183c0)
- Bug 1136762 - TSan: data race xpcom/io/nsPipe3.cpp:1061 CloseWithStatus. r=nfroyd. (68fd82971d)
- Bug 1237668 - Remove nsSimpleUnicharStreamFactory r=froydnj (8bb6ec081c)
- Bug 1189998, Part 4 - Add authentication secret to Push data test. r=dragana (122a0bd5f9)
- Bug 1205137 - Add a PushSubscription serializer. r=mt,smaug (aa9e847c42)
- Bug 1232910 - Use channel.asyncOpen2 within dom/push/PushServiceHttp2.jsm. r=sicking r=dragana (a2f483a983)
- Bug 1246632 - Fix ackMsgRecv in PushServiceHttp2.js. r=kitcambridge (c1559e0539)
- Bug 1240615 - Make PushService protocol init method return a Promise. r=kitcambridge (4d52dc6a41)
- Bug 1246784 - Expose Console to the WorkerDebuggerGlobalScope, r=khuey (a992fdc555)
- misspatch (33708903c4)
- Bug 1207494 - Part 5: Remove use of expression closure from dom/contacts/. r=reuben (256b3831a4)
- Bug 1207494 - Part 4: Remove use of expression closure from dom/canvas/. r=gw280 (1666e49673)
- Bug 1207494 - Part 3: Remove use of expression closure from dom/browser-element/. r=smaug (a891769373)
- Bug 1207494 - Part 2: Remove use of expression closure from dom/base/test/. r=peterv (01762e3181)
- Bug 1207494 - Part 1: Remove use of expression closure from dom/apps/. r=ferjm (2474c8619b)
- Bug 1247108 - Pass securityFlag when creating a new channel within webapps (r=fabrice) (8305294f26)
- Bug 1219004 - Improve error management in getFullAppByManifestURL r=ferjm (c3ad64df7a)
- revert contains/includes (29c60a77e5)
- Bug 1147562 - Update remaining callsites of newChannel before landing the shim in dom/ (r=sicking) (0cd64e20e1)
- Bug 1243924 - Convert remaining callsites within dom/ to use channel.open2() (r=sicking) (43b01f88ba)
- Bug 1162658 - Update FormData to match latest spec, r=smaug (a42ca52ad5)
- Bug 1208895 - Fix a typo in nsGenericHTMLElement::GetItemId(); r=baku (2d6f2d79f4)
- Bug 1223523. The named getter on document should not return images with an empty name. r=peterv (da3d1f52f5)
- Bug 1183491. Null-check the document we get from our contentWindow in the contentDocument getter, because apparently it can end up null. r=bkelly (3002a4375c)
- Bug 1203430 - Intermittent crash in PNeckoChild::SendHTMLDNSPrefetch. r=jdm (3b82b57cbf)
- Bug 893332, part 1 - Rename misnamed SetValidityState/GetValidityState arguments. r=baku (d403b12c9a)
- Bug 893332, part 2 - Update validity state before asserting range underflow state. r=baku (a4cbce224c)
- Bug 893332, part 3 - Don't assert range underflow state under the parser. r=baku (763e99ed8e)
- Bug 893332, part 4 - Crashtests. r=baku (7cdcdc02c4)
- Bug 1240336 Setting same value to either <input> or <textarea> shouldn't cause committing existing composition r=ehsan (5cc2c35dbb)
- Bug 1228708. Fix UndoManager to correctly suppress exceptions it wants to suppress on ErrorResults. r=smaug (905207a3b4)
- Bug 1230295 - Add telemetry to report when Ogg chaining is used. r=rillian,r=vladan (e47c49f508)
2023-12-29 16:00:23 +08:00

399 lines
10 KiB
C++

/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "nsUnicharInputStream.h"
#include "nsIInputStream.h"
#include "nsIServiceManager.h"
#include "nsString.h"
#include "nsTArray.h"
#include "nsAutoPtr.h"
#include "nsCRT.h"
#include "nsStreamUtils.h"
#include "nsUTF8Utils.h"
#include "mozilla/Attributes.h"
#include <fcntl.h>
#if defined(XP_WIN)
#include <io.h>
#else
#include <unistd.h>
#endif
#define STRING_BUFFER_SIZE 8192
class StringUnicharInputStream final : public nsIUnicharInputStream
{
public:
explicit StringUnicharInputStream(const nsAString& aString) :
mString(aString), mPos(0), mLen(aString.Length()) { }
NS_DECL_ISUPPORTS
NS_DECL_NSIUNICHARINPUTSTREAM
nsString mString;
uint32_t mPos;
uint32_t mLen;
private:
~StringUnicharInputStream() { }
};
NS_IMETHODIMP
StringUnicharInputStream::Read(char16_t* aBuf,
uint32_t aCount,
uint32_t* aReadCount)
{
if (mPos >= mLen) {
*aReadCount = 0;
return NS_OK;
}
nsAString::const_iterator iter;
mString.BeginReading(iter);
const char16_t* us = iter.get();
uint32_t amount = mLen - mPos;
if (amount > aCount) {
amount = aCount;
}
memcpy(aBuf, us + mPos, sizeof(char16_t) * amount);
mPos += amount;
*aReadCount = amount;
return NS_OK;
}
NS_IMETHODIMP
StringUnicharInputStream::ReadSegments(nsWriteUnicharSegmentFun aWriter,
void* aClosure,
uint32_t aCount, uint32_t* aReadCount)
{
uint32_t bytesWritten;
uint32_t totalBytesWritten = 0;
nsresult rv;
aCount = XPCOM_MIN(mString.Length() - mPos, aCount);
nsAString::const_iterator iter;
mString.BeginReading(iter);
while (aCount) {
rv = aWriter(this, aClosure, iter.get() + mPos,
totalBytesWritten, aCount, &bytesWritten);
if (NS_FAILED(rv)) {
// don't propagate errors to the caller
break;
}
aCount -= bytesWritten;
totalBytesWritten += bytesWritten;
mPos += bytesWritten;
}
*aReadCount = totalBytesWritten;
return NS_OK;
}
NS_IMETHODIMP
StringUnicharInputStream::ReadString(uint32_t aCount, nsAString& aString,
uint32_t* aReadCount)
{
if (mPos >= mLen) {
*aReadCount = 0;
return NS_OK;
}
uint32_t amount = mLen - mPos;
if (amount > aCount) {
amount = aCount;
}
aString = Substring(mString, mPos, amount);
mPos += amount;
*aReadCount = amount;
return NS_OK;
}
nsresult
StringUnicharInputStream::Close()
{
mPos = mLen;
return NS_OK;
}
NS_IMPL_ISUPPORTS(StringUnicharInputStream, nsIUnicharInputStream)
//----------------------------------------------------------------------
class UTF8InputStream final : public nsIUnicharInputStream
{
public:
UTF8InputStream();
nsresult Init(nsIInputStream* aStream);
NS_DECL_ISUPPORTS
NS_DECL_NSIUNICHARINPUTSTREAM
private:
~UTF8InputStream();
protected:
int32_t Fill(nsresult* aErrorCode);
static void CountValidUTF8Bytes(const char* aBuf, uint32_t aMaxBytes,
uint32_t& aValidUTF8bytes,
uint32_t& aValidUTF16CodeUnits);
nsCOMPtr<nsIInputStream> mInput;
FallibleTArray<char> mByteData;
FallibleTArray<char16_t> mUnicharData;
uint32_t mByteDataOffset;
uint32_t mUnicharDataOffset;
uint32_t mUnicharDataLength;
};
UTF8InputStream::UTF8InputStream() :
mByteDataOffset(0),
mUnicharDataOffset(0),
mUnicharDataLength(0)
{
}
nsresult
UTF8InputStream::Init(nsIInputStream* aStream)
{
if (!mByteData.SetCapacity(STRING_BUFFER_SIZE, mozilla::fallible) ||
!mUnicharData.SetCapacity(STRING_BUFFER_SIZE, mozilla::fallible)) {
return NS_ERROR_OUT_OF_MEMORY;
}
mInput = aStream;
return NS_OK;
}
NS_IMPL_ISUPPORTS(UTF8InputStream, nsIUnicharInputStream)
UTF8InputStream::~UTF8InputStream()
{
Close();
}
nsresult
UTF8InputStream::Close()
{
mInput = nullptr;
mByteData.Clear();
mUnicharData.Clear();
return NS_OK;
}
nsresult
UTF8InputStream::Read(char16_t* aBuf, uint32_t aCount, uint32_t* aReadCount)
{
NS_ASSERTION(mUnicharDataLength >= mUnicharDataOffset, "unsigned madness");
uint32_t readCount = mUnicharDataLength - mUnicharDataOffset;
nsresult errorCode;
if (0 == readCount) {
// Fill the unichar buffer
int32_t bytesRead = Fill(&errorCode);
if (bytesRead <= 0) {
*aReadCount = 0;
return errorCode;
}
readCount = bytesRead;
}
if (readCount > aCount) {
readCount = aCount;
}
memcpy(aBuf, mUnicharData.Elements() + mUnicharDataOffset,
readCount * sizeof(char16_t));
mUnicharDataOffset += readCount;
*aReadCount = readCount;
return NS_OK;
}
NS_IMETHODIMP
UTF8InputStream::ReadSegments(nsWriteUnicharSegmentFun aWriter,
void* aClosure,
uint32_t aCount, uint32_t* aReadCount)
{
NS_ASSERTION(mUnicharDataLength >= mUnicharDataOffset, "unsigned madness");
uint32_t bytesToWrite = mUnicharDataLength - mUnicharDataOffset;
nsresult rv = NS_OK;
if (0 == bytesToWrite) {
// Fill the unichar buffer
int32_t bytesRead = Fill(&rv);
if (bytesRead <= 0) {
*aReadCount = 0;
return rv;
}
bytesToWrite = bytesRead;
}
if (bytesToWrite > aCount) {
bytesToWrite = aCount;
}
uint32_t bytesWritten;
uint32_t totalBytesWritten = 0;
while (bytesToWrite) {
rv = aWriter(this, aClosure,
mUnicharData.Elements() + mUnicharDataOffset,
totalBytesWritten, bytesToWrite, &bytesWritten);
if (NS_FAILED(rv)) {
// don't propagate errors to the caller
break;
}
bytesToWrite -= bytesWritten;
totalBytesWritten += bytesWritten;
mUnicharDataOffset += bytesWritten;
}
*aReadCount = totalBytesWritten;
return NS_OK;
}
NS_IMETHODIMP
UTF8InputStream::ReadString(uint32_t aCount, nsAString& aString,
uint32_t* aReadCount)
{
NS_ASSERTION(mUnicharDataLength >= mUnicharDataOffset, "unsigned madness");
uint32_t readCount = mUnicharDataLength - mUnicharDataOffset;
nsresult errorCode;
if (0 == readCount) {
// Fill the unichar buffer
int32_t bytesRead = Fill(&errorCode);
if (bytesRead <= 0) {
*aReadCount = 0;
return errorCode;
}
readCount = bytesRead;
}
if (readCount > aCount) {
readCount = aCount;
}
const char16_t* buf = mUnicharData.Elements() + mUnicharDataOffset;
aString.Assign(buf, readCount);
mUnicharDataOffset += readCount;
*aReadCount = readCount;
return NS_OK;
}
int32_t
UTF8InputStream::Fill(nsresult* aErrorCode)
{
if (!mInput) {
// We already closed the stream!
*aErrorCode = NS_BASE_STREAM_CLOSED;
return -1;
}
NS_ASSERTION(mByteData.Length() >= mByteDataOffset, "unsigned madness");
uint32_t remainder = mByteData.Length() - mByteDataOffset;
mByteDataOffset = remainder;
uint32_t nb;
*aErrorCode = NS_FillArray(mByteData, mInput, remainder, &nb);
if (nb == 0) {
// Because we assume a many to one conversion, the lingering data
// in the byte buffer must be a partial conversion
// fragment. Because we know that we have received no more new
// data to add to it, we can't convert it. Therefore, we discard
// it.
return nb;
}
NS_ASSERTION(remainder + nb == mByteData.Length(), "bad nb");
// Now convert as much of the byte buffer to unicode as possible
uint32_t srcLen, dstLen;
CountValidUTF8Bytes(mByteData.Elements(), remainder + nb, srcLen, dstLen);
// the number of UCS2 characters should always be <= the number of
// UTF8 chars
NS_ASSERTION(remainder + nb >= srcLen, "cannot be longer than out buffer");
NS_ASSERTION(dstLen <= mUnicharData.Capacity(),
"Ouch. I would overflow my buffer if I wasn't so careful.");
if (dstLen > mUnicharData.Capacity()) {
return 0;
}
ConvertUTF8toUTF16 converter(mUnicharData.Elements());
nsASingleFragmentCString::const_char_iterator start = mByteData.Elements();
nsASingleFragmentCString::const_char_iterator end = mByteData.Elements() + srcLen;
copy_string(start, end, converter);
if (converter.Length() != dstLen) {
*aErrorCode = NS_BASE_STREAM_BAD_CONVERSION;
return -1;
}
mUnicharDataOffset = 0;
mUnicharDataLength = dstLen;
mByteDataOffset = srcLen;
return dstLen;
}
void
UTF8InputStream::CountValidUTF8Bytes(const char* aBuffer, uint32_t aMaxBytes,
uint32_t& aValidUTF8bytes,
uint32_t& aValidUTF16CodeUnits)
{
const char* c = aBuffer;
const char* end = aBuffer + aMaxBytes;
const char* lastchar = c; // pre-initialize in case of 0-length buffer
uint32_t utf16length = 0;
while (c < end && *c) {
lastchar = c;
utf16length++;
if (UTF8traits::isASCII(*c)) {
c++;
} else if (UTF8traits::is2byte(*c)) {
c += 2;
} else if (UTF8traits::is3byte(*c)) {
c += 3;
} else if (UTF8traits::is4byte(*c)) {
c += 4;
utf16length++; // add 1 more because this will be converted to a
// surrogate pair.
} else if (UTF8traits::is5byte(*c)) {
c += 5;
} else if (UTF8traits::is6byte(*c)) {
c += 6;
} else {
NS_WARNING("Unrecognized UTF8 string in UTF8InputStream::CountValidUTF8Bytes()");
break; // Otherwise we go into an infinite loop. But what happens now?
}
}
if (c > end) {
c = lastchar;
utf16length--;
}
aValidUTF8bytes = c - aBuffer;
aValidUTF16CodeUnits = utf16length;
}
nsresult
NS_NewUnicharInputStream(nsIInputStream* aStreamToWrap,
nsIUnicharInputStream** aResult)
{
*aResult = nullptr;
// Create converter input stream
RefPtr<UTF8InputStream> it = new UTF8InputStream();
nsresult rv = it->Init(aStreamToWrap);
if (NS_FAILED(rv)) {
return rv;
}
it.forget(aResult);
return NS_OK;
}