forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 1
/
imgLoader.cpp
3207 lines (2705 loc) · 113 KB
/
imgLoader.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- 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"
#undef LoadImage
#include "imgLoader.h"
#include <algorithm>
#include <utility>
#include "DecoderFactory.h"
#include "Image.h"
#include "ImageLogging.h"
#include "ReferrerInfo.h"
#include "imgRequestProxy.h"
#include "mozilla/Attributes.h"
#include "mozilla/BasePrincipal.h"
#include "mozilla/ChaosMode.h"
#include "mozilla/ClearOnShutdown.h"
#include "mozilla/LoadInfo.h"
#include "mozilla/NullPrincipal.h"
#include "mozilla/Preferences.h"
#include "mozilla/StaticPrefs_image.h"
#include "mozilla/StaticPrefs_network.h"
#include "mozilla/dom/ContentParent.h"
#include "mozilla/dom/nsMixedContentBlocker.h"
#include "mozilla/image/ImageMemoryReporter.h"
#include "mozilla/layers/CompositorManagerChild.h"
#include "nsCOMPtr.h"
#include "nsCRT.h"
#include "nsContentPolicyUtils.h"
#include "nsContentUtils.h"
#include "nsIApplicationCache.h"
#include "nsIApplicationCacheContainer.h"
#include "nsIAsyncVerifyRedirectCallback.h"
#include "nsICacheInfoChannel.h"
#include "nsIChannelEventSink.h"
#include "nsIClassOfService.h"
#include "nsIFile.h"
#include "nsIFileURL.h"
#include "nsIHttpChannel.h"
#include "nsIInterfaceRequestor.h"
#include "nsIInterfaceRequestorUtils.h"
#include "nsIMemoryReporter.h"
#include "nsINetworkPredictor.h"
#include "nsIProgressEventSink.h"
#include "nsIProtocolHandler.h"
#include "nsImageModule.h"
#include "nsMediaSniffer.h"
#include "nsMimeTypes.h"
#include "nsNetCID.h"
#include "nsNetUtil.h"
#include "nsQueryObject.h"
#include "nsReadableUtils.h"
#include "nsStreamUtils.h"
#include "prtime.h"
// 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"
using namespace mozilla;
using namespace mozilla::dom;
using namespace mozilla::image;
using namespace mozilla::net;
MOZ_DEFINE_MALLOC_SIZE_OF(ImagesMallocSizeOf)
class imgMemoryReporter final : public nsIMemoryReporter {
~imgMemoryReporter() = default;
public:
NS_DECL_ISUPPORTS
NS_IMETHOD CollectReports(nsIHandleReportCallback* aHandleReport,
nsISupports* aData, bool aAnonymize) override {
MOZ_ASSERT(NS_IsMainThread());
layers::CompositorManagerChild* manager =
mozilla::layers::CompositorManagerChild::GetInstance();
if (!manager || !StaticPrefs::image_mem_debug_reporting()) {
layers::SharedSurfacesMemoryReport sharedSurfaces;
FinishCollectReports(aHandleReport, aData, aAnonymize, sharedSurfaces);
return NS_OK;
}
RefPtr<imgMemoryReporter> self(this);
nsCOMPtr<nsIHandleReportCallback> handleReport(aHandleReport);
nsCOMPtr<nsISupports> data(aData);
manager->SendReportSharedSurfacesMemory(
[=](layers::SharedSurfacesMemoryReport aReport) {
self->FinishCollectReports(handleReport, data, aAnonymize, aReport);
},
[=](mozilla::ipc::ResponseRejectReason&& aReason) {
layers::SharedSurfacesMemoryReport sharedSurfaces;
self->FinishCollectReports(handleReport, data, aAnonymize,
sharedSurfaces);
});
return NS_OK;
}
void FinishCollectReports(
nsIHandleReportCallback* aHandleReport, nsISupports* aData,
bool aAnonymize, layers::SharedSurfacesMemoryReport& aSharedSurfaces) {
nsTArray<ImageMemoryCounter> chrome;
nsTArray<ImageMemoryCounter> content;
nsTArray<ImageMemoryCounter> uncached;
for (uint32_t i = 0; i < mKnownLoaders.Length(); i++) {
for (auto iter = mKnownLoaders[i]->mChromeCache.Iter(); !iter.Done();
iter.Next()) {
imgCacheEntry* entry = iter.UserData();
RefPtr<imgRequest> req = entry->GetRequest();
RecordCounterForRequest(req, &chrome, !entry->HasNoProxies());
}
for (auto iter = mKnownLoaders[i]->mCache.Iter(); !iter.Done();
iter.Next()) {
imgCacheEntry* entry = iter.UserData();
RefPtr<imgRequest> req = entry->GetRequest();
RecordCounterForRequest(req, &content, !entry->HasNoProxies());
}
MutexAutoLock lock(mKnownLoaders[i]->mUncachedImagesMutex);
for (auto iter = mKnownLoaders[i]->mUncachedImages.Iter(); !iter.Done();
iter.Next()) {
nsPtrHashKey<imgRequest>* entry = iter.Get();
RefPtr<imgRequest> req = entry->GetKey();
RecordCounterForRequest(req, &uncached, req->HasConsumers());
}
}
// Note that we only need to anonymize content image URIs.
ReportCounterArray(aHandleReport, aData, chrome, "images/chrome",
/* aAnonymize */ false, aSharedSurfaces);
ReportCounterArray(aHandleReport, aData, content, "images/content",
aAnonymize, aSharedSurfaces);
// 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 (auto iter = imgLoader::sMemReporter->mKnownLoaders[i]->mCache.Iter();
!iter.Done(); iter.Next()) {
imgCacheEntry* entry = iter.UserData();
if (entry->HasNoProxies()) {
continue;
}
RefPtr<imgRequest> req = entry->GetRequest();
RefPtr<image::Image> image = req->GetImage();
if (!image) {
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;
}
void RegisterLoader(imgLoader* aLoader) {
mKnownLoaders.AppendElement(aLoader);
}
void UnregisterLoader(imgLoader* aLoader) {
mKnownLoaders.RemoveElement(aLoader);
}
private:
nsTArray<imgLoader*> mKnownLoaders;
struct MemoryTotal {
MemoryTotal& operator+=(const ImageMemoryCounter& aImageCounter) {
if (aImageCounter.Type() == imgIContainer::TYPE_RASTER) {
if (aImageCounter.IsUsed()) {
mUsedRasterCounter += aImageCounter.Values();
} else {
mUnusedRasterCounter += aImageCounter.Values();
}
} else if (aImageCounter.Type() == imgIContainer::TYPE_VECTOR) {
if (aImageCounter.IsUsed()) {
mUsedVectorCounter += aImageCounter.Values();
} else {
mUnusedVectorCounter += aImageCounter.Values();
}
} else if (aImageCounter.Type() == imgIContainer::TYPE_REQUEST) {
// Nothing to do, we did not get to the point of having an image.
} else {
MOZ_CRASH("Unexpected image type");
}
return *this;
}
const MemoryCounter& UsedRaster() const { return mUsedRasterCounter; }
const MemoryCounter& UnusedRaster() const { return mUnusedRasterCounter; }
const MemoryCounter& UsedVector() const { return mUsedVectorCounter; }
const MemoryCounter& UnusedVector() const { return mUnusedVectorCounter; }
private:
MemoryCounter mUsedRasterCounter;
MemoryCounter mUnusedRasterCounter;
MemoryCounter mUsedVectorCounter;
MemoryCounter mUnusedVectorCounter;
};
// Reports all images of a single kind, e.g. all used chrome images.
void ReportCounterArray(nsIHandleReportCallback* aHandleReport,
nsISupports* aData,
nsTArray<ImageMemoryCounter>& aCounterArray,
const char* 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("<anonymized-%u>", i);
} else {
// The URI could be an extremely long data: URI. Truncate if needed.
static const size_t max = 256;
if (counter.URI().Length() > max) {
counter.URI().Truncate(max);
counter.URI().AppendLiteral(" (truncated)");
}
counter.URI().ReplaceChar('/', '\\');
}
summaryTotal += counter;
if (counter.IsNotable() || StaticPrefs::image_mem_debug_reporting()) {
ReportImage(aHandleReport, aData, aPathPrefix, counter,
aSharedSurfaces);
} else {
ImageMemoryReporter::TrimSharedSurfaces(counter, aSharedSurfaces);
nonNotableTotal += counter;
}
}
// Report non-notable images in aggregate.
ReportTotal(aHandleReport, aData, /* aExplicit = */ true, aPathPrefix,
"<non-notable images>/", nonNotableTotal);
// Report a summary in aggregate, outside of the explicit tree.
ReportTotal(aHandleReport, aData, /* aExplicit = */ false, aPathPrefix, "",
summaryTotal);
}
static void ReportImage(nsIHandleReportCallback* aHandleReport,
nsISupports* aData, const char* aPathPrefix,
const ImageMemoryCounter& aCounter,
layers::SharedSurfacesMemoryReport& aSharedSurfaces) {
nsAutoCString pathPrefix("explicit/"_ns);
pathPrefix.Append(aPathPrefix);
switch (aCounter.Type()) {
case imgIContainer::TYPE_RASTER:
pathPrefix.AppendLiteral("/raster/");
break;
case imgIContainer::TYPE_VECTOR:
pathPrefix.AppendLiteral("/vector/");
break;
case imgIContainer::TYPE_REQUEST:
pathPrefix.AppendLiteral("/request/");
break;
default:
pathPrefix.AppendLiteral("/unknown=");
pathPrefix.AppendInt(aCounter.Type());
pathPrefix.AppendLiteral("/");
break;
}
pathPrefix.Append(aCounter.IsUsed() ? "used/" : "unused/");
if (aCounter.IsValidating()) {
pathPrefix.AppendLiteral("validating/");
}
if (aCounter.HasError()) {
pathPrefix.AppendLiteral("err/");
}
pathPrefix.AppendLiteral("progress=");
pathPrefix.AppendInt(aCounter.Progress(), 16);
pathPrefix.AppendLiteral("/");
pathPrefix.AppendLiteral("image(");
pathPrefix.AppendInt(aCounter.IntrinsicSize().width);
pathPrefix.AppendLiteral("x");
pathPrefix.AppendInt(aCounter.IntrinsicSize().height);
pathPrefix.AppendLiteral(", ");
if (aCounter.URI().IsEmpty()) {
pathPrefix.AppendLiteral("<unknown URI>");
} else {
pathPrefix.Append(aCounter.URI());
}
pathPrefix.AppendLiteral(")/");
ReportSurfaces(aHandleReport, aData, pathPrefix, aCounter, aSharedSurfaces);
ReportSourceValue(aHandleReport, aData, pathPrefix, aCounter.Values());
}
static void ReportSurfaces(
nsIHandleReportCallback* aHandleReport, nsISupports* aData,
const nsACString& aPathPrefix, const ImageMemoryCounter& aCounter,
layers::SharedSurfacesMemoryReport& aSharedSurfaces) {
for (const SurfaceMemoryCounter& counter : aCounter.Surfaces()) {
nsAutoCString surfacePathPrefix(aPathPrefix);
if (counter.IsLocked()) {
surfacePathPrefix.AppendLiteral("locked/");
} else {
surfacePathPrefix.AppendLiteral("unlocked/");
}
if (counter.IsFactor2()) {
surfacePathPrefix.AppendLiteral("factor2/");
}
if (counter.CannotSubstitute()) {
surfacePathPrefix.AppendLiteral("cannot_substitute/");
}
surfacePathPrefix.AppendLiteral("types=");
surfacePathPrefix.AppendInt(counter.Values().SurfaceTypes(), 16);
surfacePathPrefix.AppendLiteral("/surface(");
surfacePathPrefix.AppendInt(counter.Key().Size().width);
surfacePathPrefix.AppendLiteral("x");
surfacePathPrefix.AppendInt(counter.Key().Size().height);
if (!counter.IsFinished()) {
surfacePathPrefix.AppendLiteral(", incomplete");
}
if (counter.Values().ExternalHandles() > 0) {
surfacePathPrefix.AppendLiteral(", handles:");
surfacePathPrefix.AppendInt(
uint32_t(counter.Values().ExternalHandles()));
}
ImageMemoryReporter::AppendSharedSurfacePrefix(surfacePathPrefix, counter,
aSharedSurfaces);
if (counter.Type() == SurfaceMemoryCounterType::NORMAL) {
PlaybackType playback = counter.Key().Playback();
if (playback == PlaybackType::eAnimated) {
if (StaticPrefs::image_mem_debug_reporting()) {
surfacePathPrefix.AppendPrintf(
" (animation %4u)", uint32_t(counter.Values().FrameIndex()));
} else {
surfacePathPrefix.AppendLiteral(" (animation)");
}
}
if (counter.Key().Flags() != DefaultSurfaceFlags()) {
surfacePathPrefix.AppendLiteral(", flags:");
surfacePathPrefix.AppendInt(uint32_t(counter.Key().Flags()),
/* aRadix = */ 16);
}
if (counter.Key().SVGContext()) {
const SVGImageContext& context = counter.Key().SVGContext().ref();
surfacePathPrefix.AppendLiteral(", svgContext:[ ");
if (context.GetViewportSize()) {
const CSSIntSize& size = context.GetViewportSize().ref();
surfacePathPrefix.AppendLiteral("viewport=(");
surfacePathPrefix.AppendInt(size.width);
surfacePathPrefix.AppendLiteral("x");
surfacePathPrefix.AppendInt(size.height);
surfacePathPrefix.AppendLiteral(") ");
}
if (context.GetPreserveAspectRatio()) {
nsAutoString aspect;
context.GetPreserveAspectRatio()->ToString(aspect);
surfacePathPrefix.AppendLiteral("preserveAspectRatio=(");
LossyAppendUTF16toASCII(aspect, surfacePathPrefix);
surfacePathPrefix.AppendLiteral(") ");
}
if (context.GetContextPaint()) {
const SVGEmbeddingContextPaint* paint = context.GetContextPaint();
surfacePathPrefix.AppendLiteral("contextPaint=(");
if (paint->GetFill()) {
surfacePathPrefix.AppendLiteral(" fill=");
surfacePathPrefix.AppendInt(paint->GetFill()->ToABGR(), 16);
}
if (paint->GetFillOpacity()) {
surfacePathPrefix.AppendLiteral(" fillOpa=");
surfacePathPrefix.AppendFloat(paint->GetFillOpacity());
}
if (paint->GetStroke()) {
surfacePathPrefix.AppendLiteral(" stroke=");
surfacePathPrefix.AppendInt(paint->GetStroke()->ToABGR(), 16);
}
if (paint->GetStrokeOpacity()) {
surfacePathPrefix.AppendLiteral(" strokeOpa=");
surfacePathPrefix.AppendFloat(paint->GetStrokeOpacity());
}
surfacePathPrefix.AppendLiteral(" ) ");
}
surfacePathPrefix.AppendLiteral("]");
}
} else if (counter.Type() == SurfaceMemoryCounterType::COMPOSITING) {
surfacePathPrefix.AppendLiteral(", compositing frame");
} else if (counter.Type() == SurfaceMemoryCounterType::COMPOSITING_PREV) {
surfacePathPrefix.AppendLiteral(", compositing prev frame");
} else {
MOZ_ASSERT_UNREACHABLE("Unknown counter type");
}
surfacePathPrefix.AppendLiteral(")/");
ReportValues(aHandleReport, aData, surfacePathPrefix, counter.Values());
}
}
static void ReportTotal(nsIHandleReportCallback* aHandleReport,
nsISupports* aData, bool aExplicit,
const char* aPathPrefix, const char* aPathInfix,
const MemoryTotal& aTotal) {
nsAutoCString pathPrefix;
if (aExplicit) {
pathPrefix.AppendLiteral("explicit/");
}
pathPrefix.Append(aPathPrefix);
nsAutoCString rasterUsedPrefix(pathPrefix);
rasterUsedPrefix.AppendLiteral("/raster/used/");
rasterUsedPrefix.Append(aPathInfix);
ReportValues(aHandleReport, aData, rasterUsedPrefix, aTotal.UsedRaster());
nsAutoCString rasterUnusedPrefix(pathPrefix);
rasterUnusedPrefix.AppendLiteral("/raster/unused/");
rasterUnusedPrefix.Append(aPathInfix);
ReportValues(aHandleReport, aData, rasterUnusedPrefix,
aTotal.UnusedRaster());
nsAutoCString vectorUsedPrefix(pathPrefix);
vectorUsedPrefix.AppendLiteral("/vector/used/");
vectorUsedPrefix.Append(aPathInfix);
ReportValues(aHandleReport, aData, vectorUsedPrefix, aTotal.UsedVector());
nsAutoCString vectorUnusedPrefix(pathPrefix);
vectorUnusedPrefix.AppendLiteral("/vector/unused/");
vectorUnusedPrefix.Append(aPathInfix);
ReportValues(aHandleReport, aData, vectorUnusedPrefix,
aTotal.UnusedVector());
}
static void ReportValues(nsIHandleReportCallback* aHandleReport,
nsISupports* aData, const nsACString& aPathPrefix,
const MemoryCounter& aCounter) {
ReportSourceValue(aHandleReport, aData, aPathPrefix, aCounter);
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());
}
static void ReportSourceValue(nsIHandleReportCallback* aHandleReport,
nsISupports* aData,
const nsACString& aPathPrefix,
const MemoryCounter& aCounter) {
ReportValue(aHandleReport, aData, KIND_HEAP, aPathPrefix, "source",
"Raster image source data and vector image documents.",
aCounter.Source());
}
static void ReportValue(nsIHandleReportCallback* aHandleReport,
nsISupports* aData, int32_t aKind,
const nsACString& aPathPrefix,
const char* aPathSuffix, const char* aDescription,
size_t aValue) {
if (aValue == 0) {
return;
}
nsAutoCString desc(aDescription);
nsAutoCString path(aPathPrefix);
path.Append(aPathSuffix);
aHandleReport->Callback(EmptyCString(), path, aKind, UNITS_BYTES, aValue,
desc, aData);
}
static void 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));
}
}
};
NS_IMPL_ISUPPORTS(imgMemoryReporter, nsIMemoryReporter)
NS_IMPL_ISUPPORTS(nsProgressNotificationProxy, nsIProgressEventSink,
nsIChannelEventSink, nsIInterfaceRequestor)
NS_IMETHODIMP
nsProgressNotificationProxy::OnProgress(nsIRequest* request, int64_t progress,
int64_t progressMax) {
nsCOMPtr<nsILoadGroup> loadGroup;
request->GetLoadGroup(getter_AddRefs(loadGroup));
nsCOMPtr<nsIProgressEventSink> target;
NS_QueryNotificationCallbacks(mOriginalCallbacks, loadGroup,
NS_GET_IID(nsIProgressEventSink),
getter_AddRefs(target));
if (!target) {
return NS_OK;
}
return target->OnProgress(mImageRequest, progress, progressMax);
}
NS_IMETHODIMP
nsProgressNotificationProxy::OnStatus(nsIRequest* request, nsresult status,
const char16_t* statusArg) {
nsCOMPtr<nsILoadGroup> loadGroup;
request->GetLoadGroup(getter_AddRefs(loadGroup));
nsCOMPtr<nsIProgressEventSink> target;
NS_QueryNotificationCallbacks(mOriginalCallbacks, loadGroup,
NS_GET_IID(nsIProgressEventSink),
getter_AddRefs(target));
if (!target) {
return NS_OK;
}
return target->OnStatus(mImageRequest, status, statusArg);
}
NS_IMETHODIMP
nsProgressNotificationProxy::AsyncOnChannelRedirect(
nsIChannel* oldChannel, nsIChannel* newChannel, uint32_t flags,
nsIAsyncVerifyRedirectCallback* cb) {
// Tell the original original callbacks about it too
nsCOMPtr<nsILoadGroup> loadGroup;
newChannel->GetLoadGroup(getter_AddRefs(loadGroup));
nsCOMPtr<nsIChannelEventSink> target;
NS_QueryNotificationCallbacks(mOriginalCallbacks, loadGroup,
NS_GET_IID(nsIChannelEventSink),
getter_AddRefs(target));
if (!target) {
cb->OnRedirectVerifyCallback(NS_OK);
return NS_OK;
}
// Delegate to |target| if set, reusing |cb|
return target->AsyncOnChannelRedirect(oldChannel, newChannel, flags, cb);
}
NS_IMETHODIMP
nsProgressNotificationProxy::GetInterface(const nsIID& iid, void** result) {
if (iid.Equals(NS_GET_IID(nsIProgressEventSink))) {
*result = static_cast<nsIProgressEventSink*>(this);
NS_ADDREF_THIS();
return NS_OK;
}
if (iid.Equals(NS_GET_IID(nsIChannelEventSink))) {
*result = static_cast<nsIChannelEventSink*>(this);
NS_ADDREF_THIS();
return NS_OK;
}
if (mOriginalCallbacks) {
return mOriginalCallbacks->GetInterface(iid, result);
}
return NS_NOINTERFACE;
}
static void NewRequestAndEntry(bool aForcePrincipalCheckForCacheEntry,
imgLoader* aLoader, const ImageCacheKey& aKey,
imgRequest** aRequest, imgCacheEntry** aEntry) {
RefPtr<imgRequest> request = new imgRequest(aLoader, aKey);
RefPtr<imgCacheEntry> entry =
new imgCacheEntry(aLoader, request, aForcePrincipalCheckForCacheEntry);
aLoader->AddToUncachedImages(request);
request.forget(aRequest);
entry.forget(aEntry);
}
static bool ShouldRevalidateEntry(imgCacheEntry* aEntry, nsLoadFlags aFlags,
bool aHasExpired) {
bool bValidateEntry = false;
if (aFlags & nsIRequest::LOAD_BYPASS_CACHE) {
return false;
}
if (aFlags & nsIRequest::VALIDATE_ALWAYS) {
bValidateEntry = true;
} else if (aEntry->GetMustValidate()) {
bValidateEntry = true;
} else if (aHasExpired) {
// The cache entry has expired... Determine whether the stale cache
// entry can be used without validation...
if (aFlags &
(nsIRequest::VALIDATE_NEVER | nsIRequest::VALIDATE_ONCE_PER_SESSION)) {
// 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.
bValidateEntry = false;
} else if (!(aFlags & nsIRequest::LOAD_FROM_CACHE)) {
// LOAD_FROM_CACHE allows a stale cache entry to be used... Otherwise,
// the entry must be revalidated.
bValidateEntry = true;
}
}
return bValidateEntry;
}
/* Call content policies on cached images that went through a redirect */
static bool 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);
secCheckLoadInfo->SetSendCSPViolationEvents(aSendCSPViolationReports);
int16_t decision = nsIContentPolicy::REJECT_REQUEST;
rv = NS_CheckContentLoadPolicy(contentLocation, secCheckLoadInfo,
EmptyCString(), // mime guess
&decision, nsContentUtils::GetContentPolicy());
if (NS_FAILED(rv) || !NS_CP_ACCEPTED(decision)) {
return false;
}
// 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)) {
return false;
}
}
if (!aTriggeringPrincipal || !aTriggeringPrincipal->IsSystemPrincipal()) {
// reset the decision for mixed content blocker check
decision = nsIContentPolicy::REJECT_REQUEST;
rv = nsMixedContentBlocker::ShouldLoad(insecureRedirect, contentLocation,
secCheckLoadInfo,
EmptyCString(), // mime guess
true, // aReportError
&decision);
if (NS_FAILED(rv) || !NS_CP_ACCEPTED(decision)) {
return false;
}
}
}
return true;
}
// 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. Also checks the Referrer Policy, since requests with different
// referrers/policies may generate different responses.
static bool ValidateSecurityInfo(imgRequest* request, bool forcePrincipalCheck,
int32_t corsmode,
nsIPrincipal* triggeringPrincipal,
Document* aLoadingDocument,
nsContentPolicyType aPolicyType) {
// 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 (request->GetCORSMode() != corsmode) {
return false;
}
if (request->GetCORSMode() != imgIRequest::CORS_NONE || forcePrincipalCheck) {
nsCOMPtr<nsIPrincipal> otherprincipal = request->GetTriggeringPrincipal();
// If we previously had a principal, but we don't now, we can't use this
// request.
if (otherprincipal && !triggeringPrincipal) {
return false;
}
if (otherprincipal && triggeringPrincipal) {
bool equals = false;
otherprincipal->Equals(triggeringPrincipal, &equals);
if (!equals) {
return false;
}
}
}
// Content Policy Check on Cached Images
return ShouldLoadCachedImage(request, aLoadingDocument, triggeringPrincipal,
aPolicyType,
/* aSendCSPViolationReports */ false);
}
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, int32_t aCORSMode,
nsIReferrerInfo* aReferrerInfo, nsILoadGroup* aLoadGroup,
nsLoadFlags aLoadFlags, nsContentPolicyType aPolicyType,
nsIPrincipal* aTriggeringPrincipal, nsINode* aRequestingNode,
bool aRespectPrivacy) {
MOZ_ASSERT(aResult);
nsresult rv;
nsCOMPtr<nsIHttpChannel> newHttpChannel;
nsCOMPtr<nsIInterfaceRequestor> callbacks;
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.
//
nsSecurityFlags securityFlags =
aCORSMode == imgIRequest::CORS_NONE
? nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_INHERITS_SEC_CONTEXT
: nsILoadInfo::SEC_REQUIRE_CORS_INHERITS_SEC_CONTEXT;
if (aCORSMode == imgIRequest::CORS_ANONYMOUS) {
securityFlags |= nsILoadInfo::SEC_COOKIES_SAME_ORIGIN;
} else if (aCORSMode == imgIRequest::CORS_USE_CREDENTIALS) {
securityFlags |= nsILoadInfo::SEC_COOKIES_INCLUDE;
}
securityFlags |= nsILoadInfo::SEC_ALLOW_CHROME;
// 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;
nsCOMPtr<nsILoadInfo> loadInfo = (*aResult)->LoadInfo();
rv = loadInfo->SetOriginAttributes(attrs);
}
if (NS_FAILED(rv)) {
return rv;
}
// only inherit if we have a principal
*aForcePrincipalCheckForCacheEntry =
aTriggeringPrincipal && nsContentUtils::ChannelShouldInheritPrincipal(
aTriggeringPrincipal, aURI,
/* aInheritForAboutBlank */ false,
/* aForceInherit */ false);
// Initialize HTTP-specific attributes
newHttpChannel = do_QueryInterface(*aResult);
if (newHttpChannel) {
nsCOMPtr<nsIHttpChannelInternal> httpChannelInternal =
do_QueryInterface(newHttpChannel);
NS_ENSURE_TRUE(httpChannelInternal, NS_ERROR_UNEXPECTED);
rv = httpChannelInternal->SetDocumentURI(aInitialDocumentURI);
MOZ_ASSERT(NS_SUCCEEDED(rv));
if (aReferrerInfo) {
DebugOnly<nsresult> rv = newHttpChannel->SetReferrerInfo(aReferrerInfo);
MOZ_ASSERT(NS_SUCCEEDED(rv));
}
}
// Image channels are loaded by default with reduced priority.
nsCOMPtr<nsISupportsPriority> p = do_QueryInterface(*aResult);
if (p) {
uint32_t priority = nsISupportsPriority::PRIORITY_LOW;
if (aLoadFlags & nsIRequest::LOAD_BACKGROUND) {
++priority; // further reduce priority for background loads
}
p->AdjustPriority(priority);
}
// 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.
nsCOMPtr<nsILoadGroup> loadGroup = do_CreateInstance(NS_LOADGROUP_CONTRACTID);
nsCOMPtr<nsILoadGroupChild> childLoadGroup = do_QueryInterface(loadGroup);
if (childLoadGroup) {
childLoadGroup->SetParentLoadGroup(aLoadGroup);
}
(*aResult)->SetLoadGroup(loadGroup);
return NS_OK;
}
static uint32_t SecondsFromPRTime(PRTime aTime) {
return nsContentUtils::SecondsFromPRTime(aTime);
}
/* static */
imgCacheEntry::imgCacheEntry(imgLoader* loader, imgRequest* request,
bool forcePrincipalCheck)
: mLoader(loader),
mRequest(request),
mDataSize(0),
mTouchedTime(SecondsFromPRTime(PR_Now())),
mLoadTime(SecondsFromPRTime(PR_Now())),
mExpiryTime(0),
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) {}
imgCacheEntry::~imgCacheEntry() {
LOG_FUNC(gImgLog, "imgCacheEntry::~imgCacheEntry()");
}
void imgCacheEntry::Touch(bool updateTime /* = true */) {
LOG_SCOPE(gImgLog, "imgCacheEntry::Touch");
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(mRequest->IsChrome(), diff);
}
}
void imgCacheEntry::UpdateLoadTime() {
mLoadTime = SecondsFromPRTime(PR_Now());
}
void imgCacheEntry::SetHasNoProxies(bool hasNoProxies) {
if (MOZ_LOG_TEST(gImgLog, LogLevel::Debug)) {
if (hasNoProxies) {
LOG_FUNC_WITH_PARAM(gImgLog, "imgCacheEntry::SetHasNoProxies true", "uri",
mRequest->CacheKey().URI());
} else {
LOG_FUNC_WITH_PARAM(gImgLog, "imgCacheEntry::SetHasNoProxies false",
"uri", mRequest->CacheKey().URI());
}
}
mHasNoProxies = hasNoProxies;