Bug 1883861 - Part 1: Move visitMemoryBarrier into the common CodeGenerator file...
[gecko.git] / layout / style / StreamLoader.cpp
blob3e8bd37d76317dbd9429312f43b78a5eca70ca76
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "mozilla/css/StreamLoader.h"
9 #include "mozilla/Encoding.h"
10 #include "mozilla/TaskQueue.h"
11 #include "nsContentUtils.h"
12 #include "nsIChannel.h"
13 #include "nsIInputStream.h"
14 #include "nsIThreadRetargetableRequest.h"
15 #include "nsIStreamTransportService.h"
16 #include "nsNetCID.h"
17 #include "nsServiceManagerUtils.h"
19 namespace mozilla::css {
21 StreamLoader::StreamLoader(SheetLoadData& aSheetLoadData)
22 : mSheetLoadData(&aSheetLoadData), mStatus(NS_OK) {}
24 StreamLoader::~StreamLoader() {
25 #ifdef NIGHTLY_BUILD
26 MOZ_RELEASE_ASSERT(mOnStopRequestCalled || mChannelOpenFailed);
27 #endif
30 NS_IMPL_ISUPPORTS(StreamLoader, nsIStreamListener,
31 nsIThreadRetargetableStreamListener)
33 /* nsIRequestObserver implementation */
34 NS_IMETHODIMP
35 StreamLoader::OnStartRequest(nsIRequest* aRequest) {
36 MOZ_ASSERT(aRequest);
37 mSheetLoadData->NotifyStart(aRequest);
39 // It's kinda bad to let Web content send a number that results
40 // in a potentially large allocation directly, but efficiency of
41 // compression bombs is so great that it doesn't make much sense
42 // to require a site to send one before going ahead and allocating.
43 if (nsCOMPtr<nsIChannel> channel = do_QueryInterface(aRequest)) {
44 int64_t length;
45 nsresult rv = channel->GetContentLength(&length);
46 if (NS_SUCCEEDED(rv) && length > 0) {
47 CheckedInt<nsACString::size_type> checkedLength(length);
48 if (!checkedLength.isValid()) {
49 return (mStatus = NS_ERROR_OUT_OF_MEMORY);
51 if (!mBytes.SetCapacity(checkedLength.value(), fallible)) {
52 return (mStatus = NS_ERROR_OUT_OF_MEMORY);
56 if (nsCOMPtr<nsIThreadRetargetableRequest> rr = do_QueryInterface(aRequest)) {
57 nsCOMPtr<nsIEventTarget> sts =
58 do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID);
59 RefPtr queue =
60 TaskQueue::Create(sts.forget(), "css::StreamLoader Delivery Queue");
61 rr->RetargetDeliveryTo(queue);
64 mSheetLoadData->mExpirationTime = [&] {
65 auto info = nsContentUtils::GetSubresourceCacheValidationInfo(
66 aRequest, mSheetLoadData->mURI);
68 // For now, we never cache entries that we have to revalidate, or whose
69 // channel don't support caching.
70 if (info.mMustRevalidate || !info.mExpirationTime) {
71 return nsContentUtils::SecondsFromPRTime(PR_Now()) - 1;
73 return *info.mExpirationTime;
74 }();
76 return NS_OK;
79 NS_IMETHODIMP
80 StreamLoader::CheckListenerChain() { return NS_OK; }
82 NS_IMETHODIMP
83 StreamLoader::OnStopRequest(nsIRequest* aRequest, nsresult aStatus) {
84 #ifdef NIGHTLY_BUILD
85 MOZ_RELEASE_ASSERT(!mOnStopRequestCalled);
86 mOnStopRequestCalled = true;
87 #endif
89 nsresult rv = mStatus;
90 // Decoded data
91 nsCString utf8String;
93 // Hold the nsStringBuffer for the bytes from the stack to ensure release
94 // no matter which return branch is taken.
95 nsCString bytes = std::move(mBytes);
97 nsCOMPtr<nsIChannel> channel = do_QueryInterface(aRequest);
99 if (NS_FAILED(mStatus)) {
100 mSheetLoadData->VerifySheetReadyToParse(mStatus, ""_ns, ""_ns, channel);
101 return mStatus;
104 rv = mSheetLoadData->VerifySheetReadyToParse(aStatus, mBOMBytes, bytes,
105 channel);
106 if (rv != NS_OK_PARSE_SHEET) {
107 return rv;
110 // BOM detection generally happens during the write callback, but that won't
111 // have happened if fewer than three bytes were received.
112 if (mEncodingFromBOM.isNothing()) {
113 HandleBOM();
114 MOZ_ASSERT(mEncodingFromBOM.isSome());
117 // The BOM handling has happened, but we still may not have an encoding if
118 // there was no BOM. Ensure we have one.
119 const Encoding* encoding = mEncodingFromBOM.value();
120 if (!encoding) {
121 // No BOM
122 encoding = mSheetLoadData->DetermineNonBOMEncoding(bytes, channel);
124 mSheetLoadData->mEncoding = encoding;
126 size_t validated = 0;
127 if (encoding == UTF_8_ENCODING) {
128 validated = Encoding::UTF8ValidUpTo(bytes);
131 if (validated == bytes.Length()) {
132 // Either this is UTF-8 and all valid, or it's not UTF-8 but is an empty
133 // string. This assumes that an empty string in any encoding decodes to
134 // empty string, which seems like a plausible assumption.
135 utf8String = std::move(bytes);
136 } else {
137 rv = encoding->DecodeWithoutBOMHandling(bytes, utf8String, validated);
138 NS_ENSURE_SUCCESS(rv, rv);
140 } // run destructor for `bytes`
142 // For reasons I don't understand, factoring the below lines into
143 // a method on SheetLoadData resulted in a linker error. Hence,
144 // accessing fields of mSheetLoadData from here.
145 mSheetLoadData->mLoader->ParseSheet(utf8String, *mSheetLoadData,
146 Loader::AllowAsyncParse::Yes);
148 return NS_OK;
151 /* nsIStreamListener implementation */
152 NS_IMETHODIMP
153 StreamLoader::OnDataAvailable(nsIRequest*, nsIInputStream* aInputStream,
154 uint64_t, uint32_t aCount) {
155 if (NS_FAILED(mStatus)) {
156 return mStatus;
158 uint32_t dummy;
159 return aInputStream->ReadSegments(WriteSegmentFun, this, aCount, &dummy);
162 NS_IMETHODIMP
163 StreamLoader::OnDataFinished(nsresult aStatus) { return NS_OK; }
165 void StreamLoader::HandleBOM() {
166 MOZ_ASSERT(mEncodingFromBOM.isNothing());
167 MOZ_ASSERT(mBytes.IsEmpty());
169 auto [encoding, bomLength] = Encoding::ForBOM(mBOMBytes);
170 mEncodingFromBOM.emplace(encoding); // Null means no BOM.
172 // BOMs are three bytes at most, but may be fewer. Copy over anything
173 // that wasn't part of the BOM to mBytes. Note that we need to track
174 // any BOM bytes as well for SRI handling.
175 mBytes.Append(Substring(mBOMBytes, bomLength));
176 mBOMBytes.Truncate(bomLength);
179 nsresult StreamLoader::WriteSegmentFun(nsIInputStream*, void* aClosure,
180 const char* aSegment, uint32_t,
181 uint32_t aCount, uint32_t* aWriteCount) {
182 *aWriteCount = 0;
183 StreamLoader* self = static_cast<StreamLoader*>(aClosure);
184 if (NS_FAILED(self->mStatus)) {
185 return self->mStatus;
188 // If we haven't done BOM detection yet, divert bytes into the special buffer.
189 if (self->mEncodingFromBOM.isNothing()) {
190 size_t bytesToCopy = std::min<size_t>(3 - self->mBOMBytes.Length(), aCount);
191 self->mBOMBytes.Append(aSegment, bytesToCopy);
192 aSegment += bytesToCopy;
193 *aWriteCount += bytesToCopy;
194 aCount -= bytesToCopy;
196 if (self->mBOMBytes.Length() == 3) {
197 self->HandleBOM();
198 } else {
199 return NS_OK;
203 if (!self->mBytes.Append(aSegment, aCount, fallible)) {
204 self->mBytes.Truncate();
205 return (self->mStatus = NS_ERROR_OUT_OF_MEMORY);
208 *aWriteCount += aCount;
209 return NS_OK;
212 } // namespace mozilla::css