/* -*- 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/. */
// Undefine windows version of LoadImage because our code uses that name. #include"mozilla/ScopeExit.h" #include"nsIChildChannel.h" #include"nsIThreadRetargetableStreamListener.h" #undef LoadImage
// we want to explore making the document own the load group // so we can associate the document URI with the load group. // until this point, we have an evil hack: #include"nsIHttpChannelInternal.h" #include"nsILoadGroupChild.h" #include"nsIDocShell.h"
// Uncached images may be content or chrome, so anonymize them.
ReportCounterArray(aHandleReport, aData, uncached, "images/uncached",
aAnonymize, aSharedSurfaces);
// Report any shared surfaces that were not merged with the surface cache.
ImageMemoryReporter::ReportSharedSurfaces(aHandleReport, aData,
aSharedSurfaces);
nsCOMPtr<nsIMemoryReporterManager> imgr =
do_GetService("@mozilla.org/memory-reporter-manager;1"); if (imgr) {
imgr->EndReport();
}
}
static int64_t ImagesContentUsedUncompressedDistinguishedAmount() {
size_t n = 0; for (uint32_t i = 0; i < imgLoader::sMemReporter->mKnownLoaders.Length();
i++) { for (imgCacheEntry* entry :
imgLoader::sMemReporter->mKnownLoaders[i]->mCache.Values()) { if (entry->HasNoProxies()) { continue;
}
// Both this and EntryImageSizes measure // images/content/raster/used/decoded memory. This function's // measurement is secondary -- the result doesn't go in the "explicit" // tree -- so we use moz_malloc_size_of instead of ImagesMallocSizeOf to // prevent DMD from seeing it reported twice.
SizeOfState state(moz_malloc_size_of);
ImageMemoryCounter counter(req, image, state, /* aIsUsed = */ true);
n += counter.Values().DecodedHeap();
n += counter.Values().DecodedNonHeap();
n += counter.Values().DecodedUnknown();
}
} return n;
}
// Reports all images of a single kind, e.g. all used chrome images. void ReportCounterArray(nsIHandleReportCallback* aHandleReport,
nsISupports* aData,
nsTArray<ImageMemoryCounter>& aCounterArray, constchar* aPathPrefix, bool aAnonymize,
layers::SharedSurfacesMemoryReport& aSharedSurfaces) {
MemoryTotal summaryTotal;
MemoryTotal nonNotableTotal;
// Report notable images, and compute total and non-notable aggregate sizes. for (uint32_t i = 0; i < aCounterArray.Length(); i++) {
ImageMemoryCounter& counter = aCounterArray[i];
if (aAnonymize) {
counter.URI().Truncate();
counter.URI().AppendPrintf("", i);
} else { // The URI could be an extremely long data: URI. Truncate if needed. staticconst size_t max = 256; if (counter.URI().Length() > max) {
counter.URI().Truncate(max);
counter.URI().AppendLiteral(" (truncated)");
}
counter.URI().ReplaceChar('/', '\\');
}
ReportValue(aHandleReport, aData, KIND_HEAP, aPathPrefix, "decoded-heap", "Decoded image data which is stored on the heap.",
aCounter.DecodedHeap());
ReportValue(aHandleReport, aData, KIND_NONHEAP, aPathPrefix, "decoded-nonheap", "Decoded image data which isn't stored on the heap.",
aCounter.DecodedNonHeap());
// We don't know for certain whether or not it is on the heap, so let's // just report it as non-heap for reporting purposes.
ReportValue(aHandleReport, aData, KIND_NONHEAP, aPathPrefix, "decoded-unknown", "Decoded image data which is unknown to be on the heap or not.",
aCounter.DecodedUnknown());
}
staticvoid RecordCounterForRequest(imgRequest* aRequest,
nsTArray<ImageMemoryCounter>* aArray, bool aIsUsed) {
SizeOfState state(ImagesMallocSizeOf);
RefPtr<image::Image> image = aRequest->GetImage(); if (image) {
ImageMemoryCounter counter(aRequest, image, state, aIsUsed);
aArray->AppendElement(std::move(counter));
} else { // We can at least record some information about the image from the // request, and mark it as not knowing the image type yet.
ImageMemoryCounter counter(aRequest, state, aIsUsed);
aArray->AppendElement(std::move(counter));
}
}
};
staticbool ShouldRevalidateEntry(imgCacheEntry* aEntry, nsLoadFlags aFlags, bool aHasExpired) { if (aFlags & nsIRequest::LOAD_BYPASS_CACHE) { returnfalse;
} if (aFlags & nsIRequest::VALIDATE_ALWAYS) { returntrue;
} if (aEntry->GetMustValidate()) { returntrue;
} if (aHasExpired) { // The cache entry has expired... Determine whether the stale cache // entry can be used without validation... if (aFlags & (nsIRequest::LOAD_FROM_CACHE | nsIRequest::VALIDATE_NEVER |
nsIRequest::VALIDATE_ONCE_PER_SESSION)) { // LOAD_FROM_CACHE, VALIDATE_NEVER and VALIDATE_ONCE_PER_SESSION allow // stale cache entries to be used unless they have been explicitly marked // to indicate that revalidation is necessary. returnfalse;
} // Entry is expired, revalidate. returntrue;
} returnfalse;
}
/* Call content policies on cached images that went through a redirect */ staticbool ShouldLoadCachedImage(imgRequest* aImgRequest,
Document* aLoadingDocument,
nsIPrincipal* aTriggeringPrincipal,
nsContentPolicyType aPolicyType, bool aSendCSPViolationReports) { /* Call content policies on cached images - Bug 1082837 * Cached images are keyed off of the first uri in a redirect chain. * Hence content policies don't get a chance to test the intermediate hops * or the final destination. Here we test the final destination using * mFinalURI off of the imgRequest and passing it into content policies. * For Mixed Content Blocker, we do an additional check to determine if any * of the intermediary hops went through an insecure redirect with the * mHadInsecureRedirect flag
*/ bool insecureRedirect = aImgRequest->HadInsecureRedirect();
nsCOMPtr<nsIURI> contentLocation;
aImgRequest->GetFinalURI(getter_AddRefs(contentLocation));
nsresult rv;
nsCOMPtr<nsIPrincipal> loadingPrincipal =
aLoadingDocument ? aLoadingDocument->NodePrincipal()
: aTriggeringPrincipal; // If there is no context and also no triggeringPrincipal, then we use a fresh // nullPrincipal as the loadingPrincipal because we can not create a loadinfo // without a valid loadingPrincipal. if (!loadingPrincipal) {
loadingPrincipal = NullPrincipal::CreateWithoutOriginAttributes();
}
nsCOMPtr<nsILoadInfo> secCheckLoadInfo = new LoadInfo(
loadingPrincipal, aTriggeringPrincipal, aLoadingDocument,
nsILoadInfo::SEC_ONLY_FOR_EXPLICIT_CONTENTSEC_CHECK, aPolicyType);
// We call all Content Policies above, but we also have to call mcb // individually to check the intermediary redirect hops are secure. if (insecureRedirect) { // Bug 1314356: If the image ended up in the cache upgraded by HSTS and the // page uses upgrade-inscure-requests it had an insecure redirect // (http->https). We need to invalidate the image and reload it because // mixed content blocker only bails if upgrade-insecure-requests is set on // the doc and the resource load is http: which would result in an incorrect // mixed content warning.
nsCOMPtr<nsIDocShell> docShell =
NS_CP_GetDocShellFromContext(ToSupports(aLoadingDocument)); if (docShell) {
Document* document = docShell->GetDocument(); if (document && document->GetUpgradeInsecureRequests(false)) { returnfalse;
}
}
if (!aTriggeringPrincipal || !aTriggeringPrincipal->IsSystemPrincipal()) { // reset the decision for mixed content blocker check
decision = nsIContentPolicy::REJECT_REQUEST;
rv = nsMixedContentBlocker::ShouldLoad(insecureRedirect, contentLocation,
secCheckLoadInfo, true, // aReportError
&decision); if (NS_FAILED(rv) || !NS_CP_ACCEPTED(decision)) { returnfalse;
}
}
}
returntrue;
}
// Returns true if this request is compatible with the given CORS mode on the // given loading principal, and false if the request may not be reused due // to CORS. staticbool ValidateCORSMode(imgRequest* aRequest, bool aForcePrincipalCheck,
CORSMode aCORSMode,
nsIPrincipal* aTriggeringPrincipal) { // If the entry's CORS mode doesn't match, or the CORS mode matches but the // document principal isn't the same, we can't use this request. if (aRequest->GetCORSMode() != aCORSMode) { returnfalse;
}
staticvoid AdjustPriorityForImages(nsIChannel* aChannel,
nsLoadFlags aLoadFlags,
FetchPriority aFetchPriority) { // Image channels are loaded by default with reduced priority. if (nsCOMPtr<nsISupportsPriority> supportsPriority =
do_QueryInterface(aChannel)) {
int32_t priority = nsISupportsPriority::PRIORITY_LOW;
// Adjust priority according to fetchpriorty attribute. if (StaticPrefs::network_fetchpriority_enabled()) {
priority += FETCH_PRIORITY_ADJUSTMENT_FOR(images, aFetchPriority);
}
// Further reduce priority for background loads if (aLoadFlags & nsIRequest::LOAD_BACKGROUND) {
++priority;
}
supportsPriority->AdjustPriority(priority);
}
if (nsCOMPtr<nsIClassOfService> cos = do_QueryInterface(aChannel)) {
cos->SetFetchPriorityDOM(aFetchPriority);
}
}
static nsresult NewImageChannel(
nsIChannel** aResult, // If aForcePrincipalCheckForCacheEntry is true, then we will // force a principal check even when not using CORS before // assuming we have a cache hit on a cache entry that we // create for this channel. This is an out param that should // be set to true if this channel ends up depending on // aTriggeringPrincipal and false otherwise. bool* aForcePrincipalCheckForCacheEntry, nsIURI* aURI,
nsIURI* aInitialDocumentURI, CORSMode aCORSMode,
nsIReferrerInfo* aReferrerInfo, nsILoadGroup* aLoadGroup,
nsLoadFlags aLoadFlags, nsContentPolicyType aPolicyType,
nsIPrincipal* aTriggeringPrincipal, nsINode* aRequestingNode, bool aRespectPrivacy, uint64_t aEarlyHintPreloaderId,
FetchPriority aFetchPriority) {
MOZ_ASSERT(aResult);
if (aLoadGroup) { // Get the notification callbacks from the load group for the new channel. // // XXX: This is not exactly correct, because the network request could be // referenced by multiple windows... However, the new channel needs // something. So, using the 'first' notification callbacks is better // than nothing... //
aLoadGroup->GetNotificationCallbacks(getter_AddRefs(callbacks));
}
// Pass in a nullptr loadgroup because this is the underlying network // request. This request may be referenced by several proxy image requests // (possibly in different documents). // If all of the proxy requests are canceled then this request should be // canceled too. //
// Note we are calling NS_NewChannelWithTriggeringPrincipal() here with a // node and a principal. This is for things like background images that are // specified by user stylesheets, where the document is being styled, but // the principal is that of the user stylesheet. if (aRequestingNode && aTriggeringPrincipal) {
rv = NS_NewChannelWithTriggeringPrincipal(aResult, aURI, aRequestingNode,
aTriggeringPrincipal,
securityFlags, aPolicyType,
nullptr, // PerformanceStorage
nullptr, // loadGroup
callbacks, aLoadFlags);
if (NS_FAILED(rv)) { return rv;
}
if (aPolicyType == nsIContentPolicy::TYPE_INTERNAL_IMAGE_FAVICON) { // If this is a favicon loading, we will use the originAttributes from the // triggeringPrincipal as the channel's originAttributes. This allows the // favicon loading from XUL will use the correct originAttributes.
nsCOMPtr<nsILoadInfo> loadInfo = (*aResult)->LoadInfo();
rv = loadInfo->SetOriginAttributes(
aTriggeringPrincipal->OriginAttributesRef());
}
} else { // either we are loading something inside a document, in which case // we should always have a requestingNode, or we are loading something // outside a document, in which case the triggeringPrincipal and // triggeringPrincipal should always be the systemPrincipal. // However, there are exceptions: one is Notifications which create a // channel in the parent process in which case we can't get a // requestingNode.
rv = NS_NewChannel(aResult, aURI, nsContentUtils::GetSystemPrincipal(),
securityFlags, aPolicyType,
nullptr, // nsICookieJarSettings
nullptr, // PerformanceStorage
nullptr, // loadGroup
callbacks, aLoadFlags);
if (NS_FAILED(rv)) { return rv;
}
// Use the OriginAttributes from the loading principal, if one is available, // and adjust the private browsing ID based on what kind of load the caller // has asked us to perform.
OriginAttributes attrs; if (aTriggeringPrincipal) {
attrs = aTriggeringPrincipal->OriginAttributesRef();
}
attrs.mPrivateBrowsingId = aRespectPrivacy ? 1 : 0;
// only inherit if we have a principal
*aForcePrincipalCheckForCacheEntry =
aTriggeringPrincipal && nsContentUtils::ChannelShouldInheritPrincipal(
aTriggeringPrincipal, aURI, /* aInheritForAboutBlank */ false, /* aForceInherit */ false);
// Create a new loadgroup for this new channel, using the old group as // the parent. The indirection keeps the channel insulated from cancels, // but does allow a way for this revalidation to be associated with at // least one base load group for scheduling/caching purposes.
/* static */
imgCacheEntry::imgCacheEntry(imgLoader* loader, imgRequest* request, bool forcePrincipalCheck)
: mLoader(loader),
mRequest(request),
mDataSize(0),
mTouchedTime(SecondsFromPRTime(PR_Now())),
mLoadTime(SecondsFromPRTime(PR_Now())),
mExpiryTime(CacheExpirationTime::Never()),
mMustValidate(false), // We start off as evicted so we don't try to update the cache. // PutIntoCache will set this to false.
mEvicted(true),
mHasNoProxies(true),
mForcePrincipalCheck(forcePrincipalCheck),
mHasNotified(false) {}
if (updateTime) {
mTouchedTime = SecondsFromPRTime(PR_Now());
}
UpdateCache();
}
void imgCacheEntry::UpdateCache(int32_t diff /* = 0 */) { // Don't update the cache if we've been removed from it or it doesn't care // about our size or usage. if (!Evicted() && HasNoProxies()) {
mLoader->CacheEntriesChanged(diff);
}
}
void imgCacheQueue::Remove(imgCacheEntry* entry) {
uint64_t index = mQueue.IndexOf(entry); if (index == queueContainer::NoIndex) { return;
}
mSize -= mQueue[index]->GetDataSize();
// If the queue is clean and this is the first entry, // then we can efficiently remove the entry without // dirtying the sort order. if (!IsDirty() && index == 0) {
std::pop_heap(mQueue.begin(), mQueue.end(), imgLoader::CompareCacheEntries);
mQueue.RemoveLastElement(); return;
}
// Remove from the middle of the list. This potentially // breaks the binary heap sort order.
mQueue.RemoveElementAt(index);
// If we only have one entry or the queue is empty, though, // then the sort order is still effectively good. Simply // refresh the list to clear the dirty flag. if (mQueue.Length() <= 1) {
Refresh(); return;
}
// Otherwise we must mark the queue dirty and potentially // trigger an expensive sort later.
MarkDirty();
}
RefPtr<imgCacheEntry> refptr(entry);
mQueue.AppendElement(std::move(refptr)); // If we're not dirty already, then we can efficiently add this to the // binary heap immediately. This is only O(log n). if (!IsDirty()) {
std::push_heap(mQueue.begin(), mQueue.end(),
imgLoader::CompareCacheEntries);
}
}
already_AddRefed<imgCacheEntry> imgCacheQueue::Pop() { if (mQueue.IsEmpty()) { return nullptr;
} if (IsDirty()) {
Refresh();
}
void imgCacheQueue::Refresh() { // Resort the list. This is an O(3 * n) operation and best avoided // if possible.
std::make_heap(mQueue.begin(), mQueue.end(), imgLoader::CompareCacheEntries);
mDirty = false;
}
/* XXX If we move decoding onto separate threads, we should save off the calling thread here and pass it off to |proxyRequest| so that it call proxy calls to |aObserver|.
*/
RefPtr<imgRequestProxy> proxyRequest = new imgRequestProxy();
/* It is important to call |SetLoadFlags()| before calling |Init()| because |Init()| adds the request to the loadgroup.
*/
proxyRequest->SetLoadFlags(aLoadFlags);
// init adds itself to imgRequest's list of observers
nsresult rv = proxyRequest->Init(aRequest, aLoadGroup, aURI, aObserver); if (NS_WARN_IF(NS_FAILED(rv))) { return rv;
}
proxyRequest.forget(_retval); return NS_OK;
}
class imgCacheExpirationTracker final
: public nsExpirationTracker<imgCacheEntry, 3> { enum { TIMEOUT_SECONDS = 10 };
void imgCacheExpirationTracker::NotifyExpired(imgCacheEntry* entry) { // Hold on to a reference to this entry, because the expiration tracker // mechanism doesn't.
RefPtr<imgCacheEntry> kungFuDeathGrip(entry);
if (MOZ_LOG_TEST(gImgLog, LogLevel::Debug)) {
RefPtr<imgRequest> req = entry->GetRequest(); if (req) {
LOG_FUNC_WITH_PARAM(gImgLog, "imgCacheExpirationTracker::NotifyExpired", "entry", req->CacheKey().URI());
}
}
// We can be called multiple times on the same entry. Don't do work multiple // times. if (!entry->Evicted()) {
entry->Loader()->RemoveFromCache(entry);
}
/* static */
already_AddRefed<imgLoader> imgLoader::CreateImageLoader() { // In some cases, such as xpctests, XPCOM modules are not automatically // initialized. We need to make sure that our module is initialized before // we hand out imgLoader instances and code starts using them.
mozilla::image::EnsureModuleInitialized();
RefPtr<imgLoader> loader = new imgLoader();
loader->Init();
imgLoader::~imgLoader() {
ClearImageCache();
{ // If there are any of our imgRequest's left they are in the uncached // images set, so clear their pointer to us.
MutexAutoLock lock(mUncachedImagesMutex); for (RefPtr<imgRequest> req : mUncachedImages) {
req->ClearLoader();
}
}
sMemReporter->UnregisterLoader(this);
sMemReporter->Release();
}
void imgLoader::VerifyCacheSizes() { #ifdef DEBUG if (!mCacheTracker) { return;
}
uint32_t cachesize = mCache.Count();
uint32_t queuesize = mCacheQueue.GetNumElements();
uint32_t trackersize = 0; for (nsExpirationTracker<imgCacheEntry, 3>::Iterator it(mCacheTracker.get());
it.Next();) {
trackersize++;
}
MOZ_ASSERT(queuesize == trackersize, "Queue and tracker sizes out of sync!");
MOZ_ASSERT(queuesize <= cachesize, "Queue has more elements than cache!"); #endif
}
nsresult imgLoader::RemoveEntriesInternal( const Maybe<nsCOMPtr<nsIPrincipal>>& aPrincipal, const Maybe<nsCString>& aSchemelessSite, const Maybe<OriginAttributesPattern>& aPattern) { // Can only clear by either principal or site + pattern. if ((!aPrincipal && !aSchemelessSite) || (aPrincipal && aSchemelessSite) ||
aSchemelessSite.isSome() != aPattern.isSome()) { return NS_ERROR_INVALID_ARG;
}
Maybe<OriginAttributesPattern> patternWithPartitionKey = Nothing(); if (aPattern) { // Used for checking for cache entries partitioned under aSchemelessSite.
OriginAttributesPattern pattern(aPattern.ref());
pattern.mPartitionKeyPattern.Construct();
pattern.mPartitionKeyPattern.Value().mBaseDomain.Construct(
NS_ConvertUTF8toUTF16(aSchemelessSite.ref()));
// For base domain we only clear the non-chrome cache. for (constauto& entry : mCache) { constauto& key = entry.GetKey();
constbool shouldRemove = [&] { // The isolation key is either just the site, or an origin suffix // which contains the partitionKey holding the baseDomain.
if (!aSchemelessSite) { returnfalse;
} // Clear by site and pattern.
nsAutoCString host;
nsresult rv = key.URI()->GetHost(host); if (NS_FAILED(rv) || host.IsEmpty()) { returnfalse;
}
if (!tldService) {
tldService = do_GetService(NS_EFFECTIVETLDSERVICE_CONTRACTID);
} if (NS_WARN_IF(!tldService)) { returnfalse;
}
if (hasRootDomain && aPattern->Matches(key.OriginAttributesRef())) { returntrue;
}
// Attempt to parse isolation key into origin attributes.
Maybe<OriginAttributes> originAttributesWithPartitionKey;
{
OriginAttributes attrs; if (attrs.PopulateFromSuffix(key.IsolationKeyRef())) {
OriginAttributes attrsWithPartitionKey(key.OriginAttributesRef());
attrsWithPartitionKey.mPartitionKey = attrs.mPartitionKey;
originAttributesWithPartitionKey.emplace(
std::move(attrsWithPartitionKey));
}
}
// Match it against the pattern that contains the partition key and any // fields set by the caller pattern. if (originAttributesWithPartitionKey.isSome()) {
nsAutoCString oaSuffixForPrinting;
originAttributesWithPartitionKey->CreateSuffix(oaSuffixForPrinting);
// The isolation key is the site. return aSchemelessSite->Equals(key.IsolationKeyRef());
}();
if (shouldRemove) {
entriesToBeRemoved.AppendElement(entry.GetData());
}
}
for (auto& entry : entriesToBeRemoved) { if (!RemoveFromCache(entry)) {
NS_WARNING( "Couldn't remove an entry from the cache in " "RemoveEntriesInternal()\n");
}
}
return NS_OK;
}
constexpr auto AllCORSModes() { return MakeInclusiveEnumeratedRange(kFirstCORSMode, kLastCORSMode);
}
// Check to see if this request already exists in the cache. If so, we'll // replace the old version.
RefPtr<imgCacheEntry> tmpCacheEntry; if (mCache.Get(aKey, getter_AddRefs(tmpCacheEntry)) && tmpCacheEntry) {
MOZ_LOG(
gImgLog, LogLevel::Debug,
("[this=%p] imgLoader::PutIntoCache -- Element already in the cache",
nullptr));
RefPtr<imgRequest> tmpRequest = tmpCacheEntry->GetRequest();
// If it already exists, and we're putting the same key into the cache, we // should remove the old version.
MOZ_LOG(gImgLog, LogLevel::Debug,
("[this=%p] imgLoader::PutIntoCache -- Replacing cached element",
nullptr));
RemoveFromCache(aKey);
} else {
MOZ_LOG(gImgLog, LogLevel::Debug,
("[this=%p] imgLoader::PutIntoCache --" " Element NOT already in the cache",
nullptr));
}
mCache.InsertOrUpdate(aKey, RefPtr{entry});
// We can be called to resurrect an evicted entry. if (entry->Evicted()) {
entry->SetEvicted(false);
}
// If we're resurrecting an entry with no proxies, put it back in the // tracker and queue. if (entry->HasNoProxies()) {
nsresult addrv = NS_OK;
if (mCacheTracker) {
addrv = mCacheTracker->AddObject(entry);
}
if (NS_SUCCEEDED(addrv)) {
mCacheQueue.Push(entry);
}
}
RefPtr<imgCacheEntry> entry; if (mCache.Get(key, getter_AddRefs(entry)) && entry) { // Make sure the cache entry is for the right request
RefPtr<imgRequest> entryRequest = entry->GetRequest(); if (entryRequest == aRequest && entry->HasNoProxies()) {
mCacheQueue.Remove(entry);
if (mCacheTracker) {
mCacheTracker->RemoveObject(entry);
}
entry->SetHasNoProxies(false);
returntrue;
}
}
returnfalse;
}
void imgLoader::CacheEntriesChanged(int32_t aSizeDiff /* = 0 */) { // We only need to dirty the queue if there is any sorting // taking place. Empty or single-entry lists can't become // dirty. if (mCacheQueue.GetNumElements() > 1) {
mCacheQueue.MarkDirty();
}
mCacheQueue.UpdateSize(aSizeDiff);
}
// Remove entries from the cache until we're back at our desired max size. while (mCacheQueue.GetSize() > sCacheMaxSize) { // Remove the first entry in the queue.
RefPtr<imgCacheEntry> entry(mCacheQueue.Pop());
if (MOZ_LOG_TEST(gImgLog, LogLevel::Debug)) {
RefPtr<imgRequest> req = entry->GetRequest(); if (req) {
LOG_STATIC_FUNC_WITH_PARAM(gImgLog, "imgLoader::CheckCacheLimits", "entry", req->CacheKey().URI());
}
}
if (entry) { // We just popped this entry from the queue, so pass AlreadyRemoved // to avoid searching the queue again in RemoveFromCache.
RemoveFromCache(entry, QueueState::AlreadyRemoved);
}
}
}
bool imgLoader::ValidateRequestWithNewChannel(
imgRequest* request, nsIURI* aURI, nsIURI* aInitialDocumentURI,
nsIReferrerInfo* aReferrerInfo, nsILoadGroup* aLoadGroup,
imgINotificationObserver* aObserver, Document* aLoadingDocument,
uint64_t aInnerWindowId, nsLoadFlags aLoadFlags,
nsContentPolicyType aLoadPolicyType, imgRequestProxy** aProxyRequest,
nsIPrincipal* aTriggeringPrincipal, CORSMode aCORSMode, bool aLinkPreload,
uint64_t aEarlyHintPreloaderId, FetchPriority aFetchPriority, bool* aNewChannelCreated) { // now we need to insert a new channel request object in between the real // request and the proxy that basically delays loading the image until it // gets a 304 or figures out that this needs to be a new request
nsresult rv;
// If we're currently in the middle of validating this request, just hand // back a proxy to it; the required work will be done for us. if (imgCacheValidator* validator = request->GetValidator()) {
rv = CreateNewProxyForRequest(request, aURI, aLoadGroup, aLoadingDocument,
aObserver, aLoadFlags, aProxyRequest); if (NS_FAILED(rv)) { returnfalse;
}
if (*aProxyRequest) {
imgRequestProxy* proxy = static_cast<imgRequestProxy*>(*aProxyRequest);
// We will send notifications from imgCacheValidator::OnStartRequest(). // In the mean time, we must defer notifications because we are added to // the imgRequest's proxy list, and we can get extra notifications // resulting from methods such as StartDecoding(). See bug 579122.
proxy->MarkValidating();
if (aLinkPreload) {
MOZ_ASSERT(aLoadingDocument); auto preloadKey = PreloadHashKey::CreateAsImage(
aURI, aTriggeringPrincipal, aCORSMode);
proxy->NotifyOpen(preloadKey, aLoadingDocument, true);
}
// Attach the proxy without notifying
validator->AddProxy(proxy);
}
returntrue;
} // We will rely on Necko to cache this request when it's possible, and to // tell imgCacheValidator::OnStartRequest whether the request came from its // cache.
nsCOMPtr<nsIChannel> newChannel; bool forcePrincipalCheck;
rv = NewImageChannel(getter_AddRefs(newChannel), &forcePrincipalCheck, aURI,
aInitialDocumentURI, aCORSMode, aReferrerInfo,
aLoadGroup, aLoadFlags, aLoadPolicyType,
aTriggeringPrincipal, aLoadingDocument, mRespectPrivacy,
aEarlyHintPreloaderId, aFetchPriority); if (NS_FAILED(rv)) { returnfalse;
}
if (aNewChannelCreated) {
*aNewChannelCreated = true;
}
// Make sure that OnStatus/OnProgress calls have the right request set...
RefPtr<nsProgressNotificationProxy> progressproxy = new nsProgressNotificationProxy(newChannel, req); if (!progressproxy) { returnfalse;
}
RefPtr<imgCacheValidator> hvc = new imgCacheValidator(progressproxy, this, request, aLoadingDocument,
aInnerWindowId, forcePrincipalCheck);
// Casting needed here to get past multiple inheritance.
nsCOMPtr<nsIStreamListener> listener = static_cast<nsIThreadRetargetableStreamListener*>(hvc);
NS_ENSURE_TRUE(listener, false);
// We must set the notification callbacks before setting up the // CORS listener, because that's also interested inthe // notification callbacks.
newChannel->SetNotificationCallbacks(hvc);
request->SetValidator(hvc);
// We will send notifications from imgCacheValidator::OnStartRequest(). // In the mean time, we must defer notifications because we are added to
--> --------------------
--> maximum size reached
--> --------------------
¤ Dauer der Verarbeitung: 0.32 Sekunden
(vorverarbeitet)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung ist noch experimentell.