-
Notifications
You must be signed in to change notification settings - Fork 54
/
gfxPlatform.cpp
3739 lines (3187 loc) · 128 KB
/
gfxPlatform.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: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* 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/. */
#include "mozilla/FontPropertyTypes.h"
#include "mozilla/RDDProcessManager.h"
#include "mozilla/image/ImageMemoryReporter.h"
#include "mozilla/layers/CompositorManagerChild.h"
#include "mozilla/layers/CompositorThread.h"
#include "mozilla/layers/ImageBridgeChild.h"
#include "mozilla/layers/ISurfaceAllocator.h" // for GfxMemoryImageReporter
#include "mozilla/layers/CompositorBridgeChild.h"
#include "mozilla/layers/TiledContentClient.h"
#include "mozilla/webrender/RenderThread.h"
#include "mozilla/webrender/WebRenderAPI.h"
#include "mozilla/webrender/webrender_ffi.h"
#include "mozilla/layers/PaintThread.h"
#include "mozilla/gfx/gfxVars.h"
#include "mozilla/gfx/GPUProcessManager.h"
#include "mozilla/gfx/GraphicsMessages.h"
#include "mozilla/ClearOnShutdown.h"
#include "mozilla/StaticPrefs_accessibility.h"
#include "mozilla/StaticPrefs_apz.h"
#include "mozilla/StaticPrefs_gfx.h"
#include "mozilla/StaticPrefs_layout.h"
#include "mozilla/StaticPrefs_layers.h"
#include "mozilla/StaticPrefs_media.h"
#include "mozilla/StaticPrefs_webgl.h"
#include "mozilla/Telemetry.h"
#include "mozilla/TimeStamp.h"
#include "mozilla/Unused.h"
#include "mozilla/IntegerPrintfMacros.h"
#include "mozilla/Base64.h"
#include "mozilla/Logging.h"
#include "mozilla/Services.h"
#include "nsAppDirectoryServiceDefs.h"
#include "gfxCrashReporterUtils.h"
#include "gfxPlatform.h"
#include "gfxEnv.h"
#include "gfxTextRun.h"
#include "gfxUserFontSet.h"
#include "gfxConfig.h"
#include "GfxDriverInfo.h"
#include "VRProcessManager.h"
#include "VRThread.h"
#include "mozilla/SSE.h"
#include "mozilla/arm.h"
#ifdef XP_WIN
# include <process.h>
# define getpid _getpid
#else
# include <unistd.h>
#endif
#include "nsXULAppAPI.h"
#include "nsDirectoryServiceUtils.h"
#include "nsDirectoryServiceDefs.h"
#if defined(XP_WIN)
# include "gfxWindowsPlatform.h"
# include "DisplayConfigWindows.h"
#elif defined(XP_MACOSX)
# include "gfxPlatformMac.h"
# include "gfxQuartzSurface.h"
# include "nsCocoaFeatures.h"
#elif defined(MOZ_WIDGET_GTK)
# include "gfxPlatformGtk.h"
#elif defined(ANDROID)
# include "gfxAndroidPlatform.h"
#endif
#if defined(MOZ_WIDGET_ANDROID)
# include "mozilla/jni/Utils.h" // for IsFennec
#endif
#ifdef XP_WIN
# include "mozilla/WindowsVersion.h"
# include "mozilla/gfx/DeviceManagerDx.h"
#endif
#ifdef MOZ_WAYLAND
# include "mozilla/widget/nsWaylandDisplay.h"
#endif
#include "nsGkAtoms.h"
#include "gfxPlatformFontList.h"
#include "gfxContext.h"
#include "gfxImageSurface.h"
#include "nsUnicodeProperties.h"
#include "harfbuzz/hb.h"
#include "gfxGraphiteShaper.h"
#include "gfx2DGlue.h"
#include "gfxGradientCache.h"
#include "gfxUtils.h" // for NextPowerOfTwo
#include "gfxFontMissingGlyphs.h"
#include "nsExceptionHandler.h"
#include "nsServiceManagerUtils.h"
#include "nsTArray.h"
#include "nsIObserverService.h"
#include "nsIScreenManager.h"
#include "MainThreadUtils.h"
#include "nsWeakReference.h"
#include "cairo.h"
#include "qcms.h"
#include "imgITools.h"
#include "plstr.h"
#include "nsCRT.h"
#include "GLContext.h"
#include "GLContextProvider.h"
#include "mozilla/gfx/Logging.h"
#ifdef USE_SKIA
# ifdef __GNUC__
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wshadow"
# endif
# include "skia/include/core/SkGraphics.h"
# ifdef MOZ_ENABLE_FREETYPE
# include "skia/include/ports/SkTypeface_cairo.h"
# endif
# include "mozilla/gfx/SkMemoryReporter.h"
# ifdef __GNUC__
# pragma GCC diagnostic pop // -Wshadow
# endif
static const uint32_t kDefaultGlyphCacheSize = -1;
#endif
#include "mozilla/Preferences.h"
#include "mozilla/Assertions.h"
#include "mozilla/Atomics.h"
#include "mozilla/Attributes.h"
#include "mozilla/Mutex.h"
#include "nsAlgorithm.h"
#include "nsIGfxInfo.h"
#include "nsIXULRuntime.h"
#include "VsyncSource.h"
#include "SoftwareVsyncSource.h"
#include "nscore.h" // for NS_FREE_PERMANENT_DATA
#include "mozilla/dom/ContentChild.h"
#include "mozilla/dom/TouchEvent.h"
#include "gfxVR.h"
#include "VRManagerChild.h"
#include "mozilla/gfx/GPUParent.h"
#include "mozilla/layers/MemoryReportingMLGPU.h"
#include "prsystem.h"
using namespace mozilla;
using namespace mozilla::layers;
using namespace mozilla::gl;
using namespace mozilla::gfx;
gfxPlatform* gPlatform = nullptr;
static bool gEverInitialized = false;
static int32_t gLastUsedFrameRate = -1;
const ContentDeviceData* gContentDeviceInitData = nullptr;
static Mutex* gGfxPlatformPrefsLock = nullptr;
// These two may point to the same profile
static qcms_profile* gCMSOutputProfile = nullptr;
static qcms_profile* gCMSsRGBProfile = nullptr;
static bool gCMSRGBTransformFailed = false;
static qcms_transform* gCMSRGBTransform = nullptr;
static qcms_transform* gCMSInverseRGBTransform = nullptr;
static qcms_transform* gCMSRGBATransform = nullptr;
static qcms_transform* gCMSBGRATransform = nullptr;
static bool gCMSInitialized = false;
static eCMSMode gCMSMode = eCMSMode_Off;
static void ShutdownCMS();
#include "mozilla/gfx/2D.h"
#include "mozilla/gfx/SourceSurfaceCairo.h"
/* Class to listen for pref changes so that chrome code can dynamically
force sRGB as an output profile. See Bug #452125. */
class SRGBOverrideObserver final : public nsIObserver,
public nsSupportsWeakReference {
~SRGBOverrideObserver() = default;
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIOBSERVER
};
/// This override of the LogForwarder, initially used for the critical graphics
/// errors, is sending the log to the crash annotations as well, but only
/// if the capacity set with the method below is >= 2. We always retain the
/// very first critical message, and the latest capacity-1 messages are
/// rotated through. Note that we don't expect the total number of times
/// this gets called to be large - it is meant for critical errors only.
class CrashStatsLogForwarder : public mozilla::gfx::LogForwarder {
public:
explicit CrashStatsLogForwarder(CrashReporter::Annotation aKey);
void Log(const std::string& aString) override;
void CrashAction(LogReason aReason) override;
bool UpdateStringsVector(const std::string& aString) override;
LoggingRecord LoggingRecordCopy() override;
void SetCircularBufferSize(uint32_t aCapacity);
private:
// Helper for the Log()
void UpdateCrashReport();
private:
LoggingRecord mBuffer;
CrashReporter::Annotation mCrashCriticalKey;
uint32_t mMaxCapacity;
int32_t mIndex;
Mutex mMutex;
};
CrashStatsLogForwarder::CrashStatsLogForwarder(CrashReporter::Annotation aKey)
: mBuffer(),
mCrashCriticalKey(aKey),
mMaxCapacity(0),
mIndex(-1),
mMutex("CrashStatsLogForwarder") {}
void CrashStatsLogForwarder::SetCircularBufferSize(uint32_t aCapacity) {
MutexAutoLock lock(mMutex);
mMaxCapacity = aCapacity;
mBuffer.reserve(static_cast<size_t>(aCapacity));
}
LoggingRecord CrashStatsLogForwarder::LoggingRecordCopy() {
MutexAutoLock lock(mMutex);
return mBuffer;
}
bool CrashStatsLogForwarder::UpdateStringsVector(const std::string& aString) {
// We want at least the first one and the last one. Otherwise, no point.
if (mMaxCapacity < 2) {
return false;
}
mIndex += 1;
MOZ_ASSERT(mIndex >= 0);
// index will count 0, 1, 2, ..., max-1, 1, 2, ..., max-1, 1, 2, ...
int32_t index = mIndex ? (mIndex - 1) % (mMaxCapacity - 1) + 1 : 0;
MOZ_ASSERT(index >= 0 && index < (int32_t)mMaxCapacity);
MOZ_ASSERT(index <= mIndex && index <= (int32_t)mBuffer.size());
double tStamp = (TimeStamp::NowLoRes() - TimeStamp::ProcessCreation())
.ToSecondsSigDigits();
// Checking for index >= mBuffer.size(), rather than index == mBuffer.size()
// just out of paranoia, but we know index <= mBuffer.size().
LoggingRecordEntry newEntry(mIndex, aString, tStamp);
if (index >= static_cast<int32_t>(mBuffer.size())) {
mBuffer.push_back(newEntry);
} else {
mBuffer[index] = newEntry;
}
return true;
}
void CrashStatsLogForwarder::UpdateCrashReport() {
std::stringstream message;
std::string logAnnotation;
switch (XRE_GetProcessType()) {
case GeckoProcessType_Default:
logAnnotation = "|[";
break;
case GeckoProcessType_Content:
logAnnotation = "|[C";
break;
case GeckoProcessType_GPU:
logAnnotation = "|[G";
break;
default:
logAnnotation = "|[X";
break;
}
for (auto& it : mBuffer) {
message << logAnnotation << Get<0>(it) << "]" << Get<1>(it)
<< " (t=" << Get<2>(it) << ") ";
}
nsCString reportString(message.str().c_str());
nsresult annotated =
CrashReporter::AnnotateCrashReport(mCrashCriticalKey, reportString);
if (annotated != NS_OK) {
printf("Crash Annotation %s: %s",
CrashReporter::AnnotationToString(mCrashCriticalKey),
message.str().c_str());
}
}
class LogForwarderEvent : public Runnable {
virtual ~LogForwarderEvent() = default;
public:
NS_INLINE_DECL_REFCOUNTING_INHERITED(LogForwarderEvent, Runnable)
explicit LogForwarderEvent(const nsCString& aMessage)
: mozilla::Runnable("LogForwarderEvent"), mMessage(aMessage) {}
NS_IMETHOD Run() override {
MOZ_ASSERT(NS_IsMainThread() &&
(XRE_IsContentProcess() || XRE_IsGPUProcess()));
if (XRE_IsContentProcess()) {
dom::ContentChild* cc = dom::ContentChild::GetSingleton();
Unused << cc->SendGraphicsError(mMessage);
} else if (XRE_IsGPUProcess()) {
GPUParent* gp = GPUParent::GetSingleton();
Unused << gp->SendGraphicsError(mMessage);
}
return NS_OK;
}
protected:
nsCString mMessage;
};
void CrashStatsLogForwarder::Log(const std::string& aString) {
MutexAutoLock lock(mMutex);
if (UpdateStringsVector(aString)) {
UpdateCrashReport();
}
// Add it to the parent strings
if (!XRE_IsParentProcess()) {
nsCString stringToSend(aString.c_str());
if (NS_IsMainThread()) {
if (XRE_IsContentProcess()) {
dom::ContentChild* cc = dom::ContentChild::GetSingleton();
Unused << cc->SendGraphicsError(stringToSend);
} else if (XRE_IsGPUProcess()) {
GPUParent* gp = GPUParent::GetSingleton();
Unused << gp->SendGraphicsError(stringToSend);
}
} else {
nsCOMPtr<nsIRunnable> r1 = new LogForwarderEvent(stringToSend);
NS_DispatchToMainThread(r1);
}
}
}
class CrashTelemetryEvent : public Runnable {
virtual ~CrashTelemetryEvent() = default;
public:
NS_INLINE_DECL_REFCOUNTING_INHERITED(CrashTelemetryEvent, Runnable)
explicit CrashTelemetryEvent(uint32_t aReason)
: mozilla::Runnable("CrashTelemetryEvent"), mReason(aReason) {}
NS_IMETHOD Run() override {
MOZ_ASSERT(NS_IsMainThread());
Telemetry::Accumulate(Telemetry::GFX_CRASH, mReason);
return NS_OK;
}
protected:
uint32_t mReason;
};
void CrashStatsLogForwarder::CrashAction(LogReason aReason) {
#ifndef RELEASE_OR_BETA
// Non-release builds crash by default, but will use telemetry
// if this environment variable is present.
static bool useTelemetry = gfxEnv::GfxDevCrashTelemetry();
#else
// Release builds use telemetry by default, but will crash instead
// if this environment variable is present.
static bool useTelemetry = !gfxEnv::GfxDevCrashMozCrash();
#endif
if (useTelemetry) {
// The callers need to assure that aReason is in the range
// that the telemetry call below supports.
if (NS_IsMainThread()) {
Telemetry::Accumulate(Telemetry::GFX_CRASH, (uint32_t)aReason);
} else {
nsCOMPtr<nsIRunnable> r1 = new CrashTelemetryEvent((uint32_t)aReason);
NS_DispatchToMainThread(r1);
}
} else {
// ignoring aReason, we can get the information we need from the stack
MOZ_CRASH("GFX_CRASH");
}
}
NS_IMPL_ISUPPORTS(SRGBOverrideObserver, nsIObserver, nsISupportsWeakReference)
#define GFX_DOWNLOADABLE_FONTS_ENABLED "gfx.downloadable_fonts.enabled"
#define GFX_PREF_FALLBACK_USE_CMAPS \
"gfx.font_rendering.fallback.always_use_cmaps"
#define GFX_PREF_OPENTYPE_SVG "gfx.font_rendering.opentype_svg.enabled"
#define GFX_PREF_WORD_CACHE_CHARLIMIT "gfx.font_rendering.wordcache.charlimit"
#define GFX_PREF_WORD_CACHE_MAXENTRIES "gfx.font_rendering.wordcache.maxentries"
#define GFX_PREF_GRAPHITE_SHAPING "gfx.font_rendering.graphite.enabled"
#if defined(XP_MACOSX)
# define GFX_PREF_CORETEXT_SHAPING "gfx.font_rendering.coretext.enabled"
#endif
#define BIDI_NUMERAL_PREF "bidi.numeral"
#define GFX_PREF_CMS_FORCE_SRGB "gfx.color_management.force_srgb"
#define FONT_VARIATIONS_PREF "layout.css.font-variations.enabled"
NS_IMETHODIMP
SRGBOverrideObserver::Observe(nsISupports* aSubject, const char* aTopic,
const char16_t* someData) {
NS_ASSERTION(NS_strcmp(someData, (u"" GFX_PREF_CMS_FORCE_SRGB)) == 0,
"Restarting CMS on wrong pref!");
ShutdownCMS();
// Update current cms profile.
gfxPlatform::CreateCMSOutputProfile();
return NS_OK;
}
static const char* kObservedPrefs[] = {"gfx.downloadable_fonts.",
"gfx.font_rendering.", BIDI_NUMERAL_PREF,
nullptr};
static void FontPrefChanged(const char* aPref, void* aData) {
MOZ_ASSERT(aPref);
NS_ASSERTION(gfxPlatform::GetPlatform(), "the singleton instance has gone");
gfxPlatform::GetPlatform()->FontsPrefsChanged(aPref);
}
void gfxPlatform::OnMemoryPressure(layers::MemoryPressureReason aWhy) {
Factory::PurgeAllCaches();
gfxGradientCache::PurgeAllCaches();
gfxFontMissingGlyphs::Purge();
PurgeSkiaFontCache();
if (XRE_IsParentProcess()) {
layers::CompositorManagerChild* manager =
CompositorManagerChild::GetInstance();
if (manager) {
manager->SendNotifyMemoryPressure();
}
}
}
gfxPlatform::gfxPlatform()
: mHasVariationFontSupport(false),
mAzureCanvasBackendCollector(this, &gfxPlatform::GetAzureBackendInfo),
mApzSupportCollector(this, &gfxPlatform::GetApzSupportInfo),
mTilesInfoCollector(this, &gfxPlatform::GetTilesSupportInfo),
mFrameStatsCollector(this, &gfxPlatform::GetFrameStats),
mCMSInfoCollector(this, &gfxPlatform::GetCMSSupportInfo),
mDisplayInfoCollector(this, &gfxPlatform::GetDisplayInfo),
mCompositorBackend(layers::LayersBackend::LAYERS_NONE),
mScreenDepth(0),
mScreenPixels(0) {
mAllowDownloadableFonts = UNINITIALIZED_VALUE;
mFallbackUsesCmaps = UNINITIALIZED_VALUE;
mWordCacheCharLimit = UNINITIALIZED_VALUE;
mWordCacheMaxEntries = UNINITIALIZED_VALUE;
mGraphiteShapingEnabled = UNINITIALIZED_VALUE;
mOpenTypeSVGEnabled = UNINITIALIZED_VALUE;
mBidiNumeralOption = UNINITIALIZED_VALUE;
InitBackendPrefs(GetBackendPrefs());
mTotalSystemMemory = PR_GetPhysicalMemorySize();
VRManager::ManagerInit();
}
gfxPlatform* gfxPlatform::GetPlatform() {
if (!gPlatform) {
MOZ_RELEASE_ASSERT(!XRE_IsContentProcess(),
"Content Process should have called InitChild() before "
"first GetPlatform()");
Init();
}
return gPlatform;
}
bool gfxPlatform::Initialized() { return !!gPlatform; }
/* static */
void gfxPlatform::InitChild(const ContentDeviceData& aData) {
MOZ_ASSERT(XRE_IsContentProcess());
MOZ_RELEASE_ASSERT(!gPlatform,
"InitChild() should be called before first GetPlatform()");
// Make the provided initial ContentDeviceData available to the init
// routines, so they don't have to do a sync request from the parent.
gContentDeviceInitData = &aData;
Init();
gContentDeviceInitData = nullptr;
}
void RecordingPrefChanged(const char* aPrefName, void* aClosure) {
if (Preferences::GetBool("gfx.2d.recording", false)) {
nsAutoCString fileName;
nsAutoString prefFileName;
nsresult rv = Preferences::GetString("gfx.2d.recordingfile", prefFileName);
if (NS_SUCCEEDED(rv)) {
CopyUTF16toUTF8(prefFileName, fileName);
} else {
nsCOMPtr<nsIFile> tmpFile;
if (NS_FAILED(NS_GetSpecialDirectory(NS_OS_TEMP_DIR,
getter_AddRefs(tmpFile)))) {
return;
}
fileName.AppendPrintf("moz2drec_%i_%i.aer", XRE_GetProcessType(),
getpid());
nsresult rv = tmpFile->AppendNative(fileName);
if (NS_FAILED(rv)) return;
#ifdef XP_WIN
rv = tmpFile->GetPath(prefFileName);
CopyUTF16toUTF8(prefFileName, fileName);
#else
rv = tmpFile->GetNativePath(fileName);
#endif
if (NS_FAILED(rv)) return;
}
#ifdef XP_WIN
gPlatform->mRecorder =
Factory::CreateEventRecorderForFile(prefFileName.BeginReading());
#else
gPlatform->mRecorder =
Factory::CreateEventRecorderForFile(fileName.BeginReading());
#endif
printf_stderr("Recording to %s\n", fileName.get());
Factory::SetGlobalEventRecorder(gPlatform->mRecorder);
} else {
Factory::SetGlobalEventRecorder(nullptr);
}
}
#define WR_DEBUG_PREF "gfx.webrender.debug"
static void WebRenderDebugPrefChangeCallback(const char* aPrefName, void*) {
wr::DebugFlags flags{0};
#define GFX_WEBRENDER_DEBUG(suffix, bit) \
if (Preferences::GetBool(WR_DEBUG_PREF suffix, false)) { \
flags |= (bit); \
}
GFX_WEBRENDER_DEBUG(".profiler", wr::DebugFlags::PROFILER_DBG)
GFX_WEBRENDER_DEBUG(".render-targets", wr::DebugFlags::RENDER_TARGET_DBG)
GFX_WEBRENDER_DEBUG(".texture-cache", wr::DebugFlags::TEXTURE_CACHE_DBG)
GFX_WEBRENDER_DEBUG(".gpu-time-queries", wr::DebugFlags::GPU_TIME_QUERIES)
GFX_WEBRENDER_DEBUG(".gpu-sample-queries", wr::DebugFlags::GPU_SAMPLE_QUERIES)
GFX_WEBRENDER_DEBUG(".disable-batching", wr::DebugFlags::DISABLE_BATCHING)
GFX_WEBRENDER_DEBUG(".epochs", wr::DebugFlags::EPOCHS)
GFX_WEBRENDER_DEBUG(".compact-profiler", wr::DebugFlags::COMPACT_PROFILER)
GFX_WEBRENDER_DEBUG(".smart-profiler", wr::DebugFlags::SMART_PROFILER)
GFX_WEBRENDER_DEBUG(".echo-driver-messages",
wr::DebugFlags::ECHO_DRIVER_MESSAGES)
GFX_WEBRENDER_DEBUG(".new-frame-indicator",
wr::DebugFlags::NEW_FRAME_INDICATOR)
GFX_WEBRENDER_DEBUG(".new-scene-indicator",
wr::DebugFlags::NEW_SCENE_INDICATOR)
GFX_WEBRENDER_DEBUG(".show-overdraw", wr::DebugFlags::SHOW_OVERDRAW)
GFX_WEBRENDER_DEBUG(".gpu-cache", wr::DebugFlags::GPU_CACHE_DBG)
GFX_WEBRENDER_DEBUG(".slow-frame-indicator",
wr::DebugFlags::SLOW_FRAME_INDICATOR)
GFX_WEBRENDER_DEBUG(".texture-cache.clear-evicted",
wr::DebugFlags::TEXTURE_CACHE_DBG_CLEAR_EVICTED)
GFX_WEBRENDER_DEBUG(".picture-caching", wr::DebugFlags::PICTURE_CACHING_DBG)
GFX_WEBRENDER_DEBUG(".tile-cache-logging",
wr::DebugFlags::TILE_CACHE_LOGGING_DBG)
GFX_WEBRENDER_DEBUG(".primitives", wr::DebugFlags::PRIMITIVE_DBG)
// Bit 18 is for the zoom display, which requires the mouse position and thus
// currently only works in wrench.
GFX_WEBRENDER_DEBUG(".small-screen", wr::DebugFlags::SMALL_SCREEN)
GFX_WEBRENDER_DEBUG(".disable-opaque-pass",
wr::DebugFlags::DISABLE_OPAQUE_PASS)
GFX_WEBRENDER_DEBUG(".disable-alpha-pass", wr::DebugFlags::DISABLE_ALPHA_PASS)
GFX_WEBRENDER_DEBUG(".disable-clip-masks", wr::DebugFlags::DISABLE_CLIP_MASKS)
GFX_WEBRENDER_DEBUG(".disable-text-prims", wr::DebugFlags::DISABLE_TEXT_PRIMS)
GFX_WEBRENDER_DEBUG(".disable-gradient-prims",
wr::DebugFlags::DISABLE_GRADIENT_PRIMS)
GFX_WEBRENDER_DEBUG(".obscure-images", wr::DebugFlags::OBSCURE_IMAGES)
GFX_WEBRENDER_DEBUG(".glyph-flashing", wr::DebugFlags::GLYPH_FLASHING)
GFX_WEBRENDER_DEBUG(".disable-raster-root-scaling",
wr::DebugFlags::DISABLE_RASTER_ROOT_SCALING)
#undef GFX_WEBRENDER_DEBUG
gfx::gfxVars::SetWebRenderDebugFlags(flags.bits);
}
static void WebRenderQualityPrefChangeCallback(const char* aPref, void*) {
gfxPlatform::GetPlatform()->UpdateAllowSacrificingSubpixelAA();
}
static void WebRenderMultithreadingPrefChangeCallback(const char* aPrefName,
void*) {
bool enable = Preferences::GetBool(
StaticPrefs::GetPrefName_gfx_webrender_enable_multithreading(), true);
gfx::gfxVars::SetUseWebRenderMultithreading(enable);
}
static void WebRenderBatchingPrefChangeCallback(const char* aPrefName, void*) {
uint32_t count = Preferences::GetUint(
StaticPrefs::GetPrefName_gfx_webrender_batching_lookback(), 10);
gfx::gfxVars::SetWebRenderBatchingLookback(count);
}
#if defined(USE_SKIA)
static uint32_t GetSkiaGlyphCacheSize() {
// Only increase font cache size on non-android to save memory.
# if !defined(MOZ_WIDGET_ANDROID)
// 10mb as the default pref cache size on desktop due to talos perf tweaking.
// Chromium uses 20mb and skia default uses 2mb.
// We don't need to change the font cache count since we usually
// cache thrash due to asian character sets in talos.
// Only increase memory on the content process
uint32_t cacheSize =
StaticPrefs::gfx_content_skia_font_cache_size_AtStartup() * 1024 * 1024;
if (mozilla::BrowserTabsRemoteAutostart()) {
return XRE_IsContentProcess() ? cacheSize : kDefaultGlyphCacheSize;
}
return cacheSize;
# else
return kDefaultGlyphCacheSize;
# endif // MOZ_WIDGET_ANDROID
}
#endif
class WebRenderMemoryReporter final : public nsIMemoryReporter {
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIMEMORYREPORTER
private:
~WebRenderMemoryReporter() = default;
};
// Memory reporter for WebRender.
//
// The reporting within WebRender is manual and incomplete. We could do a much
// more thorough job by depending on the malloc_size_of crate, but integrating
// that into WebRender is tricky [1].
//
// So the idea is to start with manual reporting for the large allocations
// detected by DMD, and see how much that can cover in practice (which may
// require a few rounds of iteration). If that approach turns out to be
// fundamentally insufficient, we can either duplicate more of the
// malloc_size_of functionality in WebRender, or deal with the complexity of a
// gecko-only crate dependency.
//
// [1] See https://bugzilla.mozilla.org/show_bug.cgi?id=1480293#c1
struct WebRenderMemoryReporterHelper {
WebRenderMemoryReporterHelper(nsIHandleReportCallback* aCallback,
nsISupports* aData)
: mCallback(aCallback), mData(aData) {}
nsCOMPtr<nsIHandleReportCallback> mCallback;
nsCOMPtr<nsISupports> mData;
void Report(size_t aBytes, const char* aName) const {
nsPrintfCString path("explicit/gfx/webrender/%s", aName);
nsCString desc(NS_LITERAL_CSTRING("CPU heap memory used by WebRender"));
ReportInternal(aBytes, path, desc, nsIMemoryReporter::KIND_HEAP);
}
void ReportTexture(size_t aBytes, const char* aName) const {
nsPrintfCString path("gfx/webrender/textures/%s", aName);
nsCString desc(NS_LITERAL_CSTRING("GPU texture memory used by WebRender"));
ReportInternal(aBytes, path, desc, nsIMemoryReporter::KIND_OTHER);
}
void ReportTotalGPUBytes(size_t aBytes) const {
nsCString path(NS_LITERAL_CSTRING("gfx/webrender/total-gpu-bytes"));
nsCString desc(NS_LITERAL_CSTRING(
"Total GPU bytes used by WebRender (should match textures/ sum)"));
ReportInternal(aBytes, path, desc, nsIMemoryReporter::KIND_OTHER);
}
void ReportInternal(size_t aBytes, nsACString& aPath, nsACString& aDesc,
int32_t aKind) const {
// Generally, memory reporters pass the empty string as the process name to
// indicate "current process". However, if we're using a GPU process, the
// measurements will actually take place in that process, and it's easier to
// just note that here rather than trying to invoke the memory reporter in
// the GPU process.
nsAutoCString processName;
if (gfxConfig::IsEnabled(Feature::GPU_PROCESS)) {
GPUParent::GetGPUProcessName(processName);
}
mCallback->Callback(processName, aPath, aKind,
nsIMemoryReporter::UNITS_BYTES, aBytes, aDesc, mData);
}
};
static void FinishAsyncMemoryReport() {
nsCOMPtr<nsIMemoryReporterManager> imgr =
do_GetService("@mozilla.org/memory-reporter-manager;1");
if (imgr) {
imgr->EndReport();
}
}
// clang-format off
// (For some reason, clang-format gets the second macro right, but totally mangles the first).
#define REPORT_INTERNER(id) \
helper.Report(aReport.interning.interners.id, \
"interning/" #id "/interners");
// clang-format on
#define REPORT_DATA_STORE(id) \
helper.Report(aReport.interning.data_stores.id, \
"interning/" #id "/data-stores");
NS_IMPL_ISUPPORTS(WebRenderMemoryReporter, nsIMemoryReporter)
NS_IMETHODIMP
WebRenderMemoryReporter::CollectReports(nsIHandleReportCallback* aHandleReport,
nsISupports* aData, bool aAnonymize) {
MOZ_ASSERT(XRE_IsParentProcess());
MOZ_ASSERT(NS_IsMainThread());
layers::CompositorManagerChild* manager =
CompositorManagerChild::GetInstance();
if (!manager) {
FinishAsyncMemoryReport();
return NS_OK;
}
WebRenderMemoryReporterHelper helper(aHandleReport, aData);
manager->SendReportMemory(
[=](wr::MemoryReport aReport) {
// CPU Memory.
helper.Report(aReport.clip_stores, "clip-stores");
helper.Report(aReport.gpu_cache_metadata, "gpu-cache/metadata");
helper.Report(aReport.gpu_cache_cpu_mirror, "gpu-cache/cpu-mirror");
helper.Report(aReport.render_tasks, "render-tasks");
helper.Report(aReport.hit_testers, "hit-testers");
helper.Report(aReport.fonts, "resource-cache/fonts");
helper.Report(aReport.images, "resource-cache/images");
helper.Report(aReport.rasterized_blobs,
"resource-cache/rasterized-blobs");
helper.Report(aReport.shader_cache, "shader-cache");
helper.Report(aReport.display_list, "display-list");
WEBRENDER_FOR_EACH_INTERNER(REPORT_INTERNER);
WEBRENDER_FOR_EACH_INTERNER(REPORT_DATA_STORE);
// GPU Memory.
helper.ReportTexture(aReport.gpu_cache_textures, "gpu-cache");
helper.ReportTexture(aReport.vertex_data_textures, "vertex-data");
helper.ReportTexture(aReport.render_target_textures, "render-targets");
helper.ReportTexture(aReport.texture_cache_textures, "texture-cache");
helper.ReportTexture(aReport.depth_target_textures, "depth-targets");
helper.ReportTexture(aReport.swap_chain, "swap-chains");
FinishAsyncMemoryReport();
},
[](mozilla::ipc::ResponseRejectReason&& aReason) {
FinishAsyncMemoryReport();
});
return NS_OK;
}
#undef REPORT_INTERNER
#undef REPORT_DATA_STORE
static const char* const WR_ROLLOUT_PREF = "gfx.webrender.all.qualified";
static const bool WR_ROLLOUT_PREF_DEFAULTVALUE = true;
static const char* const WR_ROLLOUT_DEFAULT_PREF =
"gfx.webrender.all.qualified.default";
static const bool WR_ROLLOUT_DEFAULT_PREF_DEFAULTVALUE = false;
static const char* const WR_ROLLOUT_PREF_OVERRIDE =
"gfx.webrender.all.qualified.gfxPref-default-override";
static const char* const WR_ROLLOUT_HW_QUALIFIED_OVERRIDE =
"gfx.webrender.all.qualified.hardware-override";
static const char* const PROFILE_BEFORE_CHANGE_TOPIC = "profile-before-change";
// If the "gfx.webrender.all.qualified" pref is true we want to enable
// WebRender for qualified hardware. This pref may be set by the Normandy
// Preference Rollout feature. The Normandy pref rollout code sets default
// values on rolled out prefs on every startup. Default pref values are not
// persisted; they only exist in memory for that session. Gfx starts up
// before Normandy does. So it's too early to observe the WR qualified pref
// changed by Normandy rollout on gfx startup. So we add a shutdown observer to
// save the default value on shutdown, and read the saved value on startup
// instead.
class WrRolloutPrefShutdownSaver : public nsIObserver {
public:
NS_DECL_ISUPPORTS
NS_IMETHOD Observe(nsISupports*, const char* aTopic,
const char16_t*) override {
if (strcmp(PROFILE_BEFORE_CHANGE_TOPIC, aTopic) != 0) {
// Not the observer we're looking for, move along.
return NS_OK;
}
SaveRolloutPref();
// Shouldn't receive another notification, remove the observer.
RefPtr<WrRolloutPrefShutdownSaver> kungFuDeathGrip(this);
nsCOMPtr<nsIObserverService> observerService =
mozilla::services::GetObserverService();
if (NS_WARN_IF(!observerService)) {
return NS_ERROR_FAILURE;
}
observerService->RemoveObserver(this, PROFILE_BEFORE_CHANGE_TOPIC);
return NS_OK;
}
static void AddShutdownObserver() {
MOZ_ASSERT(XRE_IsParentProcess());
nsCOMPtr<nsIObserverService> observerService =
mozilla::services::GetObserverService();
if (NS_WARN_IF(!observerService)) {
return;
}
RefPtr<WrRolloutPrefShutdownSaver> wrRolloutSaver =
new WrRolloutPrefShutdownSaver();
observerService->AddObserver(wrRolloutSaver, PROFILE_BEFORE_CHANGE_TOPIC,
false);
}
private:
virtual ~WrRolloutPrefShutdownSaver() = default;
void SaveRolloutPref() {
if (Preferences::HasUserValue(WR_ROLLOUT_PREF) ||
Preferences::GetType(WR_ROLLOUT_PREF) == nsIPrefBranch::PREF_INVALID) {
// Don't need to create a backup of default value, because either:
// 1. the user or the WR SHIELD study has set a user pref value, or
// 2. we've not had a default pref set by Normandy that needs to be saved
// for reading before Normandy has started up.
return;
}
bool defaultValue =
Preferences::GetBool(WR_ROLLOUT_PREF, false, PrefValueKind::Default);
Preferences::SetBool(WR_ROLLOUT_DEFAULT_PREF, defaultValue);
}
};
static void FrameRatePrefChanged(const char* aPref, void*) {
int32_t newRate = gfxPlatform::ForceSoftwareVsync()
? gfxPlatform::GetSoftwareVsyncRate()
: -1;
if (newRate != gLastUsedFrameRate) {
gLastUsedFrameRate = newRate;
gfxPlatform::ReInitFrameRate();
}
}
NS_IMPL_ISUPPORTS(WrRolloutPrefShutdownSaver, nsIObserver)
void gfxPlatform::Init() {
MOZ_RELEASE_ASSERT(!XRE_IsGPUProcess(), "GFX: Not allowed in GPU process.");
MOZ_RELEASE_ASSERT(!XRE_IsRDDProcess(), "GFX: Not allowed in RDD process.");
MOZ_RELEASE_ASSERT(NS_IsMainThread(), "GFX: Not in main thread.");
if (gEverInitialized) {
MOZ_CRASH("Already started???");
}
gEverInitialized = true;
gfxVars::Initialize();
gfxConfig::Init();
if (XRE_IsParentProcess()) {
GPUProcessManager::Initialize();
RDDProcessManager::Initialize();
if (Preferences::GetBool("media.wmf.skip-blacklist")) {
gfxVars::SetPDMWMFDisableD3D11Dlls(nsCString());
gfxVars::SetPDMWMFDisableD3D9Dlls(nsCString());
} else {
nsAutoCString d3d11;
Preferences::GetCString("media.wmf.disable-d3d11-for-dlls", d3d11);
gfxVars::SetPDMWMFDisableD3D11Dlls(d3d11);
nsAutoCString d3d9;
Preferences::GetCString("media.wmf.disable-d3d9-for-dlls", d3d9);
gfxVars::SetPDMWMFDisableD3D9Dlls(d3d9);
}
nsCOMPtr<nsIFile> file;
nsresult rv = NS_GetSpecialDirectory(NS_GRE_DIR, getter_AddRefs(file));
if (NS_FAILED(rv)) {
gfxVars::SetGREDirectory(nsString());
} else {
nsAutoString path;
file->GetPath(path);
gfxVars::SetGREDirectory(nsString(path));
}
}
if (XRE_IsParentProcess()) {
WrRolloutPrefShutdownSaver::AddShutdownObserver();
nsCOMPtr<nsIFile> profDir;
nsresult rv = NS_GetSpecialDirectory(NS_APP_PROFILE_DIR_STARTUP,
getter_AddRefs(profDir));
if (NS_FAILED(rv)) {
gfxVars::SetProfDirectory(nsString());
} else {
nsAutoString path;
profDir->GetPath(path);
gfxVars::SetProfDirectory(nsString(path));
}
nsAutoCString path;
Preferences::GetCString("layers.windowrecording.path", path);
gfxVars::SetLayersWindowRecordingPath(path);
}
// Drop a note in the crash report if we end up forcing an option that could
// destabilize things. New items should be appended at the end (of an
// existing or in a new section), so that we don't have to know the version to
// interpret these cryptic strings.
{
nsAutoCString forcedPrefs;
// D2D prefs
forcedPrefs.AppendPrintf(
"FP(D%d%d", StaticPrefs::gfx_direct2d_disabled_AtStartup(),
StaticPrefs::gfx_direct2d_force_enabled_AtStartup());
// Layers prefs
forcedPrefs.AppendPrintf(
"-L%d%d%d%d",
StaticPrefs::layers_amd_switchable_gfx_enabled_AtStartup(),
StaticPrefs::layers_acceleration_disabled_AtStartup_DoNotUseDirectly(),
StaticPrefs::
layers_acceleration_force_enabled_AtStartup_DoNotUseDirectly(),
StaticPrefs::layers_d3d11_force_warp_AtStartup());
// WebGL prefs
forcedPrefs.AppendPrintf(
"-W%d%d%d%d%d%d%d%d", StaticPrefs::webgl_angle_force_d3d11(),
StaticPrefs::webgl_angle_force_warp(), StaticPrefs::webgl_disabled(),
StaticPrefs::webgl_disable_angle(), StaticPrefs::webgl_dxgl_enabled(),
StaticPrefs::webgl_force_enabled(),
StaticPrefs::webgl_force_layers_readback(),
StaticPrefs::webgl_msaa_force());
// Prefs that don't fit into any of the other sections
forcedPrefs.AppendPrintf("-T%d%d%d) ",
StaticPrefs::gfx_android_rgb16_force_AtStartup(),
0, // SkiaGL canvas no longer supported
StaticPrefs::layers_force_shmem_tiles_AtStartup());
ScopedGfxFeatureReporter::AppNote(forcedPrefs);
}
InitMoz2DLogging();
gGfxPlatformPrefsLock = new Mutex("gfxPlatform::gGfxPlatformPrefsLock");
/* Initialize the GfxInfo service.
* Note: we can't call functions on GfxInfo that depend
* on gPlatform until after it has been initialized
* below. GfxInfo initialization annotates our
* crash reports so we want to do it before
* we try to load any drivers and do device detection
* incase that code crashes. See bug #591561. */
nsCOMPtr<nsIGfxInfo> gfxInfo;
/* this currently will only succeed on Windows */
gfxInfo = services::GetGfxInfo();
if (XRE_IsParentProcess()) {
// Some gfxVars must be initialized prior gPlatform for coherent results.
gfxVars::SetDXInterop2Blocked(IsDXInterop2Blocked());
gfxVars::SetDXNV12Blocked(IsDXNV12Blocked());
gfxVars::SetDXP010Blocked(IsDXP010Blocked());
gfxVars::SetDXP016Blocked(IsDXP016Blocked());
}
#if defined(XP_WIN)