Bug 1754107: Release the memory allocated by calls to VTSessionCopyProperty. r=media...
[gecko.git] / image / imgLoader.h
blob936b73b1061759d7d8049631e1d73fab4a1aabaf
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #ifndef mozilla_image_imgLoader_h
8 #define mozilla_image_imgLoader_h
10 #include "mozilla/Attributes.h"
11 #include "mozilla/CORSMode.h"
12 #include "mozilla/Mutex.h"
13 #include "mozilla/UniquePtr.h"
15 #include "imgILoader.h"
16 #include "imgICache.h"
17 #include "nsWeakReference.h"
18 #include "nsIContentSniffer.h"
19 #include "nsRefPtrHashtable.h"
20 #include "nsTHashSet.h"
21 #include "nsExpirationTracker.h"
22 #include "ImageCacheKey.h"
23 #include "imgRequest.h"
24 #include "nsIProgressEventSink.h"
25 #include "nsIChannel.h"
26 #include "nsIThreadRetargetableStreamListener.h"
27 #include "imgIRequest.h"
29 class imgLoader;
30 class imgRequestProxy;
31 class imgINotificationObserver;
32 class nsILoadGroup;
33 class imgCacheExpirationTracker;
34 class imgMemoryReporter;
36 namespace mozilla {
37 namespace dom {
38 class Document;
40 } // namespace mozilla
42 class imgCacheEntry {
43 public:
44 imgCacheEntry(imgLoader* loader, imgRequest* request,
45 bool aForcePrincipalCheck);
46 ~imgCacheEntry();
48 nsrefcnt AddRef() {
49 MOZ_ASSERT(int32_t(mRefCnt) >= 0, "illegal refcnt");
50 NS_ASSERT_OWNINGTHREAD(imgCacheEntry);
51 ++mRefCnt;
52 NS_LOG_ADDREF(this, mRefCnt, "imgCacheEntry", sizeof(*this));
53 return mRefCnt;
56 nsrefcnt Release() {
57 MOZ_ASSERT(0 != mRefCnt, "dup release");
58 NS_ASSERT_OWNINGTHREAD(imgCacheEntry);
59 --mRefCnt;
60 NS_LOG_RELEASE(this, mRefCnt, "imgCacheEntry");
61 if (mRefCnt == 0) {
62 mRefCnt = 1; /* stabilize */
63 delete this;
64 return 0;
66 return mRefCnt;
69 uint32_t GetDataSize() const { return mDataSize; }
70 void SetDataSize(uint32_t aDataSize) {
71 int32_t oldsize = mDataSize;
72 mDataSize = aDataSize;
73 UpdateCache(mDataSize - oldsize);
76 int32_t GetTouchedTime() const { return mTouchedTime; }
77 void SetTouchedTime(int32_t time) {
78 mTouchedTime = time;
79 Touch(/* updateTime = */ false);
82 uint32_t GetLoadTime() const { return mLoadTime; }
84 void UpdateLoadTime();
86 uint32_t GetExpiryTime() const { return mExpiryTime; }
87 void SetExpiryTime(uint32_t aExpiryTime) {
88 mExpiryTime = aExpiryTime;
89 Touch();
92 bool GetMustValidate() const { return mMustValidate; }
93 void SetMustValidate(bool aValidate) {
94 mMustValidate = aValidate;
95 Touch();
98 already_AddRefed<imgRequest> GetRequest() const {
99 RefPtr<imgRequest> req = mRequest;
100 return req.forget();
103 bool Evicted() const { return mEvicted; }
105 nsExpirationState* GetExpirationState() { return &mExpirationState; }
107 bool HasNoProxies() const { return mHasNoProxies; }
109 bool ForcePrincipalCheck() const { return mForcePrincipalCheck; }
111 imgLoader* Loader() const { return mLoader; }
113 private: // methods
114 friend class imgLoader;
115 friend class imgCacheQueue;
116 void Touch(bool updateTime = true);
117 void UpdateCache(int32_t diff = 0);
118 void SetEvicted(bool evict) { mEvicted = evict; }
119 void SetHasNoProxies(bool hasNoProxies);
121 // Private, unimplemented copy constructor.
122 imgCacheEntry(const imgCacheEntry&);
124 private: // data
125 nsAutoRefCnt mRefCnt;
126 NS_DECL_OWNINGTHREAD
128 imgLoader* mLoader;
129 RefPtr<imgRequest> mRequest;
130 uint32_t mDataSize;
131 int32_t mTouchedTime;
132 uint32_t mLoadTime;
133 uint32_t mExpiryTime;
134 nsExpirationState mExpirationState;
135 bool mMustValidate : 1;
136 bool mEvicted : 1;
137 bool mHasNoProxies : 1;
138 bool mForcePrincipalCheck : 1;
141 #include <vector>
143 #define NS_IMGLOADER_CID \
144 { /* c1354898-e3fe-4602-88a7-c4520c21cb4e */ \
145 0xc1354898, 0xe3fe, 0x4602, { \
146 0x88, 0xa7, 0xc4, 0x52, 0x0c, 0x21, 0xcb, 0x4e \
150 class imgCacheQueue {
151 public:
152 imgCacheQueue();
153 void Remove(imgCacheEntry*);
154 void Push(imgCacheEntry*);
155 void MarkDirty();
156 bool IsDirty();
157 already_AddRefed<imgCacheEntry> Pop();
158 void Refresh();
159 uint32_t GetSize() const;
160 void UpdateSize(int32_t diff);
161 uint32_t GetNumElements() const;
162 bool Contains(imgCacheEntry* aEntry) const;
163 typedef nsTArray<RefPtr<imgCacheEntry>> queueContainer;
164 typedef queueContainer::iterator iterator;
165 typedef queueContainer::const_iterator const_iterator;
167 iterator begin();
168 const_iterator begin() const;
169 iterator end();
170 const_iterator end() const;
172 private:
173 queueContainer mQueue;
174 bool mDirty;
175 uint32_t mSize;
178 enum class AcceptedMimeTypes : uint8_t {
179 IMAGES,
180 IMAGES_AND_DOCUMENTS,
183 class imgLoader final : public imgILoader,
184 public nsIContentSniffer,
185 public imgICache,
186 public nsSupportsWeakReference,
187 public nsIObserver {
188 virtual ~imgLoader();
190 public:
191 using ImageCacheKey = mozilla::image::ImageCacheKey;
192 using imgCacheTable =
193 nsRefPtrHashtable<nsGenericHashKey<ImageCacheKey>, imgCacheEntry>;
194 using imgSet = nsTHashSet<imgRequest*>;
195 using Mutex = mozilla::Mutex;
197 NS_DECL_ISUPPORTS
198 NS_DECL_IMGILOADER
199 NS_DECL_NSICONTENTSNIFFER
200 NS_DECL_IMGICACHE
201 NS_DECL_NSIOBSERVER
204 * Get the normal image loader instance that is used by gecko code, creating
205 * it if necessary.
207 static imgLoader* NormalLoader();
210 * Get the Private Browsing image loader instance that is used by gecko code,
211 * creating it if necessary.
213 static imgLoader* PrivateBrowsingLoader();
216 * Gecko code should use NormalLoader() or PrivateBrowsingLoader() to get the
217 * appropriate image loader.
219 * This constructor is public because the XPCOM module code that creates
220 * instances of "@mozilla.org/image/loader;1" / "@mozilla.org/image/cache;1"
221 * for nsIComponentManager.createInstance()/nsIServiceManager.getService()
222 * calls (now only made by add-ons) needs access to it.
224 * XXX We would like to get rid of the nsIServiceManager.getService (and
225 * nsIComponentManager.createInstance) method of creating imgLoader objects,
226 * but there are add-ons that are still using it. These add-ons don't
227 * actually do anything useful with the loaders that they create since nobody
228 * who creates an imgLoader using this method actually QIs to imgILoader and
229 * loads images. They all just QI to imgICache and either call clearCache()
230 * or findEntryProperties(). Since they're doing this on an imgLoader that
231 * has never loaded images, these calls are useless. It seems likely that
232 * the code that is doing this is just legacy code left over from a time when
233 * there was only one imgLoader instance for the entire process. (Nowadays
234 * the correct method to get an imgILoader/imgICache is to call
235 * imgITools::getImgCacheForDocument/imgITools::getImgLoaderForDocument.)
236 * All the same, even though what these add-ons are doing is a no-op,
237 * removing the nsIServiceManager.getService method of creating/getting an
238 * imgLoader objects would cause an exception in these add-ons that could
239 * break things.
241 imgLoader();
242 nsresult Init();
244 bool IsImageAvailable(nsIURI*, nsIPrincipal* aTriggeringPrincipal,
245 mozilla::CORSMode, mozilla::dom::Document*);
247 [[nodiscard]] nsresult LoadImage(
248 nsIURI* aURI, nsIURI* aInitialDocumentURI, nsIReferrerInfo* aReferrerInfo,
249 nsIPrincipal* aLoadingPrincipal, uint64_t aRequestContextID,
250 nsILoadGroup* aLoadGroup, imgINotificationObserver* aObserver,
251 nsINode* aContext, mozilla::dom::Document* aLoadingDocument,
252 nsLoadFlags aLoadFlags, nsISupports* aCacheKey,
253 nsContentPolicyType aContentPolicyType, const nsAString& initiatorType,
254 bool aUseUrgentStartForChannel, bool aLinkPreload,
255 imgRequestProxy** _retval);
257 [[nodiscard]] nsresult LoadImageWithChannel(
258 nsIChannel* channel, imgINotificationObserver* aObserver,
259 mozilla::dom::Document* aLoadingDocument, nsIStreamListener** listener,
260 imgRequestProxy** _retval);
262 static nsresult GetMimeTypeFromContent(const char* aContents,
263 uint32_t aLength,
264 nsACString& aContentType);
267 * Returns true if the given mime type may be interpreted as an image.
269 * Some MIME types may be interpreted as both images and documents. (At the
270 * moment only "image/svg+xml" falls into this category, but there may be more
271 * in the future.) Callers which want this function to return true for such
272 * MIME types should pass AcceptedMimeTypes::IMAGES_AND_DOCUMENTS for
273 * @aAccept.
275 * @param aMimeType The MIME type to evaluate.
276 * @param aAcceptedMimeTypes Which kinds of MIME types to treat as images.
278 static bool SupportImageWithMimeType(
279 const nsACString&, AcceptedMimeTypes aAccept = AcceptedMimeTypes::IMAGES);
281 static void GlobalInit(); // for use by the factory
282 static void Shutdown(); // for use by the factory
283 static void ShutdownMemoryReporter();
285 nsresult ClearChromeImageCache();
286 nsresult ClearImageCache();
287 void MinimizeCaches();
289 nsresult InitCache();
291 bool RemoveFromCache(const ImageCacheKey& aKey);
293 // Enumeration describing if a given entry is in the cache queue or not.
294 // There are some cases we know the entry is definitely not in the queue.
295 enum class QueueState { MaybeExists, AlreadyRemoved };
297 bool RemoveFromCache(imgCacheEntry* entry,
298 QueueState aQueueState = QueueState::MaybeExists);
300 bool PutIntoCache(const ImageCacheKey& aKey, imgCacheEntry* aEntry);
302 void AddToUncachedImages(imgRequest* aRequest);
303 void RemoveFromUncachedImages(imgRequest* aRequest);
305 // Returns true if we should prefer evicting cache entry |two| over cache
306 // entry |one|.
307 // This mixes units in the worst way, but provides reasonable results.
308 inline static bool CompareCacheEntries(const RefPtr<imgCacheEntry>& one,
309 const RefPtr<imgCacheEntry>& two) {
310 if (!one) {
311 return false;
313 if (!two) {
314 return true;
317 const double sizeweight = 1.0 - sCacheTimeWeight;
319 // We want large, old images to be evicted first (depending on their
320 // relative weights). Since a larger time is actually newer, we subtract
321 // time's weight, so an older image has a larger weight.
322 double oneweight = double(one->GetDataSize()) * sizeweight -
323 double(one->GetTouchedTime()) * sCacheTimeWeight;
324 double twoweight = double(two->GetDataSize()) * sizeweight -
325 double(two->GetTouchedTime()) * sCacheTimeWeight;
327 return oneweight < twoweight;
330 void VerifyCacheSizes();
332 nsresult RemoveEntriesInternal(nsIPrincipal* aPrincipal,
333 const nsACString* aBaseDomain);
335 // The image loader maintains a hash table of all imgCacheEntries. However,
336 // only some of them will be evicted from the cache: those who have no
337 // imgRequestProxies watching their imgRequests.
339 // Once an imgRequest has no imgRequestProxies, it should notify us by
340 // calling HasNoObservers(), and null out its cache entry pointer.
342 // Upon having a proxy start observing again, it should notify us by calling
343 // HasObservers(). The request's cache entry will be re-set before this
344 // happens, by calling imgRequest::SetCacheEntry() when an entry with no
345 // observers is re-requested.
346 bool SetHasNoProxies(imgRequest* aRequest, imgCacheEntry* aEntry);
347 bool SetHasProxies(imgRequest* aRequest);
349 private: // methods
350 static already_AddRefed<imgLoader> CreateImageLoader();
352 bool ValidateEntry(
353 imgCacheEntry* aEntry, nsIURI* aURI, nsIURI* aInitialDocumentURI,
354 nsIReferrerInfo* aReferrerInfo, nsILoadGroup* aLoadGroup,
355 imgINotificationObserver* aObserver,
356 mozilla::dom::Document* aLoadingDocument, nsLoadFlags aLoadFlags,
357 nsContentPolicyType aLoadPolicyType, bool aCanMakeNewChannel,
358 bool* aNewChannelCreated, imgRequestProxy** aProxyRequest,
359 nsIPrincipal* aTriggeringPrincipal, mozilla::CORSMode, bool aLinkPreload);
361 bool ValidateRequestWithNewChannel(
362 imgRequest* request, nsIURI* aURI, nsIURI* aInitialDocumentURI,
363 nsIReferrerInfo* aReferrerInfo, nsILoadGroup* aLoadGroup,
364 imgINotificationObserver* aObserver,
365 mozilla::dom::Document* aLoadingDocument, uint64_t aInnerWindowId,
366 nsLoadFlags aLoadFlags, nsContentPolicyType aContentPolicyType,
367 imgRequestProxy** aProxyRequest, nsIPrincipal* aLoadingPrincipal,
368 mozilla::CORSMode, bool aLinkPreload, bool* aNewChannelCreated);
370 void NotifyObserversForCachedImage(imgCacheEntry* aEntry, imgRequest* request,
371 nsIURI* aURI,
372 nsIReferrerInfo* aReferrerInfo,
373 mozilla::dom::Document* aLoadingDocument,
374 nsIPrincipal* aLoadingPrincipal,
375 mozilla::CORSMode);
376 // aURI may be different from imgRequest's URI in the case of blob URIs, as we
377 // can share requests with different URIs.
378 nsresult CreateNewProxyForRequest(imgRequest* aRequest, nsIURI* aURI,
379 nsILoadGroup* aLoadGroup,
380 mozilla::dom::Document* aLoadingDocument,
381 imgINotificationObserver* aObserver,
382 nsLoadFlags aLoadFlags,
383 imgRequestProxy** _retval);
385 nsresult EvictEntries(imgCacheTable& aCacheToClear);
386 nsresult EvictEntries(imgCacheQueue& aQueueToClear);
388 imgCacheTable& GetCache(bool aForChrome);
389 imgCacheTable& GetCache(const ImageCacheKey& aKey);
390 imgCacheQueue& GetCacheQueue(bool aForChrome);
391 imgCacheQueue& GetCacheQueue(const ImageCacheKey& aKey);
392 void CacheEntriesChanged(bool aForChrome, int32_t aSizeDiff = 0);
393 void CheckCacheLimits(imgCacheTable& cache, imgCacheQueue& queue);
395 private: // data
396 friend class imgCacheEntry;
397 friend class imgMemoryReporter;
399 imgCacheTable mCache;
400 imgCacheQueue mCacheQueue;
402 imgCacheTable mChromeCache;
403 imgCacheQueue mChromeCacheQueue;
405 // Hash set of every imgRequest for this loader that isn't in mCache or
406 // mChromeCache. The union over all imgLoader's of mCache, mChromeCache, and
407 // mUncachedImages should be every imgRequest that is alive. These are weak
408 // pointers so we rely on the imgRequest destructor to remove itself.
409 imgSet mUncachedImages;
410 // The imgRequest can have refs to them held on non-main thread, so we need
411 // a mutex because we modify the uncached images set from the imgRequest
412 // destructor.
413 Mutex mUncachedImagesMutex;
415 static double sCacheTimeWeight;
416 static uint32_t sCacheMaxSize;
417 static imgMemoryReporter* sMemReporter;
419 mozilla::UniquePtr<imgCacheExpirationTracker> mCacheTracker;
420 bool mRespectPrivacy;
424 * proxy stream listener class used to handle multipart/x-mixed-replace
427 #include "nsCOMPtr.h"
428 #include "nsIStreamListener.h"
429 #include "nsIThreadRetargetableStreamListener.h"
431 class ProxyListener : public nsIStreamListener,
432 public nsIThreadRetargetableStreamListener {
433 public:
434 explicit ProxyListener(nsIStreamListener* dest);
436 /* additional members */
437 NS_DECL_THREADSAFE_ISUPPORTS
438 NS_DECL_NSISTREAMLISTENER
439 NS_DECL_NSITHREADRETARGETABLESTREAMLISTENER
440 NS_DECL_NSIREQUESTOBSERVER
442 private:
443 virtual ~ProxyListener();
445 nsCOMPtr<nsIStreamListener> mDestListener;
449 * A class that implements nsIProgressEventSink and forwards all calls to it to
450 * the original notification callbacks of the channel. Also implements
451 * nsIInterfaceRequestor and gives out itself for nsIProgressEventSink calls,
452 * and forwards everything else to the channel's notification callbacks.
454 class nsProgressNotificationProxy final : public nsIProgressEventSink,
455 public nsIChannelEventSink,
456 public nsIInterfaceRequestor {
457 public:
458 nsProgressNotificationProxy(nsIChannel* channel, imgIRequest* proxy)
459 : mImageRequest(proxy) {
460 channel->GetNotificationCallbacks(getter_AddRefs(mOriginalCallbacks));
463 NS_DECL_ISUPPORTS
464 NS_DECL_NSIPROGRESSEVENTSINK
465 NS_DECL_NSICHANNELEVENTSINK
466 NS_DECL_NSIINTERFACEREQUESTOR
467 private:
468 ~nsProgressNotificationProxy() = default;
470 nsCOMPtr<nsIInterfaceRequestor> mOriginalCallbacks;
471 nsCOMPtr<nsIRequest> mImageRequest;
475 * validate checker
478 #include "nsCOMArray.h"
480 class imgCacheValidator : public nsIStreamListener,
481 public nsIThreadRetargetableStreamListener,
482 public nsIChannelEventSink,
483 public nsIInterfaceRequestor,
484 public nsIAsyncVerifyRedirectCallback {
485 public:
486 imgCacheValidator(nsProgressNotificationProxy* progress, imgLoader* loader,
487 imgRequest* aRequest, mozilla::dom::Document* aDocument,
488 uint64_t aInnerWindowId,
489 bool forcePrincipalCheckForCacheEntry);
491 void AddProxy(imgRequestProxy* aProxy);
492 void RemoveProxy(imgRequestProxy* aProxy);
494 NS_DECL_THREADSAFE_ISUPPORTS
495 NS_DECL_NSITHREADRETARGETABLESTREAMLISTENER
496 NS_DECL_NSISTREAMLISTENER
497 NS_DECL_NSIREQUESTOBSERVER
498 NS_DECL_NSICHANNELEVENTSINK
499 NS_DECL_NSIINTERFACEREQUESTOR
500 NS_DECL_NSIASYNCVERIFYREDIRECTCALLBACK
502 private:
503 void UpdateProxies(bool aCancelRequest, bool aSyncNotify);
504 virtual ~imgCacheValidator();
506 nsCOMPtr<nsIStreamListener> mDestListener;
507 RefPtr<nsProgressNotificationProxy> mProgressProxy;
508 nsCOMPtr<nsIAsyncVerifyRedirectCallback> mRedirectCallback;
509 nsCOMPtr<nsIChannel> mRedirectChannel;
511 RefPtr<imgRequest> mRequest;
512 AutoTArray<RefPtr<imgRequestProxy>, 4> mProxies;
514 RefPtr<imgRequest> mNewRequest;
515 RefPtr<imgCacheEntry> mNewEntry;
517 RefPtr<mozilla::dom::Document> mDocument;
518 uint64_t mInnerWindowId;
520 imgLoader* mImgLoader;
522 bool mHadInsecureRedirect;
525 #endif // mozilla_image_imgLoader_h