Files
palemoon27/netwerk/cache2/CacheFileChunk.cpp
T
roytam1 8a0a002cf2 import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1148708: Add missing 'override' annotations in DocAccessibleChild.h. rs=ehsan (d606358545)
- Bug 1210408 - make nsMaiInterfaceAction work with proxies, r=tbsaunde (f7c819c6ae)
- Bug 1210407 - teach nsMaiInterfaceTable to use proxies, r=tbsaunde (4ca4f10b5f)
- bug 1185157 make sure we don't send an event to a destroyed ipc document r=billm (23acf53f75)
- bug 1214864 - make SetCarretOffset() async r=davidb (e3079e9b2d)
- missing of Bug 1139972 - IPC Proxy for charAt, r=tbsaunde (e9593ed752)
- bug 1191598 - Pass MOZ_CURRENT_PROJECT in environment when running post-build automation steps for universal mac builds. r=gps (fc342c6ced)
- Bug 1164596 - Add mach android-emulator command; r=ahal (afeb9b27d1)
- Bug 1223149 - Add basic usage documentation for mach build; r=glandium (bfb802d175)
- Bug 1182301 - Improve 'mach build' notifications. r=gps (2c65a122d1)
- Bug 1184696 - Add clobber targets to |mach clobber|; Ability to clobber compiled python files, r=gps (35d8be292e)
- Bug 1117958 - Allow any debugging options to the run or gtest mach subcommands to automatically enable debugging. r=gps (32f986af4b)
- Bug 1180081 - Properly rebuild gtest/libxul before running gtests. r=gps (80db9a3d49)
- Bug 1171647, part 1 - Define a new function to convert the mode to a string. r=njn (61ad16f5ba)
- Bug 1171647, part 2 - Remove redundant assertion for dark matter mode. r=njn (b5ac9519f3)
- Bug 1058178, part 1 - Implement DMD heap scanning mode. r=njn (60e1079536)
- Bug 1058178, part 2 - Implement address clamping analysis for DMD scan logs. r=njn (45c0326b93)
- Bug 1102388 - Fix DMD static constructor ordering dependency. r=mccr8 (59b87897a1)
- Bug 1128705 - Don't redefine PAGE_SIZE in DMD if it's already defined. r=erahm (49216348ee)
- Bug 1179042 - Add a script for analyzing memory blocks using a heap scan DMD log. r=njn DONTBUILD (1c08d2d66e)
- Bug 1207245 - part 6 - rename nsRefPtr<T> to RefPtr<T>; r=ehsan; a=Tomcat (1c999d139b)
- Bug 1158772 - fix non-idiomatic memset call in nsDeque.cpp; r=erahm (de6b555245)
- Bug 1199400 - Part 1: Use CheckedInt when growing nsDeque capacity. r=froydnj (dfdf6814a3)
- Bug 1199400 - Part 0: Remove unused nsDequeIterator. r=froydnj (38d69d7f47)
- Bug 1199400 - Part 2: Add tests for possible nsDeque corner cases. r=froydnj (931baff195)
- Bug 1201997 - Part 1 - Converted compiled test to gtest for nsDeque class. Added tests to test untested methods. r=froydn (e893916651)
- Bug 1201997 - Part 2 - Removing unused methods from the nsDeque class. r=froydn (41595a90ac)
- Bug 1201997 - Part 3 - Make internally used methods private. r=froydn (8cd3afd96f)
- Bug 1201997 - Part 4 - Change size and offset variables to size_t.r=froydn (73eabc8d60)
- Bug 1215140 P1 Add an nsIConsoleReportCollector interface to support navigation channel logging. r=bz (8a41535e2b)
- Bug 1215140 P2 Make HttpBaseChannel implement nsIConsoleReportCollector. r=bz (75fca301f2)
- Bug 1197679 - If nsUnknownDecoder is involved in e10s DivertToParent can break. r=jduell (5d94a12504)
- Bug 1178991 - smartptr for http converter r=hurley (8e7fbc8443)
- bug 366559 - patch 2, fix nsHTTPCompressConv indentation r=bagder (ba762da587)
- bug 366559 - patch 3, fix nsHTTPCompressConv bracing style r=bagder (54195ab451)
- bits of  bug 366559 - patch 7, content-encoding brotli for http (f0b4051022)
- Bug 1205112 - Make PushEvent.data nullable. r=mt,smaug (775db32856)
- Bug 1193414 - SharedWorkers thread should be kept alive also when the SharedWorker object is CCed, r=khuey (b77ea8125c)
- Bug 1206520: Add about:config prefs to enable throwing on asm.js validation failures; r=bz (c42126665d)
- Bug 1193414 - Telemetry for SharedWorker spawning. r=bkelly (77984b7bcc)
- Bug 1205676 - Enable WPT service-worker/unregister-then-register-new-script.https.html in e10s, r=nsm (ec24939cf6)
- Bug 1193133 - Throw when calling postMessage from a Service Worker dom object with no global. r=bkelly (526dcacfab)
- Bug 1181871 P1 Only enforce Cache Context shared data destruction on target thread after init. r=ehsan (cdbf3ed3a8)
- Bug 1181871 P2 Fix ServiceWorkerManager usage of stack-based ErrorResult. r=ehsan (c449195d90)
- minor cleanup and missing bit of 1198230 (02f459db05)
- Bug 1143717 - Implement the ServiceWorkerMessageEvent interface. r=baku (027b3465f2)
- fix misspatch (708eee4e84)
- Bug 1188545 - Disentangle service workers from shared workers and refactor event dispatching code into a separate class. r=nsm,mrbkap (fb5b5341c9)
- Bug 1205228 - Change PackagedAppVerifier to notify the verification result asynchronously. r=valentin. (9edda0fa00)
- Bug 1178518 - Packaged App Utils. r=valentin (f60f3b7a93)
- Bug 1213150 - Part 1: Add a nsContentUtils::IsNonSubresourceRequest helper; r=jdm (b509cc3cc9)
- Bug 1213150 - Part 2: Rework ShouldPrepareForIntercept() in terms of subresource requests; r=jdm (2e92fe8780)
- Bug 1213150 - Part 3: Remove nsIInterceptedChannel.isNavigation; r=jdm (becf1cc12f)
- Bug 1213150 follow-up: fix build bustage (8d73d6ca73)
- Bug 1198394 - Part 1: Allow interception of HSTS upgraded connections in non-e10s mode; r=mcmanus (f504c5be08)
- Bug 1198394 - Part 2: Add a test for interception of HSTS upgraded connections; r=jdm (054e984eef)
- Bug 1187011 - Don't allow response body with null body status. r=bkelly (b1860741d1)
- missing bit of 1140788 (29d319712e)
- Bug 1213436 - Reject core dumps with node IDs that don't fit in an IEEE 754 double; r=sfink (3c1f6fdda0)
- Bug 1211006 - Add Debugger.Source.prototype.canonicalId; r=ejpbruel (eef7b79fce)
- Bug 1199218 - Implement JS::ubi::Node::size for js::LazyScript referents; r=sfink (098a48d240)
- Bug 1220031 - Add JS::ubi::Node::scriptFilename; r=sfink (6b824ae680)
- Bug 1143575. Remove unused MediaQueue::Empty. r=cpearce (de737f3433)
- Bug 1209933 - Make sure all parent runtime pointers are the topmost parent, r=billm. (fe824d967d)
- Bug 1197012 - Fix ThrowTypeError in Notification. r=mccr8 (0b1a097526)
- Bug 1197893 - Check the number of arguments for ThrowTypeError() and ThrowRangeError() at compile time. r=peterv (d98c7d78a0)
- Bug 1142083 - Add test for IDN Unicode domain redirect. r=mcmanus (0c8961fe17)
- Bug 1187159 - Add mochitest for loading packaged apps (iframe+fetch+mozapp) r=jduell (ce90ea561b)
- Bug 1186290 - Notify TabParent to switch process when loading a signed package. r=honzab, r=kanru. (c58a14554a)
- fix (15e2df75eb)
- Bug 1206124 P1 Fix "same-origin" CORS credentials in FetchDriver. r=ehsan (fae1bb6ab3)
- Bug 1206124 P2 Test fetch() with credentials and redirects. r=ehsan (ffc6254112)
- Bug 1211751: Remove nsIChannelEventSink-forwarding from EventSource and FetchDriver. It's never needed. r=smaug (adafe5737a)
- Bug 1212433 Fail fetch() calls that require preflight and also redirect. r=sicking a=abillings (c0d6742b9e)
- Bug 1193128 - Fix base64 decoding when fetching data URIs. r=baku (80bafa291a)
- Bug 1195167 part 1: Let necko handle all protocols. r=bkelly (bb932b0ada)
- Bug 1195167 part 2: Remove redundant aCORSFlag argument and instead use mCORSFlagEverSet. r=bkelly (beadafcad0)
- Bug 1195167 part 3: Remove more scheme-specific handling from FetchDriver. r=bkelly (d00b38db9e)
- Bug 1195167 part 4: Remove FetchDriver::BasicFetch since it is empty. r=bkelly (c5ed097267)
- Bug 1210413 P2 Test CORS credentials on cross-origin redirects. r=sicking a=dveditz (b4eeb8aac0)
- Bug 1210413 P1 Propagate new channel load flags from child to parent on redirect. r=jduell a=dveditz (8b329af4fa)
- Bug 1195167 part 5: Make FetchDriver use AsyncOpen2. r=bkelly (cc217c4cc1)
- Bug 1195167 part 6: Some code simplification since necko handles fetch recursion. r=bkelly (f3b6da2262)
- Bug 1195167: Followup to fix test which I forgot to change (81e7439a2e)
- Bug 1215746: Remove RequestMode::Cors_with_forced_preflight. r=bkelly (0336e812b6)
- Bug 1211000: Move CORS preflight logic from nsCORSListenerProxy to nsCORSPreflightListener. r=ehsan (bf2f71cf22)
- missing bit of Bug 1211443 - Drop scheduled update if decoder initialization isn't done yet. r=jya (f6bc074e33)
- Bug 1182571: Fix nsILoadInfo->GetContentPolicyType API to be less ambigious. Audit and fix all users of it. r=ckerschb (5af6fa7442)
- fix (e40c8e7625)
- Bug 1173811 - Part 1: Propagate the response URL to intercepted channels when necessary (non-e10s). r=mayhemer,bkelly (26f4f13c28)
- Bug 1173811 - Part 2: Propagate the response URL to intercepted channels when necessary (e10s). r=mayhemer,bkelly (a603fe1df2)
- Bug 1154309 - Add New Resource Timing Fields r=bz,hurley (1d14eb6bef)
- Bug 1175685 - add OriginAttribute to LoadInfo. r=jonas, r=ckerschb, r=michal (a5d18bb637)
- Bug 1175685 - add OriginAttribute to LoadInfo. r=jonas, r=ckerschb, r=michal (fb07d2c8aa)
- Bug 1212904 P1 Add a LoadTainting enumeration. r=jduell (a1db8a3e99)
- Bug 1212904 P2 Add LoadTainting information to nsILoadInfo. r=jduell (2482e5e334)
- Bug 1221151 - use [infallible] in nsILoadInfo.idl instead of manual %{C++ blocks; r=jduell (aae73129b6)
- Bug 1045891 - CSP 2 child-src implementation r=ckerschb (792920aeb9)
- Bug 1219931 - CSP: Don't allow removing a policy (r=sicking) (9daaab4186)
- Bug 1208661 - Dump client-side layer textures. r=BenWa (1f2d17d515)
2022-10-17 11:08:37 +08:00

785 lines
19 KiB
C++

/* 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 "CacheLog.h"
#include "CacheFileChunk.h"
#include "CacheFile.h"
#include "nsThreadUtils.h"
namespace mozilla {
namespace net {
#define kMinBufSize 512
class NotifyUpdateListenerEvent : public nsRunnable {
public:
NotifyUpdateListenerEvent(CacheFileChunkListener *aCallback,
CacheFileChunk *aChunk)
: mCallback(aCallback)
, mChunk(aChunk)
{
LOG(("NotifyUpdateListenerEvent::NotifyUpdateListenerEvent() [this=%p]",
this));
MOZ_COUNT_CTOR(NotifyUpdateListenerEvent);
}
protected:
~NotifyUpdateListenerEvent()
{
LOG(("NotifyUpdateListenerEvent::~NotifyUpdateListenerEvent() [this=%p]",
this));
MOZ_COUNT_DTOR(NotifyUpdateListenerEvent);
}
public:
NS_IMETHOD Run()
{
LOG(("NotifyUpdateListenerEvent::Run() [this=%p]", this));
mCallback->OnChunkUpdated(mChunk);
return NS_OK;
}
protected:
nsCOMPtr<CacheFileChunkListener> mCallback;
RefPtr<CacheFileChunk> mChunk;
};
bool
CacheFileChunk::DispatchRelease()
{
if (NS_IsMainThread()) {
return false;
}
RefPtr<nsRunnableMethod<CacheFileChunk, MozExternalRefCountType, false> > event =
NS_NewNonOwningRunnableMethod(this, &CacheFileChunk::Release);
NS_DispatchToMainThread(event);
return true;
}
NS_IMPL_ADDREF(CacheFileChunk)
NS_IMETHODIMP_(MozExternalRefCountType)
CacheFileChunk::Release()
{
nsrefcnt count = mRefCnt - 1;
if (DispatchRelease()) {
// Redispatched to the main thread.
return count;
}
NS_PRECONDITION(0 != mRefCnt, "dup release");
count = --mRefCnt;
NS_LOG_RELEASE(this, count, "CacheFileChunk");
if (0 == count) {
mRefCnt = 1;
delete (this);
return 0;
}
// We can safely access this chunk after decreasing mRefCnt since we re-post
// all calls to Release() happening off the main thread to the main thread.
// I.e. no other Release() that would delete the object could be run before
// we call CacheFile::DeactivateChunk().
//
// NOTE: we don't grab the CacheFile's lock, so the chunk might be addrefed
// on another thread before CacheFile::DeactivateChunk() grabs the lock on
// this thread. To make sure we won't deactivate chunk that was just returned
// to a new consumer we check mRefCnt once again in
// CacheFile::DeactivateChunk() after we grab the lock.
if (mActiveChunk && count == 1) {
mFile->DeactivateChunk(this);
}
return count;
}
NS_INTERFACE_MAP_BEGIN(CacheFileChunk)
NS_INTERFACE_MAP_ENTRY(mozilla::net::CacheFileIOListener)
NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END_THREADSAFE
CacheFileChunk::CacheFileChunk(CacheFile *aFile, uint32_t aIndex,
bool aInitByWriter)
: CacheMemoryConsumer(aFile->mOpenAsMemoryOnly ? MEMORY_ONLY : DONT_REPORT)
, mIndex(aIndex)
, mState(INITIAL)
, mStatus(NS_OK)
, mIsDirty(false)
, mActiveChunk(false)
, mDataSize(0)
, mReportedAllocation(0)
, mLimitAllocation(!aFile->mOpenAsMemoryOnly && aInitByWriter)
, mIsPriority(aFile->mPriority)
, mBuf(nullptr)
, mBufSize(0)
, mRWBuf(nullptr)
, mRWBufSize(0)
, mReadHash(0)
, mFile(aFile)
{
LOG(("CacheFileChunk::CacheFileChunk() [this=%p, index=%u, initByWriter=%d]",
this, aIndex, aInitByWriter));
MOZ_COUNT_CTOR(CacheFileChunk);
}
CacheFileChunk::~CacheFileChunk()
{
LOG(("CacheFileChunk::~CacheFileChunk() [this=%p]", this));
MOZ_COUNT_DTOR(CacheFileChunk);
if (mBuf) {
free(mBuf);
mBuf = nullptr;
mBufSize = 0;
ChunkAllocationChanged();
}
if (mRWBuf) {
free(mRWBuf);
mRWBuf = nullptr;
mRWBufSize = 0;
ChunkAllocationChanged();
}
}
void
CacheFileChunk::InitNew()
{
mFile->AssertOwnsLock();
LOG(("CacheFileChunk::InitNew() [this=%p]", this));
MOZ_ASSERT(mState == INITIAL);
MOZ_ASSERT(NS_SUCCEEDED(mStatus));
MOZ_ASSERT(!mBuf);
MOZ_ASSERT(!mRWBuf);
MOZ_ASSERT(!mIsDirty);
MOZ_ASSERT(mDataSize == 0);
mState = READY;
}
nsresult
CacheFileChunk::Read(CacheFileHandle *aHandle, uint32_t aLen,
CacheHash::Hash16_t aHash,
CacheFileChunkListener *aCallback)
{
mFile->AssertOwnsLock();
LOG(("CacheFileChunk::Read() [this=%p, handle=%p, len=%d, listener=%p]",
this, aHandle, aLen, aCallback));
MOZ_ASSERT(mState == INITIAL);
MOZ_ASSERT(NS_SUCCEEDED(mStatus));
MOZ_ASSERT(!mBuf);
MOZ_ASSERT(!mRWBuf);
MOZ_ASSERT(aLen);
nsresult rv;
mState = READING;
if (CanAllocate(aLen)) {
mRWBuf = static_cast<char *>(moz_malloc(aLen));
if (mRWBuf) {
mRWBufSize = aLen;
ChunkAllocationChanged();
}
}
if (!mRWBuf) {
// Allocation was denied or failed
SetError(NS_ERROR_OUT_OF_MEMORY);
return mStatus;
}
DoMemoryReport(MemorySize());
rv = CacheFileIOManager::Read(aHandle, mIndex * kChunkSize, mRWBuf, aLen,
this);
if (NS_WARN_IF(NS_FAILED(rv))) {
rv = mIndex ? NS_ERROR_FILE_CORRUPTED : NS_ERROR_FILE_NOT_FOUND;
SetError(rv);
} else {
mListener = aCallback;
mDataSize = aLen;
mReadHash = aHash;
}
return rv;
}
nsresult
CacheFileChunk::Write(CacheFileHandle *aHandle,
CacheFileChunkListener *aCallback)
{
mFile->AssertOwnsLock();
LOG(("CacheFileChunk::Write() [this=%p, handle=%p, listener=%p]",
this, aHandle, aCallback));
MOZ_ASSERT(mState == READY);
MOZ_ASSERT(NS_SUCCEEDED(mStatus));
MOZ_ASSERT(!mRWBuf);
MOZ_ASSERT(mBuf);
MOZ_ASSERT(mDataSize); // Don't write chunk when it is empty
nsresult rv;
mState = WRITING;
mRWBuf = mBuf;
mRWBufSize = mBufSize;
mBuf = nullptr;
mBufSize = 0;
rv = CacheFileIOManager::Write(aHandle, mIndex * kChunkSize, mRWBuf,
mDataSize, false, false, this);
if (NS_WARN_IF(NS_FAILED(rv))) {
SetError(rv);
} else {
mListener = aCallback;
mIsDirty = false;
}
return rv;
}
void
CacheFileChunk::WaitForUpdate(CacheFileChunkListener *aCallback)
{
mFile->AssertOwnsLock();
LOG(("CacheFileChunk::WaitForUpdate() [this=%p, listener=%p]",
this, aCallback));
MOZ_ASSERT(mFile->mOutput);
MOZ_ASSERT(IsReady());
#ifdef DEBUG
for (uint32_t i = 0 ; i < mUpdateListeners.Length() ; i++) {
MOZ_ASSERT(mUpdateListeners[i]->mCallback != aCallback);
}
#endif
ChunkListenerItem *item = new ChunkListenerItem();
item->mTarget = CacheFileIOManager::IOTarget();
if (!item->mTarget) {
LOG(("CacheFileChunk::WaitForUpdate() - Cannot get Cache I/O thread! Using "
"main thread for callback."));
item->mTarget = do_GetMainThread();
}
item->mCallback = aCallback;
MOZ_ASSERT(item->mTarget);
item->mCallback = aCallback;
mUpdateListeners.AppendElement(item);
}
nsresult
CacheFileChunk::CancelWait(CacheFileChunkListener *aCallback)
{
mFile->AssertOwnsLock();
LOG(("CacheFileChunk::CancelWait() [this=%p, listener=%p]", this, aCallback));
MOZ_ASSERT(IsReady());
uint32_t i;
for (i = 0 ; i < mUpdateListeners.Length() ; i++) {
ChunkListenerItem *item = mUpdateListeners[i];
if (item->mCallback == aCallback) {
mUpdateListeners.RemoveElementAt(i);
delete item;
break;
}
}
#ifdef DEBUG
for ( ; i < mUpdateListeners.Length() ; i++) {
MOZ_ASSERT(mUpdateListeners[i]->mCallback != aCallback);
}
#endif
return NS_OK;
}
nsresult
CacheFileChunk::NotifyUpdateListeners()
{
mFile->AssertOwnsLock();
LOG(("CacheFileChunk::NotifyUpdateListeners() [this=%p]", this));
MOZ_ASSERT(IsReady());
nsresult rv, rv2;
rv = NS_OK;
for (uint32_t i = 0 ; i < mUpdateListeners.Length() ; i++) {
ChunkListenerItem *item = mUpdateListeners[i];
LOG(("CacheFileChunk::NotifyUpdateListeners() - Notifying listener %p "
"[this=%p]", item->mCallback.get(), this));
RefPtr<NotifyUpdateListenerEvent> ev;
ev = new NotifyUpdateListenerEvent(item->mCallback, this);
rv2 = item->mTarget->Dispatch(ev, NS_DISPATCH_NORMAL);
if (NS_FAILED(rv2) && NS_SUCCEEDED(rv))
rv = rv2;
delete item;
}
mUpdateListeners.Clear();
return rv;
}
uint32_t
CacheFileChunk::Index()
{
return mIndex;
}
CacheHash::Hash16_t
CacheFileChunk::Hash()
{
mFile->AssertOwnsLock();
MOZ_ASSERT(!mListener);
MOZ_ASSERT(IsReady());
return CacheHash::Hash16(mDataSize ? BufForReading() : nullptr, mDataSize);
}
uint32_t
CacheFileChunk::DataSize()
{
mFile->AssertOwnsLock();
return mDataSize;
}
void
CacheFileChunk::UpdateDataSize(uint32_t aOffset, uint32_t aLen, bool aEOF)
{
mFile->AssertOwnsLock();
MOZ_ASSERT(!aEOF, "Implement me! What to do with opened streams?");
MOZ_ASSERT(aOffset <= mDataSize);
MOZ_ASSERT(aLen != 0);
// UpdateDataSize() is called only when we've written some data to the chunk
// and we never write data anymore once some error occurs.
MOZ_ASSERT(NS_SUCCEEDED(mStatus));
LOG(("CacheFileChunk::UpdateDataSize() [this=%p, offset=%d, len=%d, EOF=%d]",
this, aOffset, aLen, aEOF));
mIsDirty = true;
int64_t fileSize = kChunkSize * mIndex + aOffset + aLen;
bool notify = false;
if (fileSize > mFile->mDataSize)
mFile->mDataSize = fileSize;
if (aOffset + aLen > mDataSize) {
mDataSize = aOffset + aLen;
notify = true;
}
if (mState == READY || mState == WRITING) {
MOZ_ASSERT(mValidityMap.Length() == 0);
if (notify) {
NotifyUpdateListeners();
}
return;
}
// We're still waiting for data from the disk. This chunk cannot be used by
// input stream, so there must be no update listener. We also need to keep
// track of where the data is written so that we can correctly merge the new
// data with the old one.
MOZ_ASSERT(mUpdateListeners.Length() == 0);
MOZ_ASSERT(mState == READING);
mValidityMap.AddPair(aOffset, aLen);
mValidityMap.Log();
}
nsresult
CacheFileChunk::OnFileOpened(CacheFileHandle *aHandle, nsresult aResult)
{
MOZ_CRASH("CacheFileChunk::OnFileOpened should not be called!");
return NS_ERROR_UNEXPECTED;
}
nsresult
CacheFileChunk::OnDataWritten(CacheFileHandle *aHandle, const char *aBuf,
nsresult aResult)
{
LOG(("CacheFileChunk::OnDataWritten() [this=%p, handle=%p, result=0x%08x]",
this, aHandle, aResult));
nsCOMPtr<CacheFileChunkListener> listener;
{
CacheFileAutoLock lock(mFile);
MOZ_ASSERT(mState == WRITING);
MOZ_ASSERT(mListener);
if (NS_WARN_IF(NS_FAILED(aResult))) {
SetError(aResult);
}
mState = READY;
if (!mBuf) {
mBuf = mRWBuf;
mBufSize = mRWBufSize;
mRWBuf = nullptr;
mRWBufSize = 0;
} else {
free(mRWBuf);
mRWBuf = nullptr;
mRWBufSize = 0;
ChunkAllocationChanged();
}
DoMemoryReport(MemorySize());
mListener.swap(listener);
}
listener->OnChunkWritten(aResult, this);
return NS_OK;
}
nsresult
CacheFileChunk::OnDataRead(CacheFileHandle *aHandle, char *aBuf,
nsresult aResult)
{
LOG(("CacheFileChunk::OnDataRead() [this=%p, handle=%p, result=0x%08x]",
this, aHandle, aResult));
nsCOMPtr<CacheFileChunkListener> listener;
{
CacheFileAutoLock lock(mFile);
MOZ_ASSERT(mState == READING);
MOZ_ASSERT(mListener);
if (NS_SUCCEEDED(aResult)) {
CacheHash::Hash16_t hash = CacheHash::Hash16(mRWBuf, mRWBufSize);
if (hash != mReadHash) {
LOG(("CacheFileChunk::OnDataRead() - Hash mismatch! Hash of the data is"
" %hx, hash in metadata is %hx. [this=%p, idx=%d]",
hash, mReadHash, this, mIndex));
aResult = NS_ERROR_FILE_CORRUPTED;
}
else {
if (!mBuf) {
// Just swap the buffers if we don't have mBuf yet
MOZ_ASSERT(mDataSize == mRWBufSize);
mBuf = mRWBuf;
mBufSize = mRWBufSize;
mRWBuf = nullptr;
mRWBufSize = 0;
} else {
LOG(("CacheFileChunk::OnDataRead() - Merging buffers. [this=%p]",
this));
// Merge data with write buffer
if (mRWBufSize >= mBufSize) {
// The new data will fit into the buffer that contains data read
// from the disk. Simply copy the valid pieces.
mValidityMap.Log();
for (uint32_t i = 0; i < mValidityMap.Length(); i++) {
if (mValidityMap[i].Offset() + mValidityMap[i].Len() > mBufSize) {
MOZ_CRASH("Unexpected error in validity map!");
}
memcpy(mRWBuf + mValidityMap[i].Offset(),
mBuf + mValidityMap[i].Offset(), mValidityMap[i].Len());
}
mValidityMap.Clear();
free(mBuf);
mBuf = mRWBuf;
mBufSize = mRWBufSize;
mRWBuf = nullptr;
mRWBufSize = 0;
ChunkAllocationChanged();
} else {
// Buffer holding the new data is larger. Use it as the destination
// buffer to avoid reallocating mRWBuf. We need to copy those pieces
// from mRWBuf which are not valid in mBuf.
uint32_t invalidOffset = 0;
uint32_t invalidLength;
mValidityMap.Log();
for (uint32_t i = 0; i < mValidityMap.Length(); i++) {
MOZ_ASSERT(invalidOffset <= mValidityMap[i].Offset());
invalidLength = mValidityMap[i].Offset() - invalidOffset;
if (invalidLength > 0) {
if (invalidOffset + invalidLength > mRWBufSize) {
MOZ_CRASH("Unexpected error in validity map!");
}
memcpy(mBuf + invalidOffset, mRWBuf + invalidOffset,
invalidLength);
}
invalidOffset = mValidityMap[i].Offset() + mValidityMap[i].Len();
}
if (invalidOffset < mRWBufSize) {
invalidLength = mRWBufSize - invalidOffset;
memcpy(mBuf + invalidOffset, mRWBuf + invalidOffset,
invalidLength);
}
mValidityMap.Clear();
free(mRWBuf);
mRWBuf = nullptr;
mRWBufSize = 0;
ChunkAllocationChanged();
}
DoMemoryReport(MemorySize());
}
}
}
if (NS_FAILED(aResult)) {
aResult = mIndex ? NS_ERROR_FILE_CORRUPTED : NS_ERROR_FILE_NOT_FOUND;
SetError(aResult);
mDataSize = 0;
}
mState = READY;
mListener.swap(listener);
}
listener->OnChunkRead(aResult, this);
return NS_OK;
}
nsresult
CacheFileChunk::OnFileDoomed(CacheFileHandle *aHandle, nsresult aResult)
{
MOZ_CRASH("CacheFileChunk::OnFileDoomed should not be called!");
return NS_ERROR_UNEXPECTED;
}
nsresult
CacheFileChunk::OnEOFSet(CacheFileHandle *aHandle, nsresult aResult)
{
MOZ_CRASH("CacheFileChunk::OnEOFSet should not be called!");
return NS_ERROR_UNEXPECTED;
}
nsresult
CacheFileChunk::OnFileRenamed(CacheFileHandle *aHandle, nsresult aResult)
{
MOZ_CRASH("CacheFileChunk::OnFileRenamed should not be called!");
return NS_ERROR_UNEXPECTED;
}
bool
CacheFileChunk::IsReady() const
{
mFile->AssertOwnsLock();
return (NS_SUCCEEDED(mStatus) && (mState == READY || mState == WRITING));
}
bool
CacheFileChunk::IsDirty() const
{
mFile->AssertOwnsLock();
return mIsDirty;
}
nsresult
CacheFileChunk::GetStatus()
{
mFile->AssertOwnsLock();
return mStatus;
}
void
CacheFileChunk::SetError(nsresult aStatus)
{
MOZ_ASSERT(NS_FAILED(aStatus));
if (NS_FAILED(mStatus)) {
// Remember only the first error code.
return;
}
mStatus = aStatus;
}
char *
CacheFileChunk::BufForWriting() const
{
mFile->AssertOwnsLock();
MOZ_ASSERT(mBuf); // Writer should always first call EnsureBufSize()
MOZ_ASSERT(NS_SUCCEEDED(mStatus));
MOZ_ASSERT((mState == READY && !mRWBuf) ||
(mState == WRITING && mRWBuf) ||
(mState == READING && mRWBuf));
return mBuf;
}
const char *
CacheFileChunk::BufForReading() const
{
mFile->AssertOwnsLock();
MOZ_ASSERT((mState == READY && mBuf && !mRWBuf) ||
(mState == WRITING && mRWBuf));
return mBuf ? mBuf : mRWBuf;
}
MOZ_WARN_UNUSED_RESULT nsresult
CacheFileChunk::EnsureBufSize(uint32_t aBufSize)
{
mFile->AssertOwnsLock();
// EnsureBufSize() is called only when we want to write some data to the chunk
// and we never write data anymore once some error occurs.
MOZ_ASSERT(NS_SUCCEEDED(mStatus));
if (mBufSize >= aBufSize) {
return NS_OK;
}
bool copy = false;
if (!mBuf && mState == WRITING) {
// We need to duplicate the data that is being written on the background
// thread, so make sure that all the data fits into the new buffer.
copy = true;
if (mRWBufSize > aBufSize)
aBufSize = mRWBufSize;
}
// find smallest power of 2 greater than or equal to aBufSize
aBufSize--;
aBufSize |= aBufSize >> 1;
aBufSize |= aBufSize >> 2;
aBufSize |= aBufSize >> 4;
aBufSize |= aBufSize >> 8;
aBufSize |= aBufSize >> 16;
aBufSize++;
const uint32_t minBufSize = kMinBufSize;
const uint32_t maxBufSize = kChunkSize;
aBufSize = clamped(aBufSize, minBufSize, maxBufSize);
if (!CanAllocate(aBufSize - mBufSize)) {
SetError(NS_ERROR_OUT_OF_MEMORY);
return mStatus;
}
char *newBuf = static_cast<char *>(moz_realloc(mBuf, aBufSize));
if (!newBuf) {
SetError(NS_ERROR_OUT_OF_MEMORY);
return mStatus;
}
mBuf = newBuf;
mBufSize = aBufSize;
ChunkAllocationChanged();
if (copy)
memcpy(mBuf, mRWBuf, mRWBufSize);
DoMemoryReport(MemorySize());
return NS_OK;
}
// Memory reporting
size_t
CacheFileChunk::SizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const
{
size_t n = 0;
n += mallocSizeOf(mBuf);
n += mallocSizeOf(mRWBuf);
n += mValidityMap.SizeOfExcludingThis(mallocSizeOf);
return n;
}
size_t
CacheFileChunk::SizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const
{
return mallocSizeOf(this) + SizeOfExcludingThis(mallocSizeOf);
}
bool
CacheFileChunk::CanAllocate(uint32_t aSize)
{
if (!mLimitAllocation) {
return true;
}
LOG(("CacheFileChunk::CanAllocate() [this=%p, size=%u]", this, aSize));
uint32_t limit = CacheObserver::MaxDiskChunksMemoryUsage(mIsPriority);
if (limit == 0) {
return true;
}
uint32_t usage = ChunksMemoryUsage();
if (usage + aSize > limit) {
LOG(("CacheFileChunk::CanAllocate() - Returning false. [this=%p]", this));
return false;
}
return true;
}
void
CacheFileChunk::ChunkAllocationChanged()
{
if (!mLimitAllocation) {
return;
}
ChunksMemoryUsage() -= mReportedAllocation;
mReportedAllocation = mBufSize + mRWBufSize;
ChunksMemoryUsage() += mReportedAllocation;
LOG(("CacheFileChunk::ChunkAllocationChanged() - %s chunks usage %u "
"[this=%p]", mIsPriority ? "Priority" : "Normal",
static_cast<uint32_t>(ChunksMemoryUsage()), this));
}
mozilla::Atomic<uint32_t>& CacheFileChunk::ChunksMemoryUsage()
{
static mozilla::Atomic<uint32_t> chunksMemoryUsage(0);
static mozilla::Atomic<uint32_t> prioChunksMemoryUsage(0);
return mIsPriority ? prioChunksMemoryUsage : chunksMemoryUsage;
}
} // namespace net
} // namespace mozilla