2 Copyright (C) 1998 Lars Knoll (knoll@mpi-hd.mpg.de)
3 Copyright (C) 2001 Dirk Mueller (mueller@kde.org)
4 Copyright (C) 2002 Waldo Bastian (bastian@kde.org)
5 Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
6 Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
8 This library is free software; you can redistribute it and/or
9 modify it under the terms of the GNU Library General Public
10 License as published by the Free Software Foundation; either
11 version 2 of the License, or (at your option) any later version.
13 This library is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Library General Public License for more details.
18 You should have received a copy of the GNU Library General Public License
19 along with this library; see the file COPYING.LIB. If not, write to
20 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21 Boston, MA 02110-1301, USA.
25 #include "core/fetch/Resource.h"
27 #include "FetchInitiatorTypeNames.h"
28 #include "core/fetch/CachedMetadata.h"
29 #include "core/fetch/CrossOriginAccessControl.h"
30 #include "core/fetch/MemoryCache.h"
31 #include "core/fetch/ResourceClient.h"
32 #include "core/fetch/ResourceClientWalker.h"
33 #include "core/fetch/ResourceFetcher.h"
34 #include "core/fetch/ResourceLoader.h"
35 #include "core/fetch/ResourcePtr.h"
36 #include "core/inspector/InspectorInstrumentation.h"
37 #include "platform/Logging.h"
38 #include "platform/PurgeableBuffer.h"
39 #include "platform/SharedBuffer.h"
40 #include "platform/weborigin/KURL.h"
41 #include "public/platform/Platform.h"
42 #include "wtf/CurrentTime.h"
43 #include "wtf/MathExtras.h"
44 #include "wtf/RefCountedLeakCounter.h"
45 #include "wtf/StdLibExtras.h"
46 #include "wtf/Vector.h"
47 #include "wtf/text/CString.h"
53 // These response headers are not copied from a revalidated response to the
54 // cached response headers. For compatibility, this list is based on Chromium's
55 // net/http/http_response_headers.cc.
56 const char* const headersToIgnoreAfterRevalidation[] = {
73 // Some header prefixes mean "Don't copy this header from a 304 response.".
74 // Rather than listing all the relevant headers, we can consolidate them into
75 // this list, also grabbed from Chromium's net/http/http_response_headers.cc.
76 const char* const headerPrefixesToIgnoreAfterRevalidation[] = {
82 static inline bool shouldUpdateHeaderAfterRevalidation(const AtomicString& header)
84 for (size_t i = 0; i < WTF_ARRAY_LENGTH(headersToIgnoreAfterRevalidation); i++) {
85 if (equalIgnoringCase(header, headersToIgnoreAfterRevalidation[i]))
88 for (size_t i = 0; i < WTF_ARRAY_LENGTH(headerPrefixesToIgnoreAfterRevalidation); i++) {
89 if (header.startsWith(headerPrefixesToIgnoreAfterRevalidation[i], false))
95 DEFINE_DEBUG_ONLY_GLOBAL(RefCountedLeakCounter, cachedResourceLeakCounter, ("Resource"));
97 Resource::Resource(const ResourceRequest& request, Type type)
98 : m_resourceRequest(request)
99 , m_responseTimestamp(currentTime())
100 , m_cancelTimer(this, &Resource::cancelTimerFired)
101 , m_lastDecodedAccessTime(0)
102 , m_loadFinishTime(0)
109 , m_protectorCount(0)
110 , m_preloadResult(PreloadNotReferenced)
111 , m_cacheLiveResourcePriority(CacheLiveResourcePriorityLow)
112 , m_inLiveDecodedResourcesList(false)
113 , m_requestedFromNetworkingLayer(false)
116 , m_switchingClientsToRevalidatedResource(false)
120 , m_needsSynchronousCacheHit(false)
125 , m_nextInAllResourcesList(0)
126 , m_prevInAllResourcesList(0)
127 , m_nextInLiveResourcesList(0)
128 , m_prevInLiveResourcesList(0)
129 , m_resourceToRevalidate(0)
132 ASSERT(m_type == unsigned(type)); // m_type is a bitfield, so this tests careless updates of the enum.
134 cachedResourceLeakCounter.increment();
137 if (!m_resourceRequest.url().hasFragmentIdentifier())
139 KURL urlForCache = MemoryCache::removeFragmentIdentifierIfNeeded(m_resourceRequest.url());
140 if (urlForCache.hasFragmentIdentifier())
142 m_fragmentIdentifierForRequest = m_resourceRequest.url().fragmentIdentifier();
143 m_resourceRequest.setURL(urlForCache);
146 Resource::~Resource()
148 ASSERT(!m_resourceToRevalidate); // Should be true because canDelete() checks this.
152 ASSERT(url().isNull() || memoryCache()->resourceForURL(KURL(ParsedURLString, url())) != this);
156 cachedResourceLeakCounter.decrement();
160 void Resource::failBeforeStarting()
162 WTF_LOG(ResourceLoading, "Cannot start loading '%s'", url().string().latin1().data());
163 error(Resource::LoadError);
166 void Resource::load(ResourceFetcher* fetcher, const ResourceLoaderOptions& options)
168 if (!fetcher->frame()) {
169 failBeforeStarting();
176 if (!accept().isEmpty())
177 m_resourceRequest.setHTTPAccept(accept());
179 // FIXME: It's unfortunate that the cache layer and below get to know anything about fragment identifiers.
180 // We should look into removing the expectation of that knowledge from the platform network stacks.
181 ResourceRequest request(m_resourceRequest);
182 if (!m_fragmentIdentifierForRequest.isNull()) {
183 KURL url = request.url();
184 url.setFragmentIdentifier(m_fragmentIdentifierForRequest);
186 m_fragmentIdentifierForRequest = String();
190 RELEASE_ASSERT(m_options.synchronousPolicy == RequestSynchronously);
191 m_loader->changeToSynchronous();
194 m_loader = ResourceLoader::create(fetcher, this, request, options);
198 void Resource::checkNotify()
203 ResourceClientWalker<ResourceClient> w(m_clients);
204 while (ResourceClient* c = w.next())
205 c->notifyFinished(this);
208 void Resource::appendData(const char* data, int length)
210 TRACE_EVENT0("webkit", "Resource::appendData");
211 ASSERT(!m_resourceToRevalidate);
212 ASSERT(!errorOccurred());
213 if (m_options.dataBufferingPolicy == DoNotBufferData)
216 m_data->append(data, length);
218 m_data = SharedBuffer::create(data, length);
219 setEncodedSize(m_data->size());
222 void Resource::setResourceBuffer(PassRefPtr<SharedBuffer> resourceBuffer)
224 ASSERT(!m_resourceToRevalidate);
225 ASSERT(!errorOccurred());
226 ASSERT(m_options.dataBufferingPolicy == BufferData);
227 m_data = resourceBuffer;
228 setEncodedSize(m_data->size());
231 void Resource::setDataBufferingPolicy(DataBufferingPolicy dataBufferingPolicy)
233 m_options.dataBufferingPolicy = dataBufferingPolicy;
238 void Resource::error(Resource::Status status)
240 if (m_resourceToRevalidate)
241 revalidationFailed();
243 if (!m_error.isNull() && (m_error.isCancellation() || !isPreloaded()))
244 memoryCache()->remove(this);
247 ASSERT(errorOccurred());
254 void Resource::finishOnePart()
260 void Resource::finish(double finishTime)
262 ASSERT(!m_resourceToRevalidate);
263 ASSERT(!errorOccurred());
264 m_loadFinishTime = finishTime;
266 if (!errorOccurred())
270 bool Resource::passesAccessControlCheck(SecurityOrigin* securityOrigin)
272 String ignoredErrorDescription;
273 return passesAccessControlCheck(securityOrigin, ignoredErrorDescription);
276 bool Resource::passesAccessControlCheck(SecurityOrigin* securityOrigin, String& errorDescription)
278 return WebCore::passesAccessControlCheck(m_response, resourceRequest().allowCookies() ? AllowStoredCredentials : DoNotAllowStoredCredentials, securityOrigin, errorDescription);
281 bool Resource::isExpired() const
283 if (m_response.isNull())
286 return currentAge() > freshnessLifetime();
289 double Resource::currentAge() const
292 // No compensation for latency as that is not terribly important in practice
293 double dateValue = m_response.date();
294 double apparentAge = std::isfinite(dateValue) ? std::max(0., m_responseTimestamp - dateValue) : 0;
295 double ageValue = m_response.age();
296 double correctedReceivedAge = std::isfinite(ageValue) ? std::max(apparentAge, ageValue) : apparentAge;
297 double residentTime = currentTime() - m_responseTimestamp;
298 return correctedReceivedAge + residentTime;
301 double Resource::freshnessLifetime() const
304 // On desktop, local files should be reloaded in case they change.
305 if (m_response.url().isLocalFile())
309 // Cache other non-http / non-filesystem resources liberally.
310 if (!m_response.url().protocolIsInHTTPFamily()
311 && !m_response.url().protocolIs("filesystem"))
312 return std::numeric_limits<double>::max();
315 double maxAgeValue = m_response.cacheControlMaxAge();
316 if (std::isfinite(maxAgeValue))
318 double expiresValue = m_response.expires();
319 double dateValue = m_response.date();
320 double creationTime = std::isfinite(dateValue) ? dateValue : m_responseTimestamp;
321 if (std::isfinite(expiresValue))
322 return expiresValue - creationTime;
323 double lastModifiedValue = m_response.lastModified();
324 if (std::isfinite(lastModifiedValue))
325 return (creationTime - lastModifiedValue) * 0.1;
326 // If no cache headers are present, the specification leaves the decision to the UA. Other browsers seem to opt for 0.
330 void Resource::responseReceived(const ResourceResponse& response)
332 setResponse(response);
333 m_responseTimestamp = currentTime();
334 String encoding = response.textEncodingName();
335 if (!encoding.isNull())
336 setEncoding(encoding);
338 if (!m_resourceToRevalidate)
340 if (response.httpStatusCode() == 304)
341 revalidationSucceeded(response);
343 revalidationFailed();
346 void Resource::setSerializedCachedMetadata(const char* data, size_t size)
348 // We only expect to receive cached metadata from the platform once.
349 // If this triggers, it indicates an efficiency problem which is most
350 // likely unexpected in code designed to improve performance.
351 ASSERT(!m_cachedMetadata);
352 ASSERT(!m_resourceToRevalidate);
354 m_cachedMetadata = CachedMetadata::deserialize(data, size);
357 void Resource::setCachedMetadata(unsigned dataTypeID, const char* data, size_t size)
359 // Currently, only one type of cached metadata per resource is supported.
360 // If the need arises for multiple types of metadata per resource this could
361 // be enhanced to store types of metadata in a map.
362 ASSERT(!m_cachedMetadata);
364 m_cachedMetadata = CachedMetadata::create(dataTypeID, data, size);
365 const Vector<char>& serializedData = m_cachedMetadata->serialize();
366 blink::Platform::current()->cacheMetadata(m_response.url(), m_response.responseTime(), serializedData.data(), serializedData.size());
369 CachedMetadata* Resource::cachedMetadata(unsigned dataTypeID) const
371 if (!m_cachedMetadata || m_cachedMetadata->dataTypeID() != dataTypeID)
373 return m_cachedMetadata.get();
376 void Resource::setCacheLiveResourcePriority(CacheLiveResourcePriority priority)
378 if (inCache() && m_inLiveDecodedResourcesList && cacheLiveResourcePriority() != static_cast<unsigned>(priority)) {
379 memoryCache()->removeFromLiveDecodedResourcesList(this);
380 m_cacheLiveResourcePriority = priority;
381 memoryCache()->insertInLiveDecodedResourcesList(this);
382 memoryCache()->prune();
386 void Resource::clearLoader()
391 void Resource::addClient(ResourceClient* client)
393 if (addClientToSet(client))
394 didAddClient(client);
397 void Resource::didAddClient(ResourceClient* c)
399 if (!isLoading() && !stillNeedsLoad())
400 c->notifyFinished(this);
403 static bool shouldSendCachedDataSynchronouslyForType(Resource::Type type)
405 // Some resources types default to return data synchronously.
406 // For most of these, it's because there are layout tests that
407 // expect data to return synchronously in case of cache hit. In
408 // the case of fonts, there was a performance regression.
409 // FIXME: Get to the point where we don't need to special-case sync/async
410 // behavior for different resource types.
411 if (type == Resource::Image)
413 if (type == Resource::CSSStyleSheet)
415 if (type == Resource::Script)
417 if (type == Resource::Font)
422 bool Resource::addClientToSet(ResourceClient* client)
424 ASSERT(!isPurgeable());
426 if (m_preloadResult == PreloadNotReferenced) {
428 m_preloadResult = PreloadReferencedWhileComplete;
429 else if (m_requestedFromNetworkingLayer)
430 m_preloadResult = PreloadReferencedWhileLoading;
432 m_preloadResult = PreloadReferenced;
434 if (!hasClients() && inCache())
435 memoryCache()->addToLiveResourcesSize(this);
437 // If we have existing data to send to the new client and the resource type supprts it, send it asynchronously.
438 if (!m_response.isNull() && !m_proxyResource && !shouldSendCachedDataSynchronouslyForType(type()) && !m_needsSynchronousCacheHit) {
439 m_clientsAwaitingCallback.add(client);
440 ResourceCallback::callbackHandler()->schedule(this);
444 m_clients.add(client);
448 void Resource::removeClient(ResourceClient* client)
450 if (m_clientsAwaitingCallback.contains(client)) {
451 ASSERT(!m_clients.contains(client));
452 m_clientsAwaitingCallback.remove(client);
453 if (m_clientsAwaitingCallback.isEmpty())
454 ResourceCallback::callbackHandler()->cancel(this);
456 ASSERT(m_clients.contains(client));
457 m_clients.remove(client);
458 didRemoveClient(client);
461 bool deleted = deleteIfPossible();
462 if (!deleted && !hasClients()) {
464 memoryCache()->removeFromLiveResourcesSize(this);
465 memoryCache()->removeFromLiveDecodedResourcesList(this);
467 if (!m_switchingClientsToRevalidatedResource)
469 if (response().cacheControlContainsNoStore()) {
471 // "no-store: ... MUST make a best-effort attempt to remove the information from volatile storage as promptly as possible"
472 // "... History buffers MAY store such responses as part of their normal operation."
473 // We allow non-secure content to be reused in history, but we do not allow secure content to be reused.
474 if (url().protocolIs("https"))
475 memoryCache()->remove(this);
477 memoryCache()->prune(this);
480 // This object may be dead here.
483 void Resource::allClientsRemoved()
487 if (m_type == MainResource || m_type == Raw)
488 cancelTimerFired(&m_cancelTimer);
489 else if (!m_cancelTimer.isActive())
490 m_cancelTimer.startOneShot(0);
493 void Resource::cancelTimerFired(Timer<Resource>* timer)
495 ASSERT_UNUSED(timer, timer == &m_cancelTimer);
496 if (hasClients() || !m_loader)
498 ResourcePtr<Resource> protect(this);
499 m_loader->cancelIfNotFinishing();
500 if (m_status != Cached)
501 memoryCache()->remove(this);
504 bool Resource::deleteIfPossible()
506 if (canDelete() && !inCache()) {
507 InspectorInstrumentation::willDestroyResource(this);
514 void Resource::setDecodedSize(size_t size)
516 if (size == m_decodedSize)
519 ptrdiff_t delta = size - m_decodedSize;
521 // The object must now be moved to a different queue, since its size has been changed.
522 // We have to remove explicitly before updating m_decodedSize, so that we find the correct previous
525 memoryCache()->removeFromLRUList(this);
527 m_decodedSize = size;
530 // Now insert into the new LRU list.
531 memoryCache()->insertInLRUList(this);
533 // Insert into or remove from the live decoded list if necessary.
534 // When inserting into the LiveDecodedResourcesList it is possible
535 // that the m_lastDecodedAccessTime is still zero or smaller than
536 // the m_lastDecodedAccessTime of the current list head. This is a
537 // violation of the invariant that the list is to be kept sorted
538 // by access time. The weakening of the invariant does not pose
539 // a problem. For more details please see: https://bugs.webkit.org/show_bug.cgi?id=30209
540 if (m_decodedSize && !m_inLiveDecodedResourcesList && hasClients())
541 memoryCache()->insertInLiveDecodedResourcesList(this);
542 else if (!m_decodedSize && m_inLiveDecodedResourcesList)
543 memoryCache()->removeFromLiveDecodedResourcesList(this);
545 // Update the cache's size totals.
546 memoryCache()->adjustSize(hasClients(), delta);
550 void Resource::setEncodedSize(size_t size)
552 if (size == m_encodedSize)
555 ptrdiff_t delta = size - m_encodedSize;
557 // The object must now be moved to a different queue, since its size has been changed.
558 // We have to remove explicitly before updating m_encodedSize, so that we find the correct previous
561 memoryCache()->removeFromLRUList(this);
563 m_encodedSize = size;
566 // Now insert into the new LRU list.
567 memoryCache()->insertInLRUList(this);
569 // Update the cache's size totals.
570 memoryCache()->adjustSize(hasClients(), delta);
574 void Resource::didAccessDecodedData(double timeStamp)
576 m_lastDecodedAccessTime = timeStamp;
578 if (m_inLiveDecodedResourcesList) {
579 memoryCache()->removeFromLiveDecodedResourcesList(this);
580 memoryCache()->insertInLiveDecodedResourcesList(this);
582 memoryCache()->prune();
586 void Resource::finishPendingClients()
588 while (!m_clientsAwaitingCallback.isEmpty()) {
589 ResourceClient* client = m_clientsAwaitingCallback.begin()->key;
590 m_clientsAwaitingCallback.remove(client);
591 m_clients.add(client);
592 didAddClient(client);
596 void Resource::setResourceToRevalidate(Resource* resource)
599 ASSERT(!m_resourceToRevalidate);
600 ASSERT(resource != this);
601 ASSERT(m_handlesToRevalidate.isEmpty());
602 ASSERT(resource->type() == type());
604 WTF_LOG(ResourceLoading, "Resource %p setResourceToRevalidate %p", this, resource);
606 // The following assert should be investigated whenever it occurs. Although it should never fire, it currently does in rare circumstances.
607 // https://bugs.webkit.org/show_bug.cgi?id=28604.
608 // So the code needs to be robust to this assert failing thus the "if (m_resourceToRevalidate->m_proxyResource == this)" in Resource::clearResourceToRevalidate.
609 ASSERT(!resource->m_proxyResource);
611 resource->m_proxyResource = this;
612 m_resourceToRevalidate = resource;
615 void Resource::clearResourceToRevalidate()
617 ASSERT(m_resourceToRevalidate);
618 if (m_switchingClientsToRevalidatedResource)
621 // 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.
622 if (m_resourceToRevalidate->m_proxyResource == this) {
623 m_resourceToRevalidate->m_proxyResource = 0;
624 m_resourceToRevalidate->deleteIfPossible();
626 m_handlesToRevalidate.clear();
627 m_resourceToRevalidate = 0;
631 void Resource::switchClientsToRevalidatedResource()
633 ASSERT(m_resourceToRevalidate);
634 ASSERT(m_resourceToRevalidate->inCache());
637 WTF_LOG(ResourceLoading, "Resource %p switchClientsToRevalidatedResource %p", this, m_resourceToRevalidate);
639 m_resourceToRevalidate->m_identifier = m_identifier;
641 m_switchingClientsToRevalidatedResource = true;
642 HashSet<ResourcePtrBase*>::iterator end = m_handlesToRevalidate.end();
643 for (HashSet<ResourcePtrBase*>::iterator it = m_handlesToRevalidate.begin(); it != end; ++it) {
644 ResourcePtrBase* handle = *it;
645 handle->m_resource = m_resourceToRevalidate;
646 m_resourceToRevalidate->registerHandle(handle);
649 ASSERT(!m_handleCount);
650 m_handlesToRevalidate.clear();
652 Vector<ResourceClient*> clientsToMove;
653 HashCountedSet<ResourceClient*>::iterator end2 = m_clients.end();
654 for (HashCountedSet<ResourceClient*>::iterator it = m_clients.begin(); it != end2; ++it) {
655 ResourceClient* client = it->key;
656 unsigned count = it->value;
658 clientsToMove.append(client);
663 unsigned moveCount = clientsToMove.size();
664 for (unsigned n = 0; n < moveCount; ++n)
665 removeClient(clientsToMove[n]);
666 ASSERT(m_clients.isEmpty());
668 for (unsigned n = 0; n < moveCount; ++n)
669 m_resourceToRevalidate->addClientToSet(clientsToMove[n]);
670 for (unsigned n = 0; n < moveCount; ++n) {
671 // Calling didAddClient may do anything, including trying to cancel revalidation.
672 // Assert that it didn't succeed.
673 ASSERT(m_resourceToRevalidate);
674 // Calling didAddClient for a client may end up removing another client. In that case it won't be in the set anymore.
675 if (m_resourceToRevalidate->m_clients.contains(clientsToMove[n]))
676 m_resourceToRevalidate->didAddClient(clientsToMove[n]);
678 m_switchingClientsToRevalidatedResource = false;
681 void Resource::updateResponseAfterRevalidation(const ResourceResponse& validatingResponse)
683 m_responseTimestamp = currentTime();
686 // Update cached headers from the 304 response
687 const HTTPHeaderMap& newHeaders = validatingResponse.httpHeaderFields();
688 HTTPHeaderMap::const_iterator end = newHeaders.end();
689 for (HTTPHeaderMap::const_iterator it = newHeaders.begin(); it != end; ++it) {
690 // Entity headers should not be sent by servers when generating a 304
691 // response; misconfigured servers send them anyway. We shouldn't allow
692 // such headers to update the original request. We'll base this on the
693 // list defined by RFC2616 7.1, with a few additions for extension headers
695 if (!shouldUpdateHeaderAfterRevalidation(it->key))
697 m_response.setHTTPHeaderField(it->key, it->value);
701 void Resource::revalidationSucceeded(const ResourceResponse& response)
703 ASSERT(m_resourceToRevalidate);
704 ASSERT(!m_resourceToRevalidate->inCache());
705 ASSERT(m_resourceToRevalidate->isLoaded());
708 // Calling evict() can potentially delete revalidatingResource, which we use
709 // below. This mustn't be the case since revalidation means it is loaded
710 // and so canDelete() is false.
711 ASSERT(!canDelete());
713 m_resourceToRevalidate->updateResponseAfterRevalidation(response);
714 memoryCache()->replace(m_resourceToRevalidate, this);
716 switchClientsToRevalidatedResource();
718 // clearResourceToRevalidate deletes this.
719 clearResourceToRevalidate();
722 void Resource::revalidationFailed()
724 ASSERT(WTF::isMainThread());
725 WTF_LOG(ResourceLoading, "Revalidation failed for %p", this);
726 ASSERT(resourceToRevalidate());
727 clearResourceToRevalidate();
730 void Resource::updateForAccess()
734 // Need to make sure to remove before we increase the access count, since
735 // the queue will possibly change.
736 memoryCache()->removeFromLRUList(this);
738 // If this is the first time the resource has been accessed, adjust the size of the cache to account for its initial size.
740 memoryCache()->adjustSize(hasClients(), size());
743 memoryCache()->insertInLRUList(this);
746 void Resource::registerHandle(ResourcePtrBase* h)
749 if (m_resourceToRevalidate)
750 m_handlesToRevalidate.add(h);
753 void Resource::unregisterHandle(ResourcePtrBase* h)
755 ASSERT(m_handleCount > 0);
758 if (m_resourceToRevalidate)
759 m_handlesToRevalidate.remove(h);
765 bool Resource::canUseCacheValidator() const
767 if (m_loading || errorOccurred())
770 if (m_response.cacheControlContainsNoStore())
772 return m_response.hasCacheValidatorFields();
775 bool Resource::mustRevalidateDueToCacheHeaders() const
777 if (m_response.cacheControlContainsNoCache() || m_response.cacheControlContainsNoStore()) {
778 WTF_LOG(ResourceLoading, "Resource %p mustRevalidate because of m_response.cacheControlContainsNoCache() || m_response.cacheControlContainsNoStore()\n", this);
783 WTF_LOG(ResourceLoading, "Resource %p mustRevalidate because of isExpired()\n", this);
790 bool Resource::isSafeToMakePurgeable() const
792 return !hasClients() && !m_proxyResource && !m_resourceToRevalidate;
795 bool Resource::makePurgeable(bool purgeable)
798 ASSERT(isSafeToMakePurgeable());
800 if (m_purgeableData) {
807 // Should not make buffer purgeable if it has refs other than this since we don't want two copies.
808 if (!m_data->hasOneRef())
811 m_data->createPurgeableBuffer();
812 if (!m_data->hasPurgeableBuffer())
815 m_purgeableData = m_data->releasePurgeableBuffer();
816 m_purgeableData->unlock();
821 if (!m_purgeableData)
825 ASSERT(!hasClients());
827 if (!m_purgeableData->lock()) {
832 m_data = SharedBuffer::adoptPurgeableBuffer(m_purgeableData.release());
836 bool Resource::isPurgeable() const
838 return m_purgeableData && !m_purgeableData->isLocked();
841 bool Resource::wasPurged() const
846 size_t Resource::overheadSize() const
848 static const int kAverageClientsHashMapSize = 384;
849 return sizeof(Resource) + m_response.memoryUsage() + kAverageClientsHashMapSize + m_resourceRequest.url().string().length() * 2;
852 void Resource::didChangePriority(ResourceLoadPriority loadPriority)
855 m_loader->didChangePriority(loadPriority);
858 Resource::ResourceCallback* Resource::ResourceCallback::callbackHandler()
860 DEFINE_STATIC_LOCAL(ResourceCallback, callbackHandler, ());
861 return &callbackHandler;
864 Resource::ResourceCallback::ResourceCallback()
865 : m_callbackTimer(this, &ResourceCallback::timerFired)
869 void Resource::ResourceCallback::schedule(Resource* resource)
871 if (!m_callbackTimer.isActive())
872 m_callbackTimer.startOneShot(0);
873 m_resourcesWithPendingClients.add(resource);
876 void Resource::ResourceCallback::cancel(Resource* resource)
878 m_resourcesWithPendingClients.remove(resource);
879 if (m_callbackTimer.isActive() && m_resourcesWithPendingClients.isEmpty())
880 m_callbackTimer.stop();
883 void Resource::ResourceCallback::timerFired(Timer<ResourceCallback>*)
885 HashSet<Resource*>::iterator end = m_resourcesWithPendingClients.end();
886 Vector<ResourcePtr<Resource> > resources;
887 for (HashSet<Resource*>::iterator it = m_resourcesWithPendingClients.begin(); it != end; ++it)
888 resources.append(*it);
889 m_resourcesWithPendingClients.clear();
890 for (size_t i = 0; i < resources.size(); i++)
891 resources[i]->finishPendingClients();
894 static const char* initatorTypeNameToString(const AtomicString& initiatorTypeName)
896 if (initiatorTypeName == FetchInitiatorTypeNames::css)
897 return "CSS resource";
898 if (initiatorTypeName == FetchInitiatorTypeNames::document)
900 if (initiatorTypeName == FetchInitiatorTypeNames::icon)
902 if (initiatorTypeName == FetchInitiatorTypeNames::internal)
903 return "Internal resource";
904 if (initiatorTypeName == FetchInitiatorTypeNames::link)
905 return "Link element resource";
906 if (initiatorTypeName == FetchInitiatorTypeNames::processinginstruction)
907 return "Processing instruction";
908 if (initiatorTypeName == FetchInitiatorTypeNames::texttrack)
910 if (initiatorTypeName == FetchInitiatorTypeNames::xml)
911 return "XML resource";
912 if (initiatorTypeName == FetchInitiatorTypeNames::xmlhttprequest)
913 return "XMLHttpRequest";
918 const char* Resource::resourceTypeToString(Type type, const FetchInitiatorInfo& initiatorInfo)
921 case Resource::MainResource:
922 return "Main resource";
923 case Resource::Image:
925 case Resource::CSSStyleSheet:
926 return "CSS stylesheet";
927 case Resource::Script:
932 return initatorTypeNameToString(initiatorInfo.name);
933 case Resource::SVGDocument:
934 return "SVG document";
935 case Resource::XSLStyleSheet:
936 return "XSL stylesheet";
937 case Resource::LinkPrefetch:
938 return "Link prefetch resource";
939 case Resource::LinkSubresource:
940 return "Link subresource";
941 case Resource::TextTrack:
943 case Resource::Shader:
945 case Resource::ImportResource:
946 return "Imported resource";
948 ASSERT_NOT_REACHED();
949 return initatorTypeNameToString(initiatorInfo.name);
953 const char* ResourceTypeName(Resource::Type type)
956 case Resource::MainResource:
957 return "MainResource";
958 case Resource::Image:
960 case Resource::CSSStyleSheet:
961 return "CSSStyleSheet";
962 case Resource::Script:
968 case Resource::SVGDocument:
969 return "SVGDocument";
970 case Resource::XSLStyleSheet:
971 return "XSLStyleSheet";
972 case Resource::LinkPrefetch:
973 return "LinkPrefetch";
974 case Resource::LinkSubresource:
975 return "LinkSubresource";
976 case Resource::TextTrack:
978 case Resource::Shader:
980 case Resource::ImportResource:
981 return "ImportResource";
983 ASSERT_NOT_REACHED();
986 #endif // !LOG_DISABLED