CachedResource leak in validation code
[WebKit-https.git] / Source / WebCore / loader / cache / CachedResource.cpp
index ceee58c..da44cc8 100644 (file)
@@ -29,6 +29,8 @@
 #include "CachedResourceHandle.h"
 #include "CachedResourceLoader.h"
 #include "CrossOriginAccessControl.h"
+#include "DiagnosticLoggingClient.h"
+#include "DiagnosticLoggingKeys.h"
 #include "Document.h"
 #include "DocumentLoader.h"
 #include "FrameLoader.h"
@@ -38,6 +40,7 @@
 #include "URL.h"
 #include "LoaderStrategy.h"
 #include "Logging.h"
+#include "MainFrame.h"
 #include "MemoryCache.h"
 #include "PlatformStrategies.h"
 #include "ResourceHandle.h"
@@ -65,34 +68,37 @@ static ResourceLoadPriority defaultPriorityForResourceType(CachedResource::Type
 {
     switch (type) {
     case CachedResource::MainResource:
-        return ResourceLoadPriorityVeryHigh;
+        return ResourceLoadPriority::VeryHigh;
     case CachedResource::CSSStyleSheet:
-        return ResourceLoadPriorityHigh;
+        return ResourceLoadPriority::High;
     case CachedResource::Script:
+#if ENABLE(SVG_FONTS)
+    case CachedResource::SVGFontResource:
+#endif
     case CachedResource::FontResource:
     case CachedResource::RawResource:
-        return ResourceLoadPriorityMedium;
+        return ResourceLoadPriority::Medium;
     case CachedResource::ImageResource:
-        return ResourceLoadPriorityLow;
+        return ResourceLoadPriority::Low;
 #if ENABLE(XSLT)
     case CachedResource::XSLStyleSheet:
-        return ResourceLoadPriorityHigh;
+        return ResourceLoadPriority::High;
 #endif
     case CachedResource::SVGDocumentResource:
-        return ResourceLoadPriorityLow;
+        return ResourceLoadPriority::Low;
 #if ENABLE(LINK_PREFETCH)
     case CachedResource::LinkPrefetch:
-        return ResourceLoadPriorityVeryLow;
+        return ResourceLoadPriority::VeryLow;
     case CachedResource::LinkSubresource:
-        return ResourceLoadPriorityVeryLow;
+        return ResourceLoadPriority::VeryLow;
 #endif
 #if ENABLE(VIDEO_TRACK)
     case CachedResource::TextTrackResource:
-        return ResourceLoadPriorityLow;
+        return ResourceLoadPriority::Low;
 #endif
     }
     ASSERT_NOT_REACHED();
-    return ResourceLoadPriorityLow;
+    return ResourceLoadPriority::Low;
 }
 
 static std::chrono::milliseconds deadDecodedDataDeletionIntervalForResourceType(CachedResource::Type type)
@@ -100,17 +106,17 @@ static std::chrono::milliseconds deadDecodedDataDeletionIntervalForResourceType(
     if (type == CachedResource::Script)
         return std::chrono::milliseconds { 0 };
 
-    return memoryCache()->deadDecodedDataDeletionInterval();
+    return MemoryCache::singleton().deadDecodedDataDeletionInterval();
 }
 
 DEFINE_DEBUG_ONLY_GLOBAL(RefCountedLeakCounter, cachedResourceLeakCounter, ("CachedResource"));
 
 CachedResource::CachedResource(const ResourceRequest& request, Type type, SessionID sessionID)
     : m_resourceRequest(request)
-    , m_decodedDataDeletionTimer(this, &CachedResource::decodedDataDeletionTimerFired, deadDecodedDataDeletionIntervalForResourceType(type))
+    , m_decodedDataDeletionTimer(*this, &CachedResource::destroyDecodedData, deadDecodedDataDeletionIntervalForResourceType(type))
     , m_sessionID(sessionID)
     , m_loadPriority(defaultPriorityForResourceType(type))
-    , m_responseTimestamp(currentTime())
+    , m_responseTimestamp(std::chrono::system_clock::now())
     , m_lastDecodedAccessTime(0)
     , m_loadFinishTime(0)
     , m_encodedSize(0)
@@ -119,7 +125,6 @@ CachedResource::CachedResource(const ResourceRequest& request, Type type, Sessio
     , m_handleCount(0)
     , m_preloadCount(0)
     , m_preloadResult(PreloadNotReferenced)
-    , m_inLiveDecodedResourcesList(false)
     , m_requestedFromNetworkingLayer(false)
     , m_inCache(false)
     , m_loading(false)
@@ -130,10 +135,6 @@ CachedResource::CachedResource(const ResourceRequest& request, Type type, Sessio
     , m_deleted(false)
     , m_lruIndex(0)
 #endif
-    , m_nextInAllResourcesList(0)
-    , m_prevInAllResourcesList(0)
-    , m_nextInLiveResourcesList(0)
-    , m_prevInLiveResourcesList(0)
     , m_owningCachedResourceLoader(0)
     , m_resourceToRevalidate(0)
     , m_proxyResource(0)
@@ -159,7 +160,7 @@ CachedResource::~CachedResource()
     ASSERT(canDelete());
     ASSERT(!inCache());
     ASSERT(!m_deleted);
-    ASSERT(url().isNull() || memoryCache()->resourceForRequest(resourceRequest(), sessionID()) != this);
+    ASSERT(url().isNull() || MemoryCache::singleton().resourceForRequest(resourceRequest(), sessionID()) != this);
 
 #ifndef NDEBUG
     m_deleted = true;
@@ -167,7 +168,7 @@ CachedResource::~CachedResource()
 #endif
 
     if (m_owningCachedResourceLoader)
-        m_owningCachedResourceLoader->removeCachedResource(this);
+        m_owningCachedResourceLoader->removeCachedResource(*this);
 }
 
 void CachedResource::failBeforeStarting()
@@ -175,17 +176,17 @@ void CachedResource::failBeforeStarting()
     // FIXME: What if resources in other frames were waiting for this revalidation?
     LOG(ResourceLoading, "Cannot start loading '%s'", url().string().latin1().data());
     if (m_resourceToRevalidate) 
-        memoryCache()->revalidationFailed(this); 
+        MemoryCache::singleton().revalidationFailed(*this);
     error(CachedResource::LoadError);
 }
 
-void CachedResource::addAdditionalRequestHeaders(CachedResourceLoader* cachedResourceLoader)
+void CachedResource::addAdditionalRequestHeaders(CachedResourceLoader& cachedResourceLoader)
 {
     // Note: We skip the Content-Security-Policy check here because we check
     // the Content-Security-Policy at the CachedResourceLoader layer so we can
     // handle different resource types differently.
 
-    FrameLoader& frameLoader = cachedResourceLoader->frame()->loader();
+    FrameLoader& frameLoader = cachedResourceLoader.frame()->loader();
     String outgoingReferrer;
     String outgoingOrigin;
     if (m_resourceRequest.httpReferrer().isNull()) {
@@ -196,7 +197,7 @@ void CachedResource::addAdditionalRequestHeaders(CachedResourceLoader* cachedRes
         outgoingOrigin = SecurityOrigin::createFromString(outgoingReferrer)->toString();
     }
 
-    outgoingReferrer = SecurityPolicy::generateReferrerHeader(cachedResourceLoader->document()->referrerPolicy(), m_resourceRequest.url(), outgoingReferrer);
+    outgoingReferrer = SecurityPolicy::generateReferrerHeader(cachedResourceLoader.document()->referrerPolicy(), m_resourceRequest.url(), outgoingReferrer);
     if (outgoingReferrer.isEmpty())
         m_resourceRequest.clearHTTPReferrer();
     else
@@ -206,14 +207,20 @@ void CachedResource::addAdditionalRequestHeaders(CachedResourceLoader* cachedRes
     frameLoader.addExtraFieldsToSubresourceRequest(m_resourceRequest);
 }
 
-void CachedResource::load(CachedResourceLoader* cachedResourceLoader, const ResourceLoaderOptions& options)
+void CachedResource::load(CachedResourceLoader& cachedResourceLoader, const ResourceLoaderOptions& options)
 {
-    if (!cachedResourceLoader->frame()) {
+    if (!cachedResourceLoader.frame()) {
         failBeforeStarting();
         return;
     }
 
-    FrameLoader& frameLoader = cachedResourceLoader->frame()->loader();
+    // Prevent new loads if we are in the PageCache or being added to the PageCache.
+    if (cachedResourceLoader.frame()->page() && cachedResourceLoader.frame()->page()->inPageCache()) {
+        failBeforeStarting();
+        return;
+    }
+
+    FrameLoader& frameLoader = cachedResourceLoader.frame()->loader();
     if (options.securityCheck() == DoSecurityCheck && (frameLoader.state() == FrameStateProvisional || !frameLoader.activeDocumentLoader() || frameLoader.activeDocumentLoader()->isStopping())) {
         failBeforeStarting();
         return;
@@ -227,7 +234,7 @@ void CachedResource::load(CachedResourceLoader* cachedResourceLoader, const Reso
         // When QuickLook is invoked to convert a document, it returns a unique URL in the
         // NSURLReponse for the main document. To make safeQLURLForDocumentURLAndResourceURL()
         // work, we need to use the QL URL not the original URL.
-        const URL& documentURL = cachedResourceLoader->frame() ? cachedResourceLoader->frame()->loader().documentLoader()->response().url() : cachedResourceLoader->document()->url();
+        const URL& documentURL = cachedResourceLoader.frame() ? cachedResourceLoader.frame()->loader().documentLoader()->response().url() : cachedResourceLoader.document()->url();
         m_resourceRequest.setURL(safeQLURLForDocumentURLAndResourceURL(documentURL, url()));
     }
 #endif
@@ -242,8 +249,8 @@ void CachedResource::load(CachedResourceLoader* cachedResourceLoader, const Reso
         const String& lastModified = resourceToRevalidate->response().httpHeaderField(HTTPHeaderName::LastModified);
         const String& eTag = resourceToRevalidate->response().httpHeaderField(HTTPHeaderName::ETag);
         if (!lastModified.isEmpty() || !eTag.isEmpty()) {
-            ASSERT(cachedResourceLoader->cachePolicy(type()) != CachePolicyReload);
-            if (cachedResourceLoader->cachePolicy(type()) == CachePolicyRevalidate)
+            ASSERT(cachedResourceLoader.cachePolicy(type()) != CachePolicyReload);
+            if (cachedResourceLoader.cachePolicy(type()) == CachePolicyRevalidate)
                 m_resourceRequest.setHTTPHeaderField(HTTPHeaderName::CacheControl, "max-age=0");
             if (!lastModified.isEmpty())
                 m_resourceRequest.setHTTPHeaderField(HTTPHeaderName::IfModifiedSince, lastModified);
@@ -271,7 +278,7 @@ void CachedResource::load(CachedResourceLoader* cachedResourceLoader, const Reso
         m_fragmentIdentifierForRequest = String();
     }
 
-    m_loader = platformStrategies()->loaderStrategy()->resourceLoadScheduler()->scheduleSubresourceLoad(cachedResourceLoader->frame(), this, request, options);
+    m_loader = platformStrategies()->loaderStrategy()->resourceLoadScheduler()->scheduleSubresourceLoad(cachedResourceLoader.frame(), this, request, options);
     if (!m_loader) {
         failBeforeStarting();
         return;
@@ -310,7 +317,7 @@ void CachedResource::error(CachedResource::Status status)
 {
     setStatus(status);
     ASSERT(errorOccurred());
-    m_data.clear();
+    m_data = nullptr;
 
     setLoading(false);
     checkNotify();
@@ -332,10 +339,17 @@ void CachedResource::finish()
         m_status = Cached;
 }
 
-bool CachedResource::passesAccessControlCheck(SecurityOrigin* securityOrigin)
+bool CachedResource::passesAccessControlCheck(SecurityOrigin& securityOrigin)
 {
     String errorDescription;
-    return WebCore::passesAccessControlCheck(m_response, resourceRequest().allowCookies() ? AllowStoredCredentials : DoNotAllowStoredCredentials, securityOrigin, errorDescription);
+    return WebCore::passesAccessControlCheck(response(), resourceRequest().allowCookies() ? AllowStoredCredentials : DoNotAllowStoredCredentials, &securityOrigin, errorDescription);
+}
+
+bool CachedResource::passesSameOriginPolicyCheck(SecurityOrigin& securityOrigin)
+{
+    if (securityOrigin.canRequest(responseForSameOriginPolicyChecks().url()))
+        return true;
+    return passesAccessControlCheck(securityOrigin);
 }
 
 bool CachedResource::isExpired() const
@@ -346,33 +360,43 @@ bool CachedResource::isExpired() const
     return computeCurrentAge(m_response, m_responseTimestamp) > freshnessLifetime(m_response);
 }
 
-double CachedResource::freshnessLifetime(const ResourceResponse& response) const
+std::chrono::microseconds CachedResource::freshnessLifetime(const ResourceResponse& response) const
 {
     if (!response.url().protocolIsInHTTPFamily()) {
         // Don't cache non-HTTP main resources since we can't check for freshness.
         // FIXME: We should not cache subresources either, but when we tried this
         // it caused performance and flakiness issues in our test infrastructure.
         if (m_type == MainResource && !SchemeRegistry::shouldCacheResponsesFromURLSchemeIndefinitely(response.url().protocol()))
-            return 0;
+            return std::chrono::microseconds::zero();
 
-        return std::numeric_limits<double>::max();
+        return std::chrono::microseconds::max();
     }
 
     return computeFreshnessLifetimeForHTTPFamily(response, m_responseTimestamp);
 }
 
-void CachedResource::willSendRequest(ResourceRequest&, const ResourceResponse& response)
+void CachedResource::redirectReceived(ResourceRequest& request, const ResourceResponse& response)
 {
     m_requestedFromNetworkingLayer = true;
     if (response.isNull())
         return;
+
+    // Redirect to data: URL uses the last HTTP response for SOP.
+    if (response.isHTTP() && request.url().protocolIsData())
+        m_redirectResponseForSameOriginPolicyChecks = response;
+
     updateRedirectChainStatus(m_redirectChainCacheStatus, response);
 }
 
+const ResourceResponse& CachedResource::responseForSameOriginPolicyChecks() const
+{
+    return m_redirectResponseForSameOriginPolicyChecks.isNull() ? m_response : m_redirectResponseForSameOriginPolicyChecks;
+}
+
 void CachedResource::responseReceived(const ResourceResponse& response)
 {
     setResponse(response);
-    m_responseTimestamp = currentTime();
+    m_responseTimestamp = std::chrono::system_clock::now();
     String encoding = response.textEncodingName();
     if (!encoding.isNull())
         setEncoding(encoding);
@@ -381,7 +405,9 @@ void CachedResource::responseReceived(const ResourceResponse& response)
 void CachedResource::clearLoader()
 {
     ASSERT(m_loader);
-    m_loader = 0;
+    m_identifierForLoadWithoutResourceLoader = m_loader->identifier();
+    m_loader = nullptr;
+    deleteIfPossible();
 }
 
 void CachedResource::addClient(CachedResourceClient* client)
@@ -412,7 +438,7 @@ bool CachedResource::addClientToSet(CachedResourceClient* client)
             m_preloadResult = PreloadReferenced;
     }
     if (!hasClients() && inCache())
-        memoryCache()->addToLiveResourcesSize(this);
+        MemoryCache::singleton().addToLiveResourcesSize(*this);
 
     if ((m_type == RawResource || m_type == MainResource) && !m_response.isNull() && !m_proxyResource) {
         // Certain resources (especially XHRs and main resources) do crazy things if an asynchronous load returns
@@ -443,9 +469,10 @@ void CachedResource::removeClient(CachedResourceClient* client)
 
     bool deleted = deleteIfPossible();
     if (!deleted && !hasClients()) {
+        auto& memoryCache = MemoryCache::singleton();
         if (inCache()) {
-            memoryCache()->removeFromLiveResourcesSize(this);
-            memoryCache()->removeFromLiveDecodedResourcesList(this);
+            memoryCache.removeFromLiveResourcesSize(*this);
+            memoryCache.removeFromLiveDecodedResourcesList(*this);
         }
         if (!m_switchingClientsToRevalidatedResource)
             allClientsRemoved();
@@ -455,9 +482,9 @@ void CachedResource::removeClient(CachedResourceClient* client)
             // "no-store: ... MUST make a best-effort attempt to remove the information from volatile storage as promptly as possible"
             // "... History buffers MAY store such responses as part of their normal operation."
             // We allow non-secure content to be reused in history, but we do not allow secure content to be reused.
-            memoryCache()->remove(this);
+            memoryCache.remove(*this);
         }
-        memoryCache()->prune();
+        memoryCache.pruneSoon();
     }
     // This object may be dead here.
 }
@@ -466,7 +493,7 @@ void CachedResource::destroyDecodedDataIfNeeded()
 {
     if (!m_decodedSize)
         return;
-    if (!memoryCache()->deadDecodedDataDeletionInterval().count())
+    if (!MemoryCache::singleton().deadDecodedDataDeletionInterval().count())
         return;
     m_decodedDataDeletionTimer.restart();
 }
@@ -479,7 +506,7 @@ void CachedResource::decodedDataDeletionTimerFired()
 bool CachedResource::deleteIfPossible()
 {
     if (canDelete() && !inCache()) {
-        InspectorInstrumentation::willDestroyCachedResource(this);
+        InspectorInstrumentation::willDestroyCachedResource(*this);
         delete this;
         return true;
     }
@@ -493,17 +520,17 @@ void CachedResource::setDecodedSize(unsigned size)
 
     int delta = size - m_decodedSize;
 
-    // The object must now be moved to a different queue, since its size has been changed.
-    // We have to remove explicitly before updating m_decodedSize, so that we find the correct previous
-    // queue.
+    // The object must be moved to a different queue, since its size has been changed.
+    // Remove before updating m_decodedSize, so we find the resource in the correct LRU list.
     if (inCache())
-        memoryCache()->removeFromLRUList(this);
+        MemoryCache::singleton().removeFromLRUList(*this);
     
     m_decodedSize = size;
    
-    if (inCache()) { 
+    if (inCache()) {
+        auto& memoryCache = MemoryCache::singleton();
         // Now insert into the new LRU list.
-        memoryCache()->insertInLRUList(this);
+        memoryCache.insertInLRUList(*this);
         
         // Insert into or remove from the live decoded list if necessary.
         // When inserting into the LiveDecodedResourcesList it is possible
@@ -512,13 +539,14 @@ void CachedResource::setDecodedSize(unsigned size)
         // violation of the invariant that the list is to be kept sorted
         // by access time. The weakening of the invariant does not pose
         // a problem. For more details please see: https://bugs.webkit.org/show_bug.cgi?id=30209
-        if (m_decodedSize && !m_inLiveDecodedResourcesList && hasClients())
-            memoryCache()->insertInLiveDecodedResourcesList(this);
-        else if (!m_decodedSize && m_inLiveDecodedResourcesList)
-            memoryCache()->removeFromLiveDecodedResourcesList(this);
+        bool inLiveDecodedResourcesList = memoryCache.inLiveDecodedResourcesList(*this);
+        if (m_decodedSize && !inLiveDecodedResourcesList && hasClients())
+            memoryCache.insertInLiveDecodedResourcesList(*this);
+        else if (!m_decodedSize && inLiveDecodedResourcesList)
+            memoryCache.removeFromLiveDecodedResourcesList(*this);
 
         // Update the cache's size totals.
-        memoryCache()->adjustSize(hasClients(), delta);
+        memoryCache.adjustSize(hasClients(), delta);
     }
 }
 
@@ -527,25 +555,19 @@ void CachedResource::setEncodedSize(unsigned size)
     if (size == m_encodedSize)
         return;
 
-    // The size cannot ever shrink (unless it is being nulled out because of an error).  If it ever does, assert.
-    ASSERT(size == 0 || size >= m_encodedSize);
-    
     int delta = size - m_encodedSize;
 
-    // The object must now be moved to a different queue, since its size has been changed.
-    // We have to remove explicitly before updating m_encodedSize, so that we find the correct previous
-    // queue.
+    // The object must be moved to a different queue, since its size has been changed.
+    // Remove before updating m_encodedSize, so we find the resource in the correct LRU list.
     if (inCache())
-        memoryCache()->removeFromLRUList(this);
-    
+        MemoryCache::singleton().removeFromLRUList(*this);
+
     m_encodedSize = size;
-   
-    if (inCache()) { 
-        // Now insert into the new LRU list.
-        memoryCache()->insertInLRUList(this);
-        
-        // Update the cache's size totals.
-        memoryCache()->adjustSize(hasClients(), delta);
+
+    if (inCache()) {
+        auto& memoryCache = MemoryCache::singleton();
+        memoryCache.insertInLRUList(*this);
+        memoryCache.adjustSize(hasClients(), delta);
     }
 }
 
@@ -554,11 +576,12 @@ void CachedResource::didAccessDecodedData(double timeStamp)
     m_lastDecodedAccessTime = timeStamp;
     
     if (inCache()) {
-        if (m_inLiveDecodedResourcesList) {
-            memoryCache()->removeFromLiveDecodedResourcesList(this);
-            memoryCache()->insertInLiveDecodedResourcesList(this);
+        auto& memoryCache = MemoryCache::singleton();
+        if (memoryCache.inLiveDecodedResourcesList(*this)) {
+            memoryCache.removeFromLiveDecodedResourcesList(*this);
+            memoryCache.insertInLiveDecodedResourcesList(*this);
         }
-        memoryCache()->prune();
+        memoryCache.pruneSoon();
     }
 }
     
@@ -569,29 +592,25 @@ void CachedResource::setResourceToRevalidate(CachedResource* resource)
     ASSERT(resource != this);
     ASSERT(m_handlesToRevalidate.isEmpty());
     ASSERT(resource->type() == type());
+    ASSERT(!resource->m_proxyResource);
 
     LOG(ResourceLoading, "CachedResource %p setResourceToRevalidate %p", this, resource);
 
-    // The following assert should be investigated whenever it occurs. Although it should never fire, it currently does in rare circumstances.
-    // https://bugs.webkit.org/show_bug.cgi?id=28604.
-    // So the code needs to be robust to this assert failing thus the "if (m_resourceToRevalidate->m_proxyResource == this)" in CachedResource::clearResourceToRevalidate.
-    ASSERT(!resource->m_proxyResource);
-
     resource->m_proxyResource = this;
     m_resourceToRevalidate = resource;
 }
 
 void CachedResource::clearResourceToRevalidate() 
-{ 
+{
     ASSERT(m_resourceToRevalidate);
+    ASSERT(m_resourceToRevalidate->m_proxyResource == this);
+
     if (m_switchingClientsToRevalidatedResource)
         return;
 
-    // A resource may start revalidation before this method has been called, so check that this resource is still the proxy resource before clearing it out.
-    if (m_resourceToRevalidate->m_proxyResource == this) {
-        m_resourceToRevalidate->m_proxyResource = 0;
-        m_resourceToRevalidate->deleteIfPossible();
-    }
+    m_resourceToRevalidate->m_proxyResource = nullptr;
+    m_resourceToRevalidate->deleteIfPossible();
+
     m_handlesToRevalidate.clear();
     m_resourceToRevalidate = 0;
     deleteIfPossible();
@@ -647,7 +666,7 @@ void CachedResource::switchClientsToRevalidatedResource()
 
 void CachedResource::updateResponseAfterRevalidation(const ResourceResponse& validatingResponse)
 {
-    m_responseTimestamp = currentTime();
+    m_responseTimestamp = std::chrono::system_clock::now();
 
     updateResponseHeadersAfterRevalidation(m_response, validatingResponse);
 }
@@ -681,38 +700,35 @@ bool CachedResource::canUseCacheValidator() const
     return m_response.hasCacheValidatorFields();
 }
 
-bool CachedResource::mustRevalidateDueToCacheHeaders(CachePolicy cachePolicy) const
+CachedResource::RevalidationDecision CachedResource::makeRevalidationDecision(CachePolicy cachePolicy) const
 {    
-    ASSERT(cachePolicy == CachePolicyRevalidate || cachePolicy == CachePolicyCache || cachePolicy == CachePolicyVerify);
-
-    if (cachePolicy == CachePolicyRevalidate)
-        return true;
-
-    if (m_response.cacheControlContainsNoCache() || m_response.cacheControlContainsNoStore()) {
-        LOG(ResourceLoading, "CachedResource %p mustRevalidate because of m_response.cacheControlContainsNoCache() || m_response.cacheControlContainsNoStore()\n", this);
-        return true;
-    }
-
-    if (cachePolicy == CachePolicyCache) {
-        if (m_response.cacheControlContainsMustRevalidate() && isExpired()) {
-            LOG(ResourceLoading, "CachedResource %p mustRevalidate because of cachePolicy == CachePolicyCache and m_response.cacheControlContainsMustRevalidate() && isExpired()\n", this);
-            return true;
-        }
-        return false;
-    }
-
-    // CachePolicyVerify
-    if (isExpired()) {
-        LOG(ResourceLoading, "CachedResource %p mustRevalidate because of isExpired()\n", this);
-        return true;
-    }
-
-    return false;
+    switch (cachePolicy) {
+    case CachePolicyHistoryBuffer:
+        return RevalidationDecision::No;
+
+    case CachePolicyReload:
+    case CachePolicyRevalidate:
+        return RevalidationDecision::YesDueToCachePolicy;
+
+    case CachePolicyVerify:
+        if (m_response.cacheControlContainsNoCache())
+            return RevalidationDecision::YesDueToNoCache;
+        // FIXME: Cache-Control:no-store should prevent storing, not reuse.
+        if (m_response.cacheControlContainsNoStore())
+            return RevalidationDecision::YesDueToNoStore;
+
+        if (isExpired())
+            return RevalidationDecision::YesDueToExpired;
+
+        return RevalidationDecision::No;
+    };
+    ASSERT_NOT_REACHED();
+    return RevalidationDecision::No;
 }
 
-bool CachedResource::redirectChainAllowsReuse() const
+bool CachedResource::redirectChainAllowsReuse(ReuseExpiredRedirectionOrNot reuseExpiredRedirection) const
 {
-    return WebCore::redirectChainAllowsReuse(m_redirectChainCacheStatus);
+    return WebCore::redirectChainAllowsReuse(m_redirectChainCacheStatus, reuseExpiredRedirection);
 }
 
 unsigned CachedResource::overheadSize() const
@@ -721,17 +737,30 @@ unsigned CachedResource::overheadSize() const
     return sizeof(CachedResource) + m_response.memoryUsage() + kAverageClientsHashMapSize + m_resourceRequest.url().string().length() * 2;
 }
 
-void CachedResource::setLoadPriority(ResourceLoadPriority loadPriority)
+bool CachedResource::areAllClientsXMLHttpRequests() const
+{
+    if (type() != RawResource)
+        return false;
+
+    for (auto& client : m_clients) {
+        if (!client.key->isXMLHttpRequest())
+            return false;
+    }
+    return true;
+}
+
+void CachedResource::setLoadPriority(const Optional<ResourceLoadPriority>& loadPriority)
 {
-    if (loadPriority == ResourceLoadPriorityUnresolved)
-        loadPriority = defaultPriorityForResourceType(type());
-    m_loadPriority = loadPriority;
+    if (loadPriority)
+        m_loadPriority = loadPriority.value();
+    else
+        m_loadPriority = defaultPriorityForResourceType(type());
 }
 
 inline CachedResource::Callback::Callback(CachedResource& resource, CachedResourceClient& client)
     : m_resource(resource)
     , m_client(client)
-    , m_timer(this, &Callback::timerFired)
+    , m_timer(*this, &Callback::timerFired)
 {
     m_timer.startOneShot(0);
 }
@@ -742,12 +771,12 @@ inline void CachedResource::Callback::cancel()
         m_timer.stop();
 }
 
-void CachedResource::Callback::timerFired(Timer<Callback>&)
+void CachedResource::Callback::timerFired()
 {
     m_resource.didAddClient(&m_client);
 }
 
-#if USE(FOUNDATION)
+#if USE(FOUNDATION) || USE(SOUP)
 
 void CachedResource::tryReplaceEncodedData(SharedBuffer& newBuffer)
 {