summaryrefslogtreecommitdiffstats
path: root/widget/GfxInfoBase.cpp
blob: 251b46ce661bea523a5e693bc19f36fd640a60eb (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
/* vim: se cin sw=2 ts=2 et : */
/* -*- Mode: C++; tab-width: 2; 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/ArrayUtils.h"

#include "GfxInfoBase.h"

#include <mutex>  // std::call_once

#include "GfxDriverInfo.h"
#include "js/Array.h"               // JS::GetArrayLength, JS::NewArrayObject
#include "js/PropertyAndElement.h"  // JS_SetElement, JS_SetProperty
#include "nsCOMPtr.h"
#include "nsCOMArray.h"
#include "nsString.h"
#include "nsUnicharUtils.h"
#include "nsVersionComparator.h"
#include "mozilla/Services.h"
#include "mozilla/Observer.h"
#include "nsIObserver.h"
#include "nsIObserverService.h"
#include "nsTArray.h"
#include "nsXULAppAPI.h"
#include "nsIXULAppInfo.h"
#include "mozilla/BinarySearch.h"
#include "mozilla/ClearOnShutdown.h"
#include "mozilla/Preferences.h"
#include "mozilla/StaticPrefs_gfx.h"
#include "mozilla/gfx/2D.h"
#include "mozilla/gfx/BuildConstants.h"
#include "mozilla/gfx/GPUProcessManager.h"
#include "mozilla/gfx/Logging.h"
#include "mozilla/gfx/gfxVars.h"
#include "mozilla/widget/ScreenManager.h"
#include "mozilla/widget/Screen.h"

#include "jsapi.h"

#include "gfxPlatform.h"
#include "gfxConfig.h"
#include "DriverCrashGuard.h"

#ifdef MOZ_WIDGET_ANDROID
#  include <set>
#  include "AndroidBuild.h"
#endif

using namespace mozilla::widget;
using namespace mozilla;
using mozilla::MutexAutoLock;

nsTArray<GfxDriverInfo>* GfxInfoBase::sDriverInfo;
StaticAutoPtr<nsTArray<gfx::GfxInfoFeatureStatus>> GfxInfoBase::sFeatureStatus;
bool GfxInfoBase::sDriverInfoObserverInitialized;
bool GfxInfoBase::sShutdownOccurred;

// Call this when setting sFeatureStatus to a non-null pointer to
// ensure destruction even if the GfxInfo component is never instantiated.
static void InitFeatureStatus(nsTArray<gfx::GfxInfoFeatureStatus>* aPtr) {
  static std::once_flag sOnce;
  std::call_once(sOnce, [] { ClearOnShutdown(&GfxInfoBase::sFeatureStatus); });
  GfxInfoBase::sFeatureStatus = aPtr;
}

// Observes for shutdown so that the child GfxDriverInfo list is freed.
class ShutdownObserver : public nsIObserver {
  virtual ~ShutdownObserver() = default;

 public:
  ShutdownObserver() = default;

  NS_DECL_ISUPPORTS

  NS_IMETHOD Observe(nsISupports* subject, const char* aTopic,
                     const char16_t* aData) override {
    MOZ_ASSERT(strcmp(aTopic, NS_XPCOM_SHUTDOWN_OBSERVER_ID) == 0);

    delete GfxInfoBase::sDriverInfo;
    GfxInfoBase::sDriverInfo = nullptr;

    for (auto& deviceFamily : GfxDriverInfo::sDeviceFamilies) {
      delete deviceFamily;
      deviceFamily = nullptr;
    }

    for (auto& windowProtocol : GfxDriverInfo::sWindowProtocol) {
      delete windowProtocol;
      windowProtocol = nullptr;
    }

    for (auto& deviceVendor : GfxDriverInfo::sDeviceVendors) {
      delete deviceVendor;
      deviceVendor = nullptr;
    }

    for (auto& driverVendor : GfxDriverInfo::sDriverVendors) {
      delete driverVendor;
      driverVendor = nullptr;
    }

    GfxInfoBase::sShutdownOccurred = true;

    return NS_OK;
  }
};

NS_IMPL_ISUPPORTS(ShutdownObserver, nsIObserver)

static void InitGfxDriverInfoShutdownObserver() {
  if (GfxInfoBase::sDriverInfoObserverInitialized) return;

  GfxInfoBase::sDriverInfoObserverInitialized = true;

  nsCOMPtr<nsIObserverService> observerService = services::GetObserverService();
  if (!observerService) {
    NS_WARNING("Could not get observer service!");
    return;
  }

  ShutdownObserver* obs = new ShutdownObserver();
  observerService->AddObserver(obs, NS_XPCOM_SHUTDOWN_OBSERVER_ID, false);
}

using namespace mozilla::widget;
using namespace mozilla::gfx;
using namespace mozilla;

NS_IMPL_ISUPPORTS(GfxInfoBase, nsIGfxInfo, nsIObserver,
                  nsISupportsWeakReference)

#define BLOCKLIST_PREF_BRANCH "gfx.blacklist."
#define SUGGESTED_VERSION_PREF BLOCKLIST_PREF_BRANCH "suggested-driver-version"

static const char* GetPrefNameForFeature(int32_t aFeature) {
  const char* name = nullptr;
  switch (aFeature) {
    case nsIGfxInfo::FEATURE_DIRECT2D:
      name = BLOCKLIST_PREF_BRANCH "direct2d";
      break;
    case nsIGfxInfo::FEATURE_DIRECT3D_9_LAYERS:
      name = BLOCKLIST_PREF_BRANCH "layers.direct3d9";
      break;
    case nsIGfxInfo::FEATURE_DIRECT3D_10_LAYERS:
      name = BLOCKLIST_PREF_BRANCH "layers.direct3d10";
      break;
    case nsIGfxInfo::FEATURE_DIRECT3D_10_1_LAYERS:
      name = BLOCKLIST_PREF_BRANCH "layers.direct3d10-1";
      break;
    case nsIGfxInfo::FEATURE_DIRECT3D_11_LAYERS:
      name = BLOCKLIST_PREF_BRANCH "layers.direct3d11";
      break;
    case nsIGfxInfo::FEATURE_DIRECT3D_11_ANGLE:
      name = BLOCKLIST_PREF_BRANCH "direct3d11angle";
      break;
    case nsIGfxInfo::FEATURE_HARDWARE_VIDEO_DECODING:
      name = BLOCKLIST_PREF_BRANCH "hardwarevideodecoding";
      break;
    case nsIGfxInfo::FEATURE_OPENGL_LAYERS:
      name = BLOCKLIST_PREF_BRANCH "layers.opengl";
      break;
    case nsIGfxInfo::FEATURE_WEBGL_OPENGL:
      name = BLOCKLIST_PREF_BRANCH "webgl.opengl";
      break;
    case nsIGfxInfo::FEATURE_WEBGL_ANGLE:
      name = BLOCKLIST_PREF_BRANCH "webgl.angle";
      break;
    case nsIGfxInfo::UNUSED_FEATURE_WEBGL_MSAA:
      name = BLOCKLIST_PREF_BRANCH "webgl.msaa";
      break;
    case nsIGfxInfo::FEATURE_STAGEFRIGHT:
      name = BLOCKLIST_PREF_BRANCH "stagefright";
      break;
    case nsIGfxInfo::FEATURE_WEBRTC_HW_ACCELERATION_H264:
      name = BLOCKLIST_PREF_BRANCH "webrtc.hw.acceleration.h264";
      break;
    case nsIGfxInfo::FEATURE_WEBRTC_HW_ACCELERATION_ENCODE:
      name = BLOCKLIST_PREF_BRANCH "webrtc.hw.acceleration.encode";
      break;
    case nsIGfxInfo::FEATURE_WEBRTC_HW_ACCELERATION_DECODE:
      name = BLOCKLIST_PREF_BRANCH "webrtc.hw.acceleration.decode";
      break;
    case nsIGfxInfo::FEATURE_CANVAS2D_ACCELERATION:
      name = BLOCKLIST_PREF_BRANCH "canvas2d.acceleration";
      break;
    case nsIGfxInfo::FEATURE_DX_INTEROP2:
      name = BLOCKLIST_PREF_BRANCH "dx.interop2";
      break;
    case nsIGfxInfo::FEATURE_GPU_PROCESS:
      name = BLOCKLIST_PREF_BRANCH "gpu.process";
      break;
    case nsIGfxInfo::FEATURE_WEBGL2:
      name = BLOCKLIST_PREF_BRANCH "webgl2";
      break;
    case nsIGfxInfo::FEATURE_D3D11_KEYED_MUTEX:
      name = BLOCKLIST_PREF_BRANCH "d3d11.keyed.mutex";
      break;
    case nsIGfxInfo::FEATURE_WEBRENDER:
      name = BLOCKLIST_PREF_BRANCH "webrender";
      break;
    case nsIGfxInfo::FEATURE_WEBRENDER_COMPOSITOR:
      name = BLOCKLIST_PREF_BRANCH "webrender.compositor";
      break;
    case nsIGfxInfo::FEATURE_DX_NV12:
      name = BLOCKLIST_PREF_BRANCH "dx.nv12";
      break;
    case nsIGfxInfo::FEATURE_DX_P010:
      name = BLOCKLIST_PREF_BRANCH "dx.p010";
      break;
    case nsIGfxInfo::FEATURE_DX_P016:
      name = BLOCKLIST_PREF_BRANCH "dx.p016";
      break;
    case nsIGfxInfo::FEATURE_VP8_HW_DECODE:
      name = BLOCKLIST_PREF_BRANCH "vp8.hw-decode";
      break;
    case nsIGfxInfo::FEATURE_VP9_HW_DECODE:
      name = BLOCKLIST_PREF_BRANCH "vp9.hw-decode";
      break;
    case nsIGfxInfo::FEATURE_GL_SWIZZLE:
      name = BLOCKLIST_PREF_BRANCH "gl.swizzle";
      break;
    case nsIGfxInfo::FEATURE_WEBRENDER_SCISSORED_CACHE_CLEARS:
      name = BLOCKLIST_PREF_BRANCH "webrender.scissored_cache_clears";
      break;
    case nsIGfxInfo::FEATURE_ALLOW_WEBGL_OUT_OF_PROCESS:
      name = BLOCKLIST_PREF_BRANCH "webgl.allow-oop";
      break;
    case nsIGfxInfo::FEATURE_THREADSAFE_GL:
      name = BLOCKLIST_PREF_BRANCH "gl.threadsafe";
      break;
    case nsIGfxInfo::FEATURE_WEBRENDER_OPTIMIZED_SHADERS:
      name = BLOCKLIST_PREF_BRANCH "webrender.optimized-shaders";
      break;
    case nsIGfxInfo::FEATURE_X11_EGL:
      name = BLOCKLIST_PREF_BRANCH "x11.egl";
      break;
    case nsIGfxInfo::FEATURE_DMABUF:
      name = BLOCKLIST_PREF_BRANCH "dmabuf";
      break;
    case nsIGfxInfo::FEATURE_WEBGPU:
      name = BLOCKLIST_PREF_BRANCH "webgpu";
      break;
    case nsIGfxInfo::FEATURE_VIDEO_OVERLAY:
      name = BLOCKLIST_PREF_BRANCH "video-overlay";
      break;
    case nsIGfxInfo::FEATURE_HW_DECODED_VIDEO_ZERO_COPY:
      name = BLOCKLIST_PREF_BRANCH "hw-video-zero-copy";
      break;
    case nsIGfxInfo::FEATURE_WEBRENDER_SHADER_CACHE:
      name = BLOCKLIST_PREF_BRANCH "webrender.program-binary-disk";
      break;
    case nsIGfxInfo::FEATURE_WEBRENDER_PARTIAL_PRESENT:
      name = BLOCKLIST_PREF_BRANCH "webrender.partial-present";
      break;
    case nsIGfxInfo::FEATURE_DMABUF_SURFACE_EXPORT:
      name = BLOCKLIST_PREF_BRANCH "dmabuf.surface-export";
      break;
    case nsIGfxInfo::FEATURE_REUSE_DECODER_DEVICE:
      name = BLOCKLIST_PREF_BRANCH "reuse-decoder-device";
      break;
    case nsIGfxInfo::FEATURE_BACKDROP_FILTER:
      name = BLOCKLIST_PREF_BRANCH "backdrop.filter";
      break;
    case nsIGfxInfo::FEATURE_ACCELERATED_CANVAS2D:
      name = BLOCKLIST_PREF_BRANCH "accelerated-canvas2d";
      break;
    case nsIGfxInfo::FEATURE_H264_HW_DECODE:
      name = BLOCKLIST_PREF_BRANCH "h264.hw-decode";
      break;
    case nsIGfxInfo::FEATURE_AV1_HW_DECODE:
      name = BLOCKLIST_PREF_BRANCH "av1.hw-decode";
      break;
    case nsIGfxInfo::FEATURE_VIDEO_SOFTWARE_OVERLAY:
      name = BLOCKLIST_PREF_BRANCH "video-software-overlay";
      break;
    case nsIGfxInfo::FEATURE_WEBGL_USE_HARDWARE:
      name = BLOCKLIST_PREF_BRANCH "webgl-use-hardware";
      break;
    case nsIGfxInfo::FEATURE_OVERLAY_VP_AUTO_HDR:
      name = BLOCKLIST_PREF_BRANCH "overlay-vp-auto-hdr";
      break;
    case nsIGfxInfo::FEATURE_OVERLAY_VP_SUPER_RESOLUTION:
      name = BLOCKLIST_PREF_BRANCH "overlay-vp-super-resolution";
      break;
    default:
      MOZ_ASSERT_UNREACHABLE("Unexpected nsIGfxInfo feature?!");
      break;
  }

  return name;
}

// Returns the value of the pref for the relevant feature in aValue.
// If the pref doesn't exist, aValue is not touched, and returns false.
static bool GetPrefValueForFeature(int32_t aFeature, int32_t& aValue,
                                   nsACString& aFailureId) {
  const char* prefname = GetPrefNameForFeature(aFeature);
  if (!prefname) return false;

  aValue = nsIGfxInfo::FEATURE_STATUS_UNKNOWN;
  if (!NS_SUCCEEDED(Preferences::GetInt(prefname, &aValue))) {
    return false;
  }

  if (aValue == nsIGfxInfo::FEATURE_DENIED) {
    // We should never see the DENIED status with the downloadable blocklist.
    return false;
  }

  nsCString failureprefname(prefname);
  failureprefname += ".failureid";
  nsAutoCString failureValue;
  nsresult rv = Preferences::GetCString(failureprefname.get(), failureValue);
  if (NS_SUCCEEDED(rv)) {
    aFailureId = failureValue.get();
  } else {
    aFailureId = "FEATURE_FAILURE_BLOCKLIST_PREF";
  }

  return true;
}

static void SetPrefValueForFeature(int32_t aFeature, int32_t aValue,
                                   const nsACString& aFailureId) {
  const char* prefname = GetPrefNameForFeature(aFeature);
  if (!prefname) return;
  if (XRE_IsParentProcess()) {
    GfxInfoBase::sFeatureStatus = nullptr;
  }

  Preferences::SetInt(prefname, aValue);
  if (!aFailureId.IsEmpty()) {
    nsAutoCString failureprefname(prefname);
    failureprefname += ".failureid";
    Preferences::SetCString(failureprefname.get(), aFailureId);
  }
}

static void RemovePrefForFeature(int32_t aFeature) {
  const char* prefname = GetPrefNameForFeature(aFeature);
  if (!prefname) return;

  if (XRE_IsParentProcess()) {
    GfxInfoBase::sFeatureStatus = nullptr;
  }
  Preferences::ClearUser(prefname);
}

static bool GetPrefValueForDriverVersion(nsCString& aVersion) {
  return NS_SUCCEEDED(
      Preferences::GetCString(SUGGESTED_VERSION_PREF, aVersion));
}

static void SetPrefValueForDriverVersion(const nsAString& aVersion) {
  Preferences::SetString(SUGGESTED_VERSION_PREF, aVersion);
}

static void RemovePrefForDriverVersion() {
  Preferences::ClearUser(SUGGESTED_VERSION_PREF);
}

static OperatingSystem BlocklistOSToOperatingSystem(const nsAString& os) {
  if (os.EqualsLiteral("WINNT 6.1")) {
    return OperatingSystem::Windows7;
  }
  if (os.EqualsLiteral("WINNT 6.2")) {
    return OperatingSystem::Windows8;
  }
  if (os.EqualsLiteral("WINNT 6.3")) {
    return OperatingSystem::Windows8_1;
  }
  if (os.EqualsLiteral("WINNT 10.0")) {
    return OperatingSystem::Windows10;
  }
  if (os.EqualsLiteral("Linux")) {
    return OperatingSystem::Linux;
  }
  if (os.EqualsLiteral("Darwin 9")) {
    return OperatingSystem::OSX10_5;
  }
  if (os.EqualsLiteral("Darwin 10")) {
    return OperatingSystem::OSX10_6;
  }
  if (os.EqualsLiteral("Darwin 11")) {
    return OperatingSystem::OSX10_7;
  }
  if (os.EqualsLiteral("Darwin 12")) {
    return OperatingSystem::OSX10_8;
  }
  if (os.EqualsLiteral("Darwin 13")) {
    return OperatingSystem::OSX10_9;
  }
  if (os.EqualsLiteral("Darwin 14")) {
    return OperatingSystem::OSX10_10;
  }
  if (os.EqualsLiteral("Darwin 15")) {
    return OperatingSystem::OSX10_11;
  }
  if (os.EqualsLiteral("Darwin 16")) {
    return OperatingSystem::OSX10_12;
  }
  if (os.EqualsLiteral("Darwin 17")) {
    return OperatingSystem::OSX10_13;
  }
  if (os.EqualsLiteral("Darwin 18")) {
    return OperatingSystem::OSX10_14;
  }
  if (os.EqualsLiteral("Darwin 19")) {
    return OperatingSystem::OSX10_15;
  }
  if (os.EqualsLiteral("Darwin 20")) {
    return OperatingSystem::OSX11_0;
  }
  if (os.EqualsLiteral("Android")) {
    return OperatingSystem::Android;
    // For historical reasons, "All" in blocklist means "All Windows"
  }
  if (os.EqualsLiteral("All")) {
    return OperatingSystem::Windows;
  }
  if (os.EqualsLiteral("Darwin")) {
    return OperatingSystem::OSX;
  }

  return OperatingSystem::Unknown;
}

static GfxDeviceFamily* BlocklistDevicesToDeviceFamily(
    nsTArray<nsCString>& devices) {
  if (devices.Length() == 0) return nullptr;

  // For each device, get its device ID, and return a freshly-allocated
  // GfxDeviceFamily with the contents of that array.
  GfxDeviceFamily* deviceIds = new GfxDeviceFamily;

  for (uint32_t i = 0; i < devices.Length(); ++i) {
    // We make sure we don't add any "empty" device entries to the array, so
    // we don't need to check if devices[i] is empty.
    deviceIds->Append(NS_ConvertUTF8toUTF16(devices[i]));
  }

  return deviceIds;
}

static int32_t BlocklistFeatureToGfxFeature(const nsAString& aFeature) {
  MOZ_ASSERT(!aFeature.IsEmpty());
  if (aFeature.EqualsLiteral("DIRECT2D")) {
    return nsIGfxInfo::FEATURE_DIRECT2D;
  }
  if (aFeature.EqualsLiteral("DIRECT3D_9_LAYERS")) {
    return nsIGfxInfo::FEATURE_DIRECT3D_9_LAYERS;
  }
  if (aFeature.EqualsLiteral("DIRECT3D_10_LAYERS")) {
    return nsIGfxInfo::FEATURE_DIRECT3D_10_LAYERS;
  }
  if (aFeature.EqualsLiteral("DIRECT3D_10_1_LAYERS")) {
    return nsIGfxInfo::FEATURE_DIRECT3D_10_1_LAYERS;
  }
  if (aFeature.EqualsLiteral("DIRECT3D_11_LAYERS")) {
    return nsIGfxInfo::FEATURE_DIRECT3D_11_LAYERS;
  }
  if (aFeature.EqualsLiteral("DIRECT3D_11_ANGLE")) {
    return nsIGfxInfo::FEATURE_DIRECT3D_11_ANGLE;
  }
  if (aFeature.EqualsLiteral("HARDWARE_VIDEO_DECODING")) {
    return nsIGfxInfo::FEATURE_HARDWARE_VIDEO_DECODING;
  }
  if (aFeature.EqualsLiteral("OPENGL_LAYERS")) {
    return nsIGfxInfo::FEATURE_OPENGL_LAYERS;
  }
  if (aFeature.EqualsLiteral("WEBGL_OPENGL")) {
    return nsIGfxInfo::FEATURE_WEBGL_OPENGL;
  }
  if (aFeature.EqualsLiteral("WEBGL_ANGLE")) {
    return nsIGfxInfo::FEATURE_WEBGL_ANGLE;
  }
  if (aFeature.EqualsLiteral("WEBGL_MSAA")) {
    return nsIGfxInfo::UNUSED_FEATURE_WEBGL_MSAA;
  }
  if (aFeature.EqualsLiteral("STAGEFRIGHT")) {
    return nsIGfxInfo::FEATURE_STAGEFRIGHT;
  }
  if (aFeature.EqualsLiteral("WEBRTC_HW_ACCELERATION_ENCODE")) {
    return nsIGfxInfo::FEATURE_WEBRTC_HW_ACCELERATION_ENCODE;
  }
  if (aFeature.EqualsLiteral("WEBRTC_HW_ACCELERATION_DECODE")) {
    return nsIGfxInfo::FEATURE_WEBRTC_HW_ACCELERATION_DECODE;
  }
  if (aFeature.EqualsLiteral("WEBRTC_HW_ACCELERATION_H264")) {
    return nsIGfxInfo::FEATURE_WEBRTC_HW_ACCELERATION_H264;
  }
  if (aFeature.EqualsLiteral("CANVAS2D_ACCELERATION")) {
    return nsIGfxInfo::FEATURE_CANVAS2D_ACCELERATION;
  }
  if (aFeature.EqualsLiteral("DX_INTEROP2")) {
    return nsIGfxInfo::FEATURE_DX_INTEROP2;
  }
  if (aFeature.EqualsLiteral("GPU_PROCESS")) {
    return nsIGfxInfo::FEATURE_GPU_PROCESS;
  }
  if (aFeature.EqualsLiteral("WEBGL2")) {
    return nsIGfxInfo::FEATURE_WEBGL2;
  }
  if (aFeature.EqualsLiteral("D3D11_KEYED_MUTEX")) {
    return nsIGfxInfo::FEATURE_D3D11_KEYED_MUTEX;
  }
  if (aFeature.EqualsLiteral("WEBRENDER")) {
    return nsIGfxInfo::FEATURE_WEBRENDER;
  }
  if (aFeature.EqualsLiteral("WEBRENDER_COMPOSITOR")) {
    return nsIGfxInfo::FEATURE_WEBRENDER_COMPOSITOR;
  }
  if (aFeature.EqualsLiteral("DX_NV12")) {
    return nsIGfxInfo::FEATURE_DX_NV12;
  }
  if (aFeature.EqualsLiteral("VP8_HW_DECODE")) {
    return nsIGfxInfo::FEATURE_VP8_HW_DECODE;
  }
  if (aFeature.EqualsLiteral("VP9_HW_DECODE")) {
    return nsIGfxInfo::FEATURE_VP9_HW_DECODE;
  }
  if (aFeature.EqualsLiteral("GL_SWIZZLE")) {
    return nsIGfxInfo::FEATURE_GL_SWIZZLE;
  }
  if (aFeature.EqualsLiteral("WEBRENDER_SCISSORED_CACHE_CLEARS")) {
    return nsIGfxInfo::FEATURE_WEBRENDER_SCISSORED_CACHE_CLEARS;
  }
  if (aFeature.EqualsLiteral("ALLOW_WEBGL_OUT_OF_PROCESS")) {
    return nsIGfxInfo::FEATURE_ALLOW_WEBGL_OUT_OF_PROCESS;
  }
  if (aFeature.EqualsLiteral("THREADSAFE_GL")) {
    return nsIGfxInfo::FEATURE_THREADSAFE_GL;
  }
  if (aFeature.EqualsLiteral("X11_EGL")) {
    return nsIGfxInfo::FEATURE_X11_EGL;
  }
  if (aFeature.EqualsLiteral("DMABUF")) {
    return nsIGfxInfo::FEATURE_DMABUF;
  }
  if (aFeature.EqualsLiteral("WEBGPU")) {
    return nsIGfxInfo::FEATURE_WEBGPU;
  }
  if (aFeature.EqualsLiteral("VIDEO_OVERLAY")) {
    return nsIGfxInfo::FEATURE_VIDEO_OVERLAY;
  }
  if (aFeature.EqualsLiteral("HW_DECODED_VIDEO_ZERO_COPY")) {
    return nsIGfxInfo::FEATURE_HW_DECODED_VIDEO_ZERO_COPY;
  }
  if (aFeature.EqualsLiteral("REUSE_DECODER_DEVICE")) {
    return nsIGfxInfo::FEATURE_REUSE_DECODER_DEVICE;
  }
  if (aFeature.EqualsLiteral("WEBRENDER_PARTIAL_PRESENT")) {
    return nsIGfxInfo::FEATURE_WEBRENDER_PARTIAL_PRESENT;
  }
  if (aFeature.EqualsLiteral("BACKDROP_FILTER")) {
    return nsIGfxInfo::FEATURE_BACKDROP_FILTER;
  }
  if (aFeature.EqualsLiteral("ACCELERATED_CANVAS2D")) {
    return nsIGfxInfo::FEATURE_ACCELERATED_CANVAS2D;
  }
  if (aFeature.EqualsLiteral("FEATURE_OVERLAY_VP_AUTO_HDR")) {
    return nsIGfxInfo::FEATURE_OVERLAY_VP_AUTO_HDR;
  }
  if (aFeature.EqualsLiteral("FEATURE_OVERLAY_VP_SUPER_RESOLUTION")) {
    return nsIGfxInfo::FEATURE_OVERLAY_VP_SUPER_RESOLUTION;
  }
  if (aFeature.EqualsLiteral("ALL")) {
    return GfxDriverInfo::allFeatures;
  }
  if (aFeature.EqualsLiteral("OPTIONAL")) {
    return GfxDriverInfo::optionalFeatures;
  }

  // If we don't recognize the feature, it may be new, and something
  // this version doesn't understand.  So, nothing to do.  This is
  // different from feature not being specified at all, in which case
  // this method should not get called and we should continue with the
  // "optional features" blocklisting.
  return 0;
}

static int32_t BlocklistFeatureStatusToGfxFeatureStatus(
    const nsAString& aStatus) {
  if (aStatus.EqualsLiteral("STATUS_OK")) {
    return nsIGfxInfo::FEATURE_STATUS_OK;
  }
  if (aStatus.EqualsLiteral("BLOCKED_DRIVER_VERSION")) {
    return nsIGfxInfo::FEATURE_BLOCKED_DRIVER_VERSION;
  }
  if (aStatus.EqualsLiteral("BLOCKED_DEVICE")) {
    return nsIGfxInfo::FEATURE_BLOCKED_DEVICE;
  }
  if (aStatus.EqualsLiteral("DISCOURAGED")) {
    return nsIGfxInfo::FEATURE_DISCOURAGED;
  }
  if (aStatus.EqualsLiteral("BLOCKED_OS_VERSION")) {
    return nsIGfxInfo::FEATURE_BLOCKED_OS_VERSION;
  }
  if (aStatus.EqualsLiteral("DENIED")) {
    return nsIGfxInfo::FEATURE_DENIED;
  }
  if (aStatus.EqualsLiteral("ALLOW_QUALIFIED")) {
    return nsIGfxInfo::FEATURE_ALLOW_QUALIFIED;
  }
  if (aStatus.EqualsLiteral("ALLOW_ALWAYS")) {
    return nsIGfxInfo::FEATURE_ALLOW_ALWAYS;
  }

  // Do not allow it to set STATUS_UNKNOWN.  Also, we are not
  // expecting the "mismatch" status showing up here.

  return nsIGfxInfo::FEATURE_STATUS_OK;
}

static VersionComparisonOp BlocklistComparatorToComparisonOp(
    const nsAString& op) {
  if (op.EqualsLiteral("LESS_THAN")) {
    return DRIVER_LESS_THAN;
  }
  if (op.EqualsLiteral("BUILD_ID_LESS_THAN")) {
    return DRIVER_BUILD_ID_LESS_THAN;
  }
  if (op.EqualsLiteral("LESS_THAN_OR_EQUAL")) {
    return DRIVER_LESS_THAN_OR_EQUAL;
  }
  if (op.EqualsLiteral("BUILD_ID_LESS_THAN_OR_EQUAL")) {
    return DRIVER_BUILD_ID_LESS_THAN_OR_EQUAL;
  }
  if (op.EqualsLiteral("GREATER_THAN")) {
    return DRIVER_GREATER_THAN;
  }
  if (op.EqualsLiteral("GREATER_THAN_OR_EQUAL")) {
    return DRIVER_GREATER_THAN_OR_EQUAL;
  }
  if (op.EqualsLiteral("EQUAL")) {
    return DRIVER_EQUAL;
  }
  if (op.EqualsLiteral("NOT_EQUAL")) {
    return DRIVER_NOT_EQUAL;
  }
  if (op.EqualsLiteral("BETWEEN_EXCLUSIVE")) {
    return DRIVER_BETWEEN_EXCLUSIVE;
  }
  if (op.EqualsLiteral("BETWEEN_INCLUSIVE")) {
    return DRIVER_BETWEEN_INCLUSIVE;
  }
  if (op.EqualsLiteral("BETWEEN_INCLUSIVE_START")) {
    return DRIVER_BETWEEN_INCLUSIVE_START;
  }

  return DRIVER_COMPARISON_IGNORED;
}

/*
  Deserialize Blocklist entries from string.
  e.g:
  os:WINNT 6.0\tvendor:0x8086\tdevices:0x2582,0x2782\tfeature:DIRECT3D_10_LAYERS\tfeatureStatus:BLOCKED_DRIVER_VERSION\tdriverVersion:8.52.322.2202\tdriverVersionComparator:LESS_THAN_OR_EQUAL
*/
static bool BlocklistEntryToDriverInfo(const nsACString& aBlocklistEntry,
                                       GfxDriverInfo& aDriverInfo) {
  // If we get an application version to be zero, something is not working
  // and we are not going to bother checking the blocklist versions.
  // See TestGfxWidgets.cpp for how version comparison works.
  // <versionRange minVersion="42.0a1" maxVersion="45.0"></versionRange>
  static mozilla::Version zeroV("0");
  static mozilla::Version appV(GfxInfoBase::GetApplicationVersion().get());
  if (appV <= zeroV) {
    gfxCriticalErrorOnce(gfxCriticalError::DefaultOptions(false))
        << "Invalid application version "
        << GfxInfoBase::GetApplicationVersion().get();
  }

  aDriverInfo.mRuleId = "FEATURE_FAILURE_DL_BLOCKLIST_NO_ID"_ns;

  for (const auto& keyValue : aBlocklistEntry.Split('\t')) {
    nsTArray<nsCString> splitted;
    ParseString(keyValue, ':', splitted);
    if (splitted.Length() != 2) {
      // If we don't recognize the input data, we do not want to proceed.
      gfxCriticalErrorOnce(CriticalLog::DefaultOptions(false))
          << "Unrecognized data " << nsCString(keyValue).get();
      return false;
    }
    const nsCString& key = splitted[0];
    const nsCString& value = splitted[1];
    NS_ConvertUTF8toUTF16 dataValue(value);

    if (value.Length() == 0) {
      // Safety check for empty values.
      gfxCriticalErrorOnce(CriticalLog::DefaultOptions(false))
          << "Empty value for " << key.get();
      return false;
    }

    if (key.EqualsLiteral("blockID")) {
      nsCString blockIdStr = "FEATURE_FAILURE_DL_BLOCKLIST_"_ns + value;
      aDriverInfo.mRuleId = blockIdStr.get();
    } else if (key.EqualsLiteral("os")) {
      aDriverInfo.mOperatingSystem = BlocklistOSToOperatingSystem(dataValue);
    } else if (key.EqualsLiteral("osversion")) {
      aDriverInfo.mOperatingSystemVersion = strtoul(value.get(), nullptr, 10);
    } else if (key.EqualsLiteral("windowProtocol")) {
      aDriverInfo.mWindowProtocol = dataValue;
    } else if (key.EqualsLiteral("vendor")) {
      aDriverInfo.mAdapterVendor = dataValue;
    } else if (key.EqualsLiteral("driverVendor")) {
      aDriverInfo.mDriverVendor = dataValue;
    } else if (key.EqualsLiteral("feature")) {
      aDriverInfo.mFeature = BlocklistFeatureToGfxFeature(dataValue);
      if (aDriverInfo.mFeature == 0) {
        // If we don't recognize the feature, we do not want to proceed.
        gfxWarning() << "Unrecognized feature " << value.get();
        return false;
      }
    } else if (key.EqualsLiteral("featureStatus")) {
      aDriverInfo.mFeatureStatus =
          BlocklistFeatureStatusToGfxFeatureStatus(dataValue);
    } else if (key.EqualsLiteral("driverVersion")) {
      uint64_t version;
      if (ParseDriverVersion(dataValue, &version))
        aDriverInfo.mDriverVersion = version;
    } else if (key.EqualsLiteral("driverVersionMax")) {
      uint64_t version;
      if (ParseDriverVersion(dataValue, &version))
        aDriverInfo.mDriverVersionMax = version;
    } else if (key.EqualsLiteral("driverVersionComparator")) {
      aDriverInfo.mComparisonOp = BlocklistComparatorToComparisonOp(dataValue);
    } else if (key.EqualsLiteral("model")) {
      aDriverInfo.mModel = dataValue;
    } else if (key.EqualsLiteral("product")) {
      aDriverInfo.mProduct = dataValue;
    } else if (key.EqualsLiteral("manufacturer")) {
      aDriverInfo.mManufacturer = dataValue;
    } else if (key.EqualsLiteral("hardware")) {
      aDriverInfo.mHardware = dataValue;
    } else if (key.EqualsLiteral("versionRange")) {
      nsTArray<nsCString> versionRange;
      ParseString(value, ',', versionRange);
      if (versionRange.Length() != 2) {
        gfxCriticalErrorOnce(CriticalLog::DefaultOptions(false))
            << "Unrecognized versionRange " << value.get();
        return false;
      }
      const nsCString& minValue = versionRange[0];
      const nsCString& maxValue = versionRange[1];

      mozilla::Version minV(minValue.get());
      mozilla::Version maxV(maxValue.get());

      if (minV > zeroV && !(appV >= minV)) {
        // The version of the application is less than the minimal version
        // this blocklist entry applies to, so we can just ignore it by
        // returning false and letting the caller deal with it.
        return false;
      }
      if (maxV > zeroV && !(appV <= maxV)) {
        // The version of the application is more than the maximal version
        // this blocklist entry applies to, so we can just ignore it by
        // returning false and letting the caller deal with it.
        return false;
      }
    } else if (key.EqualsLiteral("devices")) {
      nsTArray<nsCString> devices;
      ParseString(value, ',', devices);
      GfxDeviceFamily* deviceIds = BlocklistDevicesToDeviceFamily(devices);
      if (deviceIds) {
        // Get GfxDriverInfo to adopt the devices array we created.
        aDriverInfo.mDeleteDevices = true;
        aDriverInfo.mDevices = deviceIds;
      }
    }
    // We explicitly ignore unknown elements.
  }

  return true;
}

NS_IMETHODIMP
GfxInfoBase::Observe(nsISupports* aSubject, const char* aTopic,
                     const char16_t* aData) {
  if (strcmp(aTopic, "blocklist-data-gfxItems") == 0) {
    nsTArray<GfxDriverInfo> driverInfo;
    NS_ConvertUTF16toUTF8 utf8Data(aData);

    for (const auto& blocklistEntry : utf8Data.Split('\n')) {
      GfxDriverInfo di;
      if (BlocklistEntryToDriverInfo(blocklistEntry, di)) {
        // XXX Changing this to driverInfo.AppendElement(di) causes leaks.
        // Probably some non-standard semantics of the copy/move operations?
        *driverInfo.AppendElement() = di;
        // Prevent di falling out of scope from destroying the devices.
        di.mDeleteDevices = false;
      } else {
        driverInfo.AppendElement();
      }
    }

    EvaluateDownloadedBlocklist(driverInfo);
  }

  return NS_OK;
}

GfxInfoBase::GfxInfoBase() : mScreenPixels(INT64_MAX), mMutex("GfxInfoBase") {}

GfxInfoBase::~GfxInfoBase() = default;

nsresult GfxInfoBase::Init() {
  InitGfxDriverInfoShutdownObserver();

  nsCOMPtr<nsIObserverService> os = mozilla::services::GetObserverService();
  if (os) {
    os->AddObserver(this, "blocklist-data-gfxItems", true);
  }

  return NS_OK;
}

void GfxInfoBase::GetData() {
  if (mScreenPixels != INT64_MAX) {
    // Already initialized.
    return;
  }

  ScreenManager::GetSingleton().GetTotalScreenPixels(&mScreenPixels);
}

NS_IMETHODIMP
GfxInfoBase::GetFeatureStatus(int32_t aFeature, nsACString& aFailureId,
                              int32_t* aStatus) {
  // Ignore the gfx.blocklist.all pref on release and beta.
#if defined(RELEASE_OR_BETA)
  int32_t blocklistAll = 0;
#else
  int32_t blocklistAll = StaticPrefs::gfx_blocklist_all_AtStartup();
#endif
  if (blocklistAll > 0) {
    gfxCriticalErrorOnce(gfxCriticalError::DefaultOptions(false))
        << "Forcing blocklisting all features";
    *aStatus = FEATURE_BLOCKED_DEVICE;
    aFailureId = "FEATURE_FAILURE_BLOCK_ALL";
    return NS_OK;
  }

  if (blocklistAll < 0) {
    gfxCriticalErrorOnce(gfxCriticalError::DefaultOptions(false))
        << "Ignoring any feature blocklisting.";
    *aStatus = FEATURE_STATUS_OK;
    return NS_OK;
  }

  // This is how we evaluate the downloadable blocklist. If there is no pref,
  // then we will fallback to checking the static blocklist.
  if (GetPrefValueForFeature(aFeature, *aStatus, aFailureId)) {
    return NS_OK;
  }

  if (XRE_IsContentProcess() || XRE_IsGPUProcess()) {
    // Use the cached data received from the parent process.
    MOZ_ASSERT(sFeatureStatus);
    bool success = false;
    for (const auto& fs : *sFeatureStatus) {
      if (fs.feature() == aFeature) {
        aFailureId = fs.failureId();
        *aStatus = fs.status();
        success = true;
        break;
      }
    }
    return success ? NS_OK : NS_ERROR_FAILURE;
  }

  nsString version;
  nsTArray<GfxDriverInfo> driverInfo;
  nsresult rv =
      GetFeatureStatusImpl(aFeature, aStatus, version, driverInfo, aFailureId);
  return rv;
}

nsTArray<gfx::GfxInfoFeatureStatus> GfxInfoBase::GetAllFeatures() {
  MOZ_RELEASE_ASSERT(XRE_IsParentProcess());
  if (!sFeatureStatus) {
    InitFeatureStatus(new nsTArray<gfx::GfxInfoFeatureStatus>());
    for (int32_t i = 1; i <= nsIGfxInfo::FEATURE_MAX_VALUE; ++i) {
      int32_t status = 0;
      nsAutoCString failureId;
      GetFeatureStatus(i, failureId, &status);
      gfx::GfxInfoFeatureStatus gfxFeatureStatus;
      gfxFeatureStatus.feature() = i;
      gfxFeatureStatus.status() = status;
      gfxFeatureStatus.failureId() = failureId;
      sFeatureStatus->AppendElement(gfxFeatureStatus);
    }
  }

  nsTArray<gfx::GfxInfoFeatureStatus> features;
  for (const auto& status : *sFeatureStatus) {
    gfx::GfxInfoFeatureStatus copy = status;
    features.AppendElement(copy);
  }
  return features;
}

inline bool MatchingAllowStatus(int32_t aStatus) {
  switch (aStatus) {
    case nsIGfxInfo::FEATURE_ALLOW_ALWAYS:
    case nsIGfxInfo::FEATURE_ALLOW_QUALIFIED:
      return true;
    default:
      return false;
  }
}

// Matching OS go somewhat beyond the simple equality check because of the
// "All Windows" and "All OS X" variations.
//
// aBlockedOS is describing the system(s) we are trying to block.
// aSystemOS is describing the system we are running on.
//
// aSystemOS should not be "Windows" or "OSX" - it should be set to
// a particular version instead.
// However, it is valid for aBlockedOS to be one of those generic values,
// as we could be blocking all of the versions.
inline bool MatchingOperatingSystems(OperatingSystem aBlockedOS,
                                     OperatingSystem aSystemOS,
                                     uint32_t aSystemOSBuild) {
  MOZ_ASSERT(aSystemOS != OperatingSystem::Windows &&
             aSystemOS != OperatingSystem::OSX);

  // If the block entry OS is unknown, it doesn't match
  if (aBlockedOS == OperatingSystem::Unknown) {
    return false;
  }

#if defined(XP_WIN)
  if (aBlockedOS == OperatingSystem::Windows) {
    // We do want even "unknown" aSystemOS to fall under "all windows"
    return true;
  }

  constexpr uint32_t kMinWin10BuildNumber = 18362;
  if (aBlockedOS == OperatingSystem::RecentWindows10 &&
      aSystemOS == OperatingSystem::Windows10) {
    // For allowlist purposes, we sometimes want to restrict to only recent
    // versions of Windows 10. This is a bit of a kludge but easier than adding
    // complicated blocklist infrastructure for build ID comparisons like driver
    // versions.
    return aSystemOSBuild >= kMinWin10BuildNumber;
  }

  if (aBlockedOS == OperatingSystem::NotRecentWindows10) {
    if (aSystemOS == OperatingSystem::Windows10) {
      return aSystemOSBuild < kMinWin10BuildNumber;
    } else {
      return true;
    }
  }
#endif

#if defined(XP_MACOSX)
  if (aBlockedOS == OperatingSystem::OSX) {
    // We do want even "unknown" aSystemOS to fall under "all OS X"
    return true;
  }
#endif

  return aSystemOS == aBlockedOS;
}

inline bool MatchingBattery(BatteryStatus aBatteryStatus, bool aHasBattery) {
  switch (aBatteryStatus) {
    case BatteryStatus::All:
      return true;
    case BatteryStatus::None:
      return !aHasBattery;
    case BatteryStatus::Present:
      return aHasBattery;
  }

  MOZ_ASSERT_UNREACHABLE("bad battery status");
  return false;
}

inline bool MatchingScreenSize(ScreenSizeStatus aScreenStatus,
                               int64_t aScreenPixels) {
  constexpr int64_t kMaxSmallPixels = 2304000;   // 1920x1200
  constexpr int64_t kMaxMediumPixels = 4953600;  // 3440x1440

  switch (aScreenStatus) {
    case ScreenSizeStatus::All:
      return true;
    case ScreenSizeStatus::Small:
      return aScreenPixels <= kMaxSmallPixels;
    case ScreenSizeStatus::SmallAndMedium:
      return aScreenPixels <= kMaxMediumPixels;
    case ScreenSizeStatus::Medium:
      return aScreenPixels > kMaxSmallPixels &&
             aScreenPixels <= kMaxMediumPixels;
    case ScreenSizeStatus::MediumAndLarge:
      return aScreenPixels > kMaxSmallPixels;
    case ScreenSizeStatus::Large:
      return aScreenPixels > kMaxMediumPixels;
  }

  MOZ_ASSERT_UNREACHABLE("bad screen status");
  return false;
}

int32_t GfxInfoBase::FindBlocklistedDeviceInList(
    const nsTArray<GfxDriverInfo>& info, nsAString& aSuggestedVersion,
    int32_t aFeature, nsACString& aFailureId, OperatingSystem os,
    bool aForAllowing) {
  int32_t status = nsIGfxInfo::FEATURE_STATUS_UNKNOWN;

  // Some properties are not available on all platforms.
  nsAutoString windowProtocol;
  nsresult rv = GetWindowProtocol(windowProtocol);
  if (NS_FAILED(rv) && rv != NS_ERROR_NOT_IMPLEMENTED) {
    return 0;
  }

  bool hasBattery = false;
  rv = GetHasBattery(&hasBattery);
  if (NS_FAILED(rv) && rv != NS_ERROR_NOT_IMPLEMENTED) {
    return 0;
  }

  uint32_t osBuild = OperatingSystemBuild();

  // Get the adapters once then reuse below
  nsAutoString adapterVendorID[2];
  nsAutoString adapterDeviceID[2];
  nsAutoString adapterDriverVendor[2];
  nsAutoString adapterDriverVersionString[2];
  bool adapterInfoFailed[2];

  adapterInfoFailed[0] =
      (NS_FAILED(GetAdapterVendorID(adapterVendorID[0])) ||
       NS_FAILED(GetAdapterDeviceID(adapterDeviceID[0])) ||
       NS_FAILED(GetAdapterDriverVendor(adapterDriverVendor[0])) ||
       NS_FAILED(GetAdapterDriverVersion(adapterDriverVersionString[0])));
  adapterInfoFailed[1] =
      (NS_FAILED(GetAdapterVendorID2(adapterVendorID[1])) ||
       NS_FAILED(GetAdapterDeviceID2(adapterDeviceID[1])) ||
       NS_FAILED(GetAdapterDriverVendor2(adapterDriverVendor[1])) ||
       NS_FAILED(GetAdapterDriverVersion2(adapterDriverVersionString[1])));
  // No point in going on if we don't have adapter info
  if (adapterInfoFailed[0] && adapterInfoFailed[1]) {
    return 0;
  }

#if defined(XP_WIN) || defined(ANDROID) || defined(MOZ_WIDGET_GTK)
  uint64_t driverVersion[2] = {0, 0};
  if (!adapterInfoFailed[0]) {
    ParseDriverVersion(adapterDriverVersionString[0], &driverVersion[0]);
  }
  if (!adapterInfoFailed[1]) {
    ParseDriverVersion(adapterDriverVersionString[1], &driverVersion[1]);
  }
#endif

  uint32_t i = 0;
  for (; i < info.Length(); i++) {
    // If the status is FEATURE_ALLOW_*, then it is for the allowlist, not
    // blocklisting. Only consider entries for our search mode.
    if (MatchingAllowStatus(info[i].mFeatureStatus) != aForAllowing) {
      continue;
    }

    // If we don't have the info for this GPU, no need to check further.
    // It is unclear that we would ever have a mixture of 1st and 2nd
    // GPU, but leaving the code in for that possibility for now.
    // (Actually, currently mGpu2 will never be true, so this can
    // be optimized out.)
    uint32_t infoIndex = info[i].mGpu2 ? 1 : 0;
    if (adapterInfoFailed[infoIndex]) {
      continue;
    }

    // Do the operating system check first, no point in getting the driver
    // info if we won't need to use it.
    if (!MatchingOperatingSystems(info[i].mOperatingSystem, os, osBuild)) {
      continue;
    }

    if (info[i].mOperatingSystemVersion &&
        info[i].mOperatingSystemVersion != OperatingSystemVersion()) {
      continue;
    }

    if (!MatchingBattery(info[i].mBattery, hasBattery)) {
      continue;
    }

    if (!MatchingScreenSize(info[i].mScreen, mScreenPixels)) {
      continue;
    }

    if (!DoesWindowProtocolMatch(info[i].mWindowProtocol, windowProtocol)) {
      continue;
    }

    if (!DoesVendorMatch(info[i].mAdapterVendor, adapterVendorID[infoIndex])) {
      continue;
    }

    if (!DoesDriverVendorMatch(info[i].mDriverVendor,
                               adapterDriverVendor[infoIndex])) {
      continue;
    }

    if (info[i].mDevices && !info[i].mDevices->IsEmpty()) {
      nsresult rv = info[i].mDevices->Contains(adapterDeviceID[infoIndex]);
      if (rv == NS_ERROR_NOT_AVAILABLE) {
        // Not found
        continue;
      }
      if (rv != NS_OK) {
        // Failed to search, allowlist should not match, blocklist should match
        // for safety reasons
        if (aForAllowing) {
          continue;
        }
        break;
      }
    }

    bool match = false;

    if (!info[i].mHardware.IsEmpty() && !info[i].mHardware.Equals(Hardware())) {
      continue;
    }
    if (!info[i].mModel.IsEmpty() && !info[i].mModel.Equals(Model())) {
      continue;
    }
    if (!info[i].mProduct.IsEmpty() && !info[i].mProduct.Equals(Product())) {
      continue;
    }
    if (!info[i].mManufacturer.IsEmpty() &&
        !info[i].mManufacturer.Equals(Manufacturer())) {
      continue;
    }

#if defined(XP_WIN) || defined(ANDROID) || defined(MOZ_WIDGET_GTK)
    switch (info[i].mComparisonOp) {
      case DRIVER_LESS_THAN:
        match = driverVersion[infoIndex] < info[i].mDriverVersion;
        break;
      case DRIVER_BUILD_ID_LESS_THAN:
        match = (driverVersion[infoIndex] & 0xFFFF) < info[i].mDriverVersion;
        break;
      case DRIVER_LESS_THAN_OR_EQUAL:
        match = driverVersion[infoIndex] <= info[i].mDriverVersion;
        break;
      case DRIVER_BUILD_ID_LESS_THAN_OR_EQUAL:
        match = (driverVersion[infoIndex] & 0xFFFF) <= info[i].mDriverVersion;
        break;
      case DRIVER_GREATER_THAN:
        match = driverVersion[infoIndex] > info[i].mDriverVersion;
        break;
      case DRIVER_GREATER_THAN_OR_EQUAL:
        match = driverVersion[infoIndex] >= info[i].mDriverVersion;
        break;
      case DRIVER_EQUAL:
        match = driverVersion[infoIndex] == info[i].mDriverVersion;
        break;
      case DRIVER_NOT_EQUAL:
        match = driverVersion[infoIndex] != info[i].mDriverVersion;
        break;
      case DRIVER_BETWEEN_EXCLUSIVE:
        match = driverVersion[infoIndex] > info[i].mDriverVersion &&
                driverVersion[infoIndex] < info[i].mDriverVersionMax;
        break;
      case DRIVER_BETWEEN_INCLUSIVE:
        match = driverVersion[infoIndex] >= info[i].mDriverVersion &&
                driverVersion[infoIndex] <= info[i].mDriverVersionMax;
        break;
      case DRIVER_BETWEEN_INCLUSIVE_START:
        match = driverVersion[infoIndex] >= info[i].mDriverVersion &&
                driverVersion[infoIndex] < info[i].mDriverVersionMax;
        break;
      case DRIVER_COMPARISON_IGNORED:
        // We don't have a comparison op, so we match everything.
        match = true;
        break;
      default:
        NS_WARNING("Bogus op in GfxDriverInfo");
        break;
    }
#else
    // We don't care what driver version it was. We only check OS version and if
    // the device matches.
    match = true;
#endif

    if (match || info[i].mDriverVersion == GfxDriverInfo::allDriverVersions) {
      if (info[i].mFeature == GfxDriverInfo::allFeatures ||
          info[i].mFeature == aFeature ||
          (info[i].mFeature == GfxDriverInfo::optionalFeatures &&
           OnlyAllowFeatureOnKnownConfig(aFeature))) {
        status = info[i].mFeatureStatus;
        if (!info[i].mRuleId.IsEmpty()) {
          aFailureId = info[i].mRuleId.get();
        } else {
          aFailureId = "FEATURE_FAILURE_DL_BLOCKLIST_NO_ID";
        }
        break;
      }
    }
  }

#if defined(XP_WIN)
  // As a very special case, we block D2D on machines with an NVidia 310M GPU
  // as either the primary or secondary adapter.  D2D is also blocked when the
  // NV 310M is the primary adapter (using the standard blocklisting mechanism).
  // If the primary GPU already matched something in the blocklist then we
  // ignore this special rule.  See bug 1008759.
  if (status == nsIGfxInfo::FEATURE_STATUS_UNKNOWN &&
      (aFeature == nsIGfxInfo::FEATURE_DIRECT2D)) {
    if (!adapterInfoFailed[1]) {
      nsAString& nvVendorID =
          (nsAString&)GfxDriverInfo::GetDeviceVendor(DeviceVendor::NVIDIA);
      const nsString nv310mDeviceId = u"0x0A70"_ns;
      if (nvVendorID.Equals(adapterVendorID[1],
                            nsCaseInsensitiveStringComparator) &&
          nv310mDeviceId.Equals(adapterDeviceID[1],
                                nsCaseInsensitiveStringComparator)) {
        status = nsIGfxInfo::FEATURE_BLOCKED_DEVICE;
        aFailureId = "FEATURE_FAILURE_D2D_NV310M_BLOCK";
      }
    }
  }

  // Depends on Windows driver versioning. We don't pass a GfxDriverInfo object
  // back to the Windows handler, so we must handle this here.
  if (status == FEATURE_BLOCKED_DRIVER_VERSION) {
    if (info[i].mSuggestedVersion) {
      aSuggestedVersion.AppendPrintf("%s", info[i].mSuggestedVersion);
    } else if (info[i].mComparisonOp == DRIVER_LESS_THAN &&
               info[i].mDriverVersion != GfxDriverInfo::allDriverVersions) {
      aSuggestedVersion.AppendPrintf(
          "%lld.%lld.%lld.%lld",
          (info[i].mDriverVersion & 0xffff000000000000) >> 48,
          (info[i].mDriverVersion & 0x0000ffff00000000) >> 32,
          (info[i].mDriverVersion & 0x00000000ffff0000) >> 16,
          (info[i].mDriverVersion & 0x000000000000ffff));
    }
  }
#endif

  return status;
}

void GfxInfoBase::SetFeatureStatus(nsTArray<gfx::GfxInfoFeatureStatus>&& aFS) {
  MOZ_ASSERT(!sFeatureStatus);
  InitFeatureStatus(new nsTArray<gfx::GfxInfoFeatureStatus>(std::move(aFS)));
}

bool GfxInfoBase::DoesWindowProtocolMatch(
    const nsAString& aBlocklistWindowProtocol,
    const nsAString& aWindowProtocol) {
  return aBlocklistWindowProtocol.Equals(aWindowProtocol,
                                         nsCaseInsensitiveStringComparator) ||
         aBlocklistWindowProtocol.Equals(
             GfxDriverInfo::GetWindowProtocol(WindowProtocol::All),
             nsCaseInsensitiveStringComparator);
}

bool GfxInfoBase::DoesVendorMatch(const nsAString& aBlocklistVendor,
                                  const nsAString& aAdapterVendor) {
  return aBlocklistVendor.Equals(aAdapterVendor,
                                 nsCaseInsensitiveStringComparator) ||
         aBlocklistVendor.Equals(
             GfxDriverInfo::GetDeviceVendor(DeviceVendor::All),
             nsCaseInsensitiveStringComparator);
}

bool GfxInfoBase::DoesDriverVendorMatch(const nsAString& aBlocklistVendor,
                                        const nsAString& aDriverVendor) {
  return aBlocklistVendor.Equals(aDriverVendor,
                                 nsCaseInsensitiveStringComparator) ||
         aBlocklistVendor.Equals(
             GfxDriverInfo::GetDriverVendor(DriverVendor::All),
             nsCaseInsensitiveStringComparator);
}

bool GfxInfoBase::IsFeatureAllowlisted(int32_t aFeature) const {
  return aFeature == nsIGfxInfo::FEATURE_HW_DECODED_VIDEO_ZERO_COPY;
}

nsresult GfxInfoBase::GetFeatureStatusImpl(
    int32_t aFeature, int32_t* aStatus, nsAString& aSuggestedVersion,
    const nsTArray<GfxDriverInfo>& aDriverInfo, nsACString& aFailureId,
    OperatingSystem* aOS /* = nullptr */) {
  if (aFeature <= 0) {
    gfxWarning() << "Invalid feature <= 0";
    return NS_OK;
  }

  if (*aStatus != nsIGfxInfo::FEATURE_STATUS_UNKNOWN) {
    // Terminate now with the status determined by the derived type (OS-specific
    // code).
    return NS_OK;
  }

  if (sShutdownOccurred) {
    // This is futile; we've already commenced shutdown and our blocklists have
    // been deleted. We may want to look into resurrecting the blocklist instead
    // but for now, just don't even go there.
    return NS_OK;
  }

  // Ensure any additional initialization required is complete.
  GetData();

  // If an operating system was provided by the derived GetFeatureStatusImpl,
  // grab it here. Otherwise, the OS is unknown.
  OperatingSystem os = (aOS ? *aOS : OperatingSystem::Unknown);

  nsAutoString adapterVendorID;
  nsAutoString adapterDeviceID;
  nsAutoString adapterDriverVersionString;
  if (NS_FAILED(GetAdapterVendorID(adapterVendorID)) ||
      NS_FAILED(GetAdapterDeviceID(adapterDeviceID)) ||
      NS_FAILED(GetAdapterDriverVersion(adapterDriverVersionString))) {
    if (OnlyAllowFeatureOnKnownConfig(aFeature)) {
      aFailureId = "FEATURE_FAILURE_CANT_RESOLVE_ADAPTER";
      *aStatus = nsIGfxInfo::FEATURE_BLOCKED_DEVICE;
    } else {
      *aStatus = nsIGfxInfo::FEATURE_STATUS_OK;
    }
    return NS_OK;
  }

  // We only check either the given blocklist, or the static list, as given.
  int32_t status;
  if (aDriverInfo.Length()) {
    status =
        FindBlocklistedDeviceInList(aDriverInfo, aSuggestedVersion, aFeature,
                                    aFailureId, os, /* aForAllowing */ false);
  } else {
    if (!sDriverInfo) {
      sDriverInfo = new nsTArray<GfxDriverInfo>();
    }
    status = FindBlocklistedDeviceInList(GetGfxDriverInfo(), aSuggestedVersion,
                                         aFeature, aFailureId, os,
                                         /* aForAllowing */ false);
  }

  if (status == nsIGfxInfo::FEATURE_STATUS_UNKNOWN) {
    if (IsFeatureAllowlisted(aFeature)) {
      // This feature is actually using the allowlist; that means after we pass
      // the blocklist to prevent us explicitly from getting the feature, we now
      // need to check the allowlist to ensure we are allowed to get it in the
      // first place.
      if (aDriverInfo.Length()) {
        status = FindBlocklistedDeviceInList(aDriverInfo, aSuggestedVersion,
                                             aFeature, aFailureId, os,
                                             /* aForAllowing */ true);
      } else {
        status = FindBlocklistedDeviceInList(
            GetGfxDriverInfo(), aSuggestedVersion, aFeature, aFailureId, os,
            /* aForAllowing */ true);
      }

      if (status == nsIGfxInfo::FEATURE_STATUS_UNKNOWN) {
        status = nsIGfxInfo::FEATURE_DENIED;
      }
    } else {
      // It's now done being processed. It's safe to set the status to
      // STATUS_OK.
      status = nsIGfxInfo::FEATURE_STATUS_OK;
    }
  }

  *aStatus = status;
  return NS_OK;
}

NS_IMETHODIMP
GfxInfoBase::GetFeatureSuggestedDriverVersion(int32_t aFeature,
                                              nsAString& aVersion) {
  nsCString version;
  if (GetPrefValueForDriverVersion(version)) {
    aVersion = NS_ConvertASCIItoUTF16(version);
    return NS_OK;
  }

  int32_t status;
  nsCString discardFailureId;
  nsTArray<GfxDriverInfo> driverInfo;
  return GetFeatureStatusImpl(aFeature, &status, aVersion, driverInfo,
                              discardFailureId);
}

void GfxInfoBase::EvaluateDownloadedBlocklist(
    nsTArray<GfxDriverInfo>& aDriverInfo) {
  // If the list is empty, then we don't actually want to call
  // GetFeatureStatusImpl since we will use the static list instead. In that
  // case, all we want to do is make sure the pref is removed.
  if (aDriverInfo.IsEmpty()) {
    gfxCriticalNoteOnce << "Evaluate empty downloaded blocklist";
    return;
  }

  OperatingSystem os = GetOperatingSystem();

  // For every feature we know about, we evaluate whether this blocklist has a
  // non-STATUS_OK status. If it does, we set the pref we evaluate in
  // GetFeatureStatus above, so we don't need to hold on to this blocklist
  // anywhere permanent.
  for (int feature = 1; feature <= nsIGfxInfo::FEATURE_MAX_VALUE; ++feature) {
    int32_t status = nsIGfxInfo::FEATURE_STATUS_UNKNOWN;
    nsCString failureId;
    nsAutoString suggestedVersion;

    // Note that we are careful to call the base class method since we only want
    // to evaluate the downloadable blocklist for these prefs.
    MOZ_ALWAYS_TRUE(NS_SUCCEEDED(GfxInfoBase::GetFeatureStatusImpl(
        feature, &status, suggestedVersion, aDriverInfo, failureId, &os)));

    switch (status) {
      default:
        MOZ_FALLTHROUGH_ASSERT("Unhandled feature status!");
      case nsIGfxInfo::FEATURE_STATUS_UNKNOWN:
        // This may be returned during shutdown or for invalid features.
      case nsIGfxInfo::FEATURE_ALLOW_ALWAYS:
      case nsIGfxInfo::FEATURE_ALLOW_QUALIFIED:
      case nsIGfxInfo::FEATURE_DENIED:
        // We cannot use the downloadable blocklist to control the allowlist.
        // If a feature is allowlisted, then we should also ignore DENIED
        // statuses from GetFeatureStatusImpl because we don't check the
        // static list when and this is an expected value. If we wish to
        // override the allowlist, it is as simple as creating a normal
        // blocklist rule with a BLOCKED* status code.
      case nsIGfxInfo::FEATURE_STATUS_OK:
        RemovePrefForFeature(feature);
        break;

      case nsIGfxInfo::FEATURE_BLOCKED_DRIVER_VERSION:
        if (!suggestedVersion.IsEmpty()) {
          SetPrefValueForDriverVersion(suggestedVersion);
        } else {
          RemovePrefForDriverVersion();
        }
        [[fallthrough]];

      case nsIGfxInfo::FEATURE_BLOCKED_MISMATCHED_VERSION:
      case nsIGfxInfo::FEATURE_BLOCKED_DEVICE:
      case nsIGfxInfo::FEATURE_DISCOURAGED:
      case nsIGfxInfo::FEATURE_BLOCKED_OS_VERSION:
      case nsIGfxInfo::FEATURE_BLOCKED_PLATFORM_TEST:
        SetPrefValueForFeature(feature, status, failureId);
        break;
    }
  }
}

NS_IMETHODIMP_(void)
GfxInfoBase::LogFailure(const nsACString& failure) {
  // gfxCriticalError has a mutex lock of its own, so we may not actually
  // need this lock. ::GetFailures() accesses the data but the LogForwarder
  // will not return the copy of the logs unless it can get the same lock
  // that gfxCriticalError uses.  Still, that is so much of an implementation
  // detail that it's nicer to just add an extra lock here and in
  // ::GetFailures()
  MutexAutoLock lock(mMutex);

  // By default, gfxCriticalError asserts; make it not assert in this case.
  gfxCriticalError(CriticalLog::DefaultOptions(false))
      << "(LF) " << failure.BeginReading();
}

NS_IMETHODIMP GfxInfoBase::GetFailures(nsTArray<int32_t>& indices,
                                       nsTArray<nsCString>& failures) {
  MutexAutoLock lock(mMutex);

  LogForwarder* logForwarder = Factory::GetLogForwarder();
  if (!logForwarder) {
    return NS_ERROR_UNEXPECTED;
  }

  // There are two string copies in this method, starting with this one. We are
  // assuming this is not a big deal, as the size of the array should be small
  // and the strings in it should be small as well (the error messages in the
  // code.)  The second copy happens with the AppendElement() calls.
  // Technically, we don't need the mutex lock after the StringVectorCopy()
  // call.
  LoggingRecord loggedStrings = logForwarder->LoggingRecordCopy();
  LoggingRecord::const_iterator it;
  for (it = loggedStrings.begin(); it != loggedStrings.end(); ++it) {
    failures.AppendElement(nsDependentCSubstring(std::get<1>(*it).c_str(),
                                                 std::get<1>(*it).size()));
    indices.AppendElement(std::get<0>(*it));
  }

  return NS_OK;
}

nsTArray<GfxInfoCollectorBase*>* sCollectors;

static void InitCollectors() {
  if (!sCollectors) sCollectors = new nsTArray<GfxInfoCollectorBase*>;
}

nsresult GfxInfoBase::GetInfo(JSContext* aCx,
                              JS::MutableHandle<JS::Value> aResult) {
  InitCollectors();
  InfoObject obj(aCx);

  for (uint32_t i = 0; i < sCollectors->Length(); i++) {
    (*sCollectors)[i]->GetInfo(obj);
  }

  // Some example property definitions
  // obj.DefineProperty("wordCacheSize", gfxTextRunWordCache::Count());
  // obj.DefineProperty("renderer", mRendererIDsString);
  // obj.DefineProperty("five", 5);

  if (!obj.mOk) {
    return NS_ERROR_FAILURE;
  }

  aResult.setObject(*obj.mObj);
  return NS_OK;
}

nsAutoCString gBaseAppVersion;

const nsCString& GfxInfoBase::GetApplicationVersion() {
  static bool versionInitialized = false;
  if (!versionInitialized) {
    // If we fail to get the version, we will not try again.
    versionInitialized = true;

    // Get the version from xpcom/system/nsIXULAppInfo.idl
    nsCOMPtr<nsIXULAppInfo> app = do_GetService("@mozilla.org/xre/app-info;1");
    if (app) {
      app->GetVersion(gBaseAppVersion);
    }
  }
  return gBaseAppVersion;
}

/* static */ bool GfxInfoBase::OnlyAllowFeatureOnKnownConfig(int32_t aFeature) {
  switch (aFeature) {
    // The GPU process doesn't need hardware acceleration and can run on
    // devices that we normally block from not being on our whitelist.
    case nsIGfxInfo::FEATURE_GPU_PROCESS:
      return kIsAndroid;
    // We can mostly assume that ANGLE will work
    case nsIGfxInfo::FEATURE_DIRECT3D_11_ANGLE:
    // Remote WebGL is needed for Win32k Lockdown, so it should be enabled
    // regardless of HW support or not
    case nsIGfxInfo::FEATURE_ALLOW_WEBGL_OUT_OF_PROCESS:
    // Backdrop filter should generally work, especially if we fall back to
    // Software WebRender because of an unknown vendor.
    case nsIGfxInfo::FEATURE_BACKDROP_FILTER:
      return false;
    default:
      return true;
  }
}

void GfxInfoBase::AddCollector(GfxInfoCollectorBase* collector) {
  InitCollectors();
  sCollectors->AppendElement(collector);
}

void GfxInfoBase::RemoveCollector(GfxInfoCollectorBase* collector) {
  InitCollectors();
  for (uint32_t i = 0; i < sCollectors->Length(); i++) {
    if ((*sCollectors)[i] == collector) {
      sCollectors->RemoveElementAt(i);
      break;
    }
  }
  if (sCollectors->IsEmpty()) {
    delete sCollectors;
    sCollectors = nullptr;
  }
}

static void AppendMonitor(JSContext* aCx, widget::Screen& aScreen,
                          JS::Handle<JSObject*> aOutArray, int32_t aIndex) {
  JS::Rooted<JSObject*> obj(aCx, JS_NewPlainObject(aCx));

  auto screenSize = aScreen.GetRect().Size();

  JS::Rooted<JS::Value> screenWidth(aCx, JS::Int32Value(screenSize.width));
  JS_SetProperty(aCx, obj, "screenWidth", screenWidth);

  JS::Rooted<JS::Value> screenHeight(aCx, JS::Int32Value(screenSize.height));
  JS_SetProperty(aCx, obj, "screenHeight", screenHeight);

  // XXX Just preserving behavior since this is exposed to telemetry, but we
  // could consider including this everywhere.
#ifdef XP_MACOSX
  JS::Rooted<JS::Value> scale(
      aCx, JS::NumberValue(aScreen.GetContentsScaleFactor()));
  JS_SetProperty(aCx, obj, "scale", scale);
#endif

#ifdef XP_WIN
  JS::Rooted<JS::Value> refreshRate(aCx,
                                    JS::Int32Value(aScreen.GetRefreshRate()));
  JS_SetProperty(aCx, obj, "refreshRate", refreshRate);

  JS::Rooted<JS::Value> pseudoDisplay(
      aCx, JS::BooleanValue(aScreen.GetIsPseudoDisplay()));
  JS_SetProperty(aCx, obj, "pseudoDisplay", pseudoDisplay);
#endif

  JS::Rooted<JS::Value> element(aCx, JS::ObjectValue(*obj));
  JS_SetElement(aCx, aOutArray, aIndex, element);
}

nsresult GfxInfoBase::FindMonitors(JSContext* aCx,
                                   JS::Handle<JSObject*> aOutArray) {
  int32_t index = 0;
  auto& sm = ScreenManager::GetSingleton();
  for (auto& screen : sm.CurrentScreenList()) {
    AppendMonitor(aCx, *screen, aOutArray, index++);
  }

  if (index == 0) {
    // Ensure we return at least one monitor, this is needed for xpcshell.
    RefPtr<Screen> screen = sm.GetPrimaryScreen();
    AppendMonitor(aCx, *screen, aOutArray, index++);
  }

  return NS_OK;
}

NS_IMETHODIMP
GfxInfoBase::GetMonitors(JSContext* aCx, JS::MutableHandle<JS::Value> aResult) {
  JS::Rooted<JSObject*> array(aCx, JS::NewArrayObject(aCx, 0));

  nsresult rv = FindMonitors(aCx, array);
  if (NS_FAILED(rv)) {
    return rv;
  }

  aResult.setObject(*array);
  return NS_OK;
}

static inline bool SetJSPropertyString(JSContext* aCx,
                                       JS::Handle<JSObject*> aObj,
                                       const char* aProp, const char* aString) {
  JS::Rooted<JSString*> str(aCx, JS_NewStringCopyZ(aCx, aString));
  if (!str) {
    return false;
  }

  JS::Rooted<JS::Value> val(aCx, JS::StringValue(str));
  return JS_SetProperty(aCx, aObj, aProp, val);
}

template <typename T>
static inline bool AppendJSElement(JSContext* aCx, JS::Handle<JSObject*> aObj,
                                   const T& aValue) {
  uint32_t index;
  if (!JS::GetArrayLength(aCx, aObj, &index)) {
    return false;
  }
  return JS_SetElement(aCx, aObj, index, aValue);
}

nsresult GfxInfoBase::GetFeatures(JSContext* aCx,
                                  JS::MutableHandle<JS::Value> aOut) {
  JS::Rooted<JSObject*> obj(aCx, JS_NewPlainObject(aCx));
  if (!obj) {
    return NS_ERROR_OUT_OF_MEMORY;
  }
  aOut.setObject(*obj);

  layers::LayersBackend backend =
      gfxPlatform::Initialized()
          ? gfxPlatform::GetPlatform()->GetCompositorBackend()
          : layers::LayersBackend::LAYERS_NONE;
  const char* backendName = layers::GetLayersBackendName(backend);
  SetJSPropertyString(aCx, obj, "compositor", backendName);

  // If graphics isn't initialized yet, just stop now.
  if (!gfxPlatform::Initialized()) {
    return NS_OK;
  }

  DescribeFeatures(aCx, obj);
  return NS_OK;
}

nsresult GfxInfoBase::GetFeatureLog(JSContext* aCx,
                                    JS::MutableHandle<JS::Value> aOut) {
  JS::Rooted<JSObject*> containerObj(aCx, JS_NewPlainObject(aCx));
  if (!containerObj) {
    return NS_ERROR_OUT_OF_MEMORY;
  }
  aOut.setObject(*containerObj);

  JS::Rooted<JSObject*> featureArray(aCx, JS::NewArrayObject(aCx, 0));
  if (!featureArray) {
    return NS_ERROR_OUT_OF_MEMORY;
  }

  // Collect features.
  gfxConfig::ForEachFeature([&](const char* aName, const char* aDescription,
                                FeatureState& aFeature) -> void {
    JS::Rooted<JSObject*> obj(aCx, JS_NewPlainObject(aCx));
    if (!obj) {
      return;
    }
    if (!SetJSPropertyString(aCx, obj, "name", aName) ||
        !SetJSPropertyString(aCx, obj, "description", aDescription) ||
        !SetJSPropertyString(aCx, obj, "status",
                             FeatureStatusToString(aFeature.GetValue()))) {
      return;
    }

    JS::Rooted<JS::Value> log(aCx);
    if (!BuildFeatureStateLog(aCx, aFeature, &log)) {
      return;
    }
    if (!JS_SetProperty(aCx, obj, "log", log)) {
      return;
    }

    if (!AppendJSElement(aCx, featureArray, obj)) {
      return;
    }
  });

  JS::Rooted<JSObject*> fallbackArray(aCx, JS::NewArrayObject(aCx, 0));
  if (!fallbackArray) {
    return NS_ERROR_OUT_OF_MEMORY;
  }

  // Collect fallbacks.
  gfxConfig::ForEachFallback(
      [&](const char* aName, const char* aMessage) -> void {
        JS::Rooted<JSObject*> obj(aCx, JS_NewPlainObject(aCx));
        if (!obj) {
          return;
        }

        if (!SetJSPropertyString(aCx, obj, "name", aName) ||
            !SetJSPropertyString(aCx, obj, "message", aMessage)) {
          return;
        }

        if (!AppendJSElement(aCx, fallbackArray, obj)) {
          return;
        }
      });

  JS::Rooted<JS::Value> val(aCx);

  val = JS::ObjectValue(*featureArray);
  JS_SetProperty(aCx, containerObj, "features", val);

  val = JS::ObjectValue(*fallbackArray);
  JS_SetProperty(aCx, containerObj, "fallbacks", val);

  return NS_OK;
}

bool GfxInfoBase::BuildFeatureStateLog(JSContext* aCx,
                                       const FeatureState& aFeature,
                                       JS::MutableHandle<JS::Value> aOut) {
  JS::Rooted<JSObject*> log(aCx, JS::NewArrayObject(aCx, 0));
  if (!log) {
    return false;
  }
  aOut.setObject(*log);

  aFeature.ForEachStatusChange([&](const char* aType, FeatureStatus aStatus,
                                   const char* aMessage,
                                   const nsCString& aFailureId) -> void {
    JS::Rooted<JSObject*> obj(aCx, JS_NewPlainObject(aCx));
    if (!obj) {
      return;
    }

    if (!SetJSPropertyString(aCx, obj, "type", aType) ||
        !SetJSPropertyString(aCx, obj, "status",
                             FeatureStatusToString(aStatus)) ||
        (!aFailureId.IsEmpty() &&
         !SetJSPropertyString(aCx, obj, "failureId", aFailureId.get())) ||
        (aMessage && !SetJSPropertyString(aCx, obj, "message", aMessage))) {
      return;
    }

    if (!AppendJSElement(aCx, log, obj)) {
      return;
    }
  });

  return true;
}

void GfxInfoBase::DescribeFeatures(JSContext* aCx, JS::Handle<JSObject*> aObj) {
  JS::Rooted<JSObject*> obj(aCx);

  gfx::FeatureState& hwCompositing =
      gfxConfig::GetFeature(gfx::Feature::HW_COMPOSITING);
  InitFeatureObject(aCx, aObj, "hwCompositing", hwCompositing, &obj);

  gfx::FeatureState& gpuProcess =
      gfxConfig::GetFeature(gfx::Feature::GPU_PROCESS);
  InitFeatureObject(aCx, aObj, "gpuProcess", gpuProcess, &obj);

  gfx::FeatureState& webrender = gfxConfig::GetFeature(gfx::Feature::WEBRENDER);
  InitFeatureObject(aCx, aObj, "webrender", webrender, &obj);

  gfx::FeatureState& wrCompositor =
      gfxConfig::GetFeature(gfx::Feature::WEBRENDER_COMPOSITOR);
  InitFeatureObject(aCx, aObj, "wrCompositor", wrCompositor, &obj);

  gfx::FeatureState& openglCompositing =
      gfxConfig::GetFeature(gfx::Feature::OPENGL_COMPOSITING);
  InitFeatureObject(aCx, aObj, "openglCompositing", openglCompositing, &obj);

  gfx::FeatureState& omtp = gfxConfig::GetFeature(gfx::Feature::OMTP);
  InitFeatureObject(aCx, aObj, "omtp", omtp, &obj);
}

bool GfxInfoBase::InitFeatureObject(JSContext* aCx,
                                    JS::Handle<JSObject*> aContainer,
                                    const char* aName,
                                    mozilla::gfx::FeatureState& aFeatureState,
                                    JS::MutableHandle<JSObject*> aOutObj) {
  JS::Rooted<JSObject*> obj(aCx, JS_NewPlainObject(aCx));
  if (!obj) {
    return false;
  }

  nsCString status = aFeatureState.GetStatusAndFailureIdString();

  JS::Rooted<JSString*> str(aCx, JS_NewStringCopyZ(aCx, status.get()));
  JS::Rooted<JS::Value> val(aCx, JS::StringValue(str));
  JS_SetProperty(aCx, obj, "status", val);

  // Add the feature object to the container.
  {
    JS::Rooted<JS::Value> val(aCx, JS::ObjectValue(*obj));
    JS_SetProperty(aCx, aContainer, aName, val);
  }

  aOutObj.set(obj);
  return true;
}

nsresult GfxInfoBase::GetActiveCrashGuards(JSContext* aCx,
                                           JS::MutableHandle<JS::Value> aOut) {
  JS::Rooted<JSObject*> array(aCx, JS::NewArrayObject(aCx, 0));
  if (!array) {
    return NS_ERROR_OUT_OF_MEMORY;
  }
  aOut.setObject(*array);

  DriverCrashGuard::ForEachActiveCrashGuard(
      [&](const char* aName, const char* aPrefName) -> void {
        JS::Rooted<JSObject*> obj(aCx, JS_NewPlainObject(aCx));
        if (!obj) {
          return;
        }
        if (!SetJSPropertyString(aCx, obj, "type", aName)) {
          return;
        }
        if (!SetJSPropertyString(aCx, obj, "prefName", aPrefName)) {
          return;
        }
        if (!AppendJSElement(aCx, array, obj)) {
          return;
        }
      });

  return NS_OK;
}

NS_IMETHODIMP
GfxInfoBase::GetTargetFrameRate(uint32_t* aTargetFrameRate) {
  *aTargetFrameRate = gfxPlatform::TargetFrameRate();
  return NS_OK;
}

NS_IMETHODIMP
GfxInfoBase::GetCodecSupportInfo(nsACString& aCodecSupportInfo) {
  aCodecSupportInfo.Assign(gfx::gfxVars::CodecSupportInfo());
  return NS_OK;
}

NS_IMETHODIMP
GfxInfoBase::GetIsHeadless(bool* aIsHeadless) {
  *aIsHeadless = gfxPlatform::IsHeadless();
  return NS_OK;
}

#if defined(MOZ_WIDGET_ANDROID)

const char* chromebookProductList[] = {
    "asuka",    "asurada",   "atlas",    "auron",    "banjo",     "banon",
    "bob",      "brask",     "brya",     "buddy",    "butterfly", "candy",
    "caroline", "cave",      "celes",    "chell",    "cherry",    "clapper",
    "coral",    "corsola",   "cyan",     "daisy",    "dedede",    "drallion",
    "edgar",    "elm",       "enguarde", "eve",      "expresso",  "falco",
    "fizz",     "gandof",    "glimmer",  "gnawty",   "grunt",     "guado",
    "guybrush", "hana",      "hatch",    "heli",     "jacuzzi",   "kalista",
    "kefka",    "kevin",     "kip",      "kukui",    "lars",      "leon",
    "link",     "lulu",      "lumpy",    "mccloud",  "monroe",    "nami",
    "nautilus", "ninja",     "nissa",    "nocturne", "nyan",      "octopus",
    "orco",     "panther",   "parrot",   "peach",    "peppy",     "puff",
    "pyro",     "quawks",    "rammus",   "reef",     "reks",      "relm",
    "rikku",    "samus",     "sand",     "sarien",   "scarlet",   "sentry",
    "setzer",   "skyrim",    "snappy",   "soraka",   "squawks",   "staryu",
    "stout",    "strongbad", "stumpy",   "sumo",     "swanky",    "terra",
    "tidus",    "tricky",    "trogdor",  "ultima",   "veyron",    "volteer",
    "winky",    "wizpig",    "wolf",     "x86",      "zako",      "zork"};

bool ProductIsChromebook(nsCString product) {
  size_t result;
  return BinarySearchIf(
      chromebookProductList, 0, ArrayLength(chromebookProductList),
      [&](const char* const aValue) -> int {
        return strcmp(product.get(), aValue);
      },
      &result);
}
#endif

using Device = nsIGfxInfo::FontVisibilityDeviceDetermination;
static StaticAutoPtr<std::pair<Device, nsString>> ret;

std::pair<Device, nsString>* GfxInfoBase::GetFontVisibilityDeterminationPair() {
  if (!ret) {
    ret = new std::pair<Device, nsString>();
    ret->first = Device::Unassigned;
    ret->second = u""_ns;
    ClearOnShutdown(&ret);
  }

  if (ret->first != Device::Unassigned) {
    return ret;
  }

#if defined(MOZ_WIDGET_ANDROID)
  auto androidReleaseVersion = strtol(
      java::sdk::Build::VERSION::RELEASE()->ToCString().get(), nullptr, 10);

  auto androidManufacturer = java::sdk::Build::MANUFACTURER()->ToCString();
  nsContentUtils::ASCIIToLower(androidManufacturer);

  auto androidBrand = java::sdk::Build::BRAND()->ToCString();
  nsContentUtils::ASCIIToLower(androidBrand);

  auto androidModel = java::sdk::Build::MODEL()->ToCString();
  nsContentUtils::ASCIIToLower(androidModel);

  auto androidProduct = java::sdk::Build::PRODUCT()->ToCString();
  nsContentUtils::ASCIIToLower(androidProduct);

  auto androidProductIsChromebook = ProductIsChromebook(androidProduct);

  if (androidReleaseVersion < 4 || androidReleaseVersion > 20) {
    // Something is screwy, oh well.
    ret->second.AppendASCII("Unknown Release Version - ");
    ret->first = Device::Android_Unknown_Release_Version;
  } else if (androidReleaseVersion <= 8) {
    ret->second.AppendASCII("Android <9 - ");
    ret->first = Device::Android_sub_9;
  } else if (androidReleaseVersion <= 11) {
    ret->second.AppendASCII("Android 9-11 - ");
    ret->first = Device::Android_9_11;
  } else if (androidReleaseVersion > 11) {
    ret->second.AppendASCII("Android 12+ - ");
    ret->first = Device::Android_12_plus;
  } else {
    MOZ_CRASH_UNSAFE_PRINTF(
        "Somehow wound up in GetFontVisibilityDeterminationPair with a release "
        "version of %li",
        androidReleaseVersion);
  }

  if (androidManufacturer == "google" && androidModel == androidProduct &&
      androidProductIsChromebook) {
    // Chromebook font set coming later
    ret->second.AppendASCII("Chromebook - ");
    ret->first = Device::Android_Chromebook;
  }
  if (androidBrand == "amazon") {
    // Amazon Fire font set coming later
    ret->second.AppendASCII("Amazon - ");
    ret->first = Device::Android_Amazon;
  }
  if (androidBrand == "peloton") {
    // We don't know how to categorize fonts on this system
    ret->second.AppendASCII("Peloton - ");
    ret->first = Device::Android_Unknown_Peloton;
  }
  if (androidProduct == "vbox86p") {
    ret->second.AppendASCII("vbox - ");
    // We can't categorize fonts when running in an emulator on a Desktop
    ret->first = Device::Android_Unknown_vbox;
  }
  if (androidModel.Find("mitv"_ns) != kNotFound && androidBrand == "xiaomi") {
    // We don't know how to categorize fonts on this system
    ret->second.AppendASCII("mitv - ");
    ret->first = Device::Android_Unknown_mitv;
  }

  ret->second.AppendPrintf(
      "release_version_str=%s, release_version=%li",
      java::sdk::Build::VERSION::RELEASE()->ToCString().get(),
      androidReleaseVersion);
  ret->second.AppendPrintf(
      ", manufacturer=%s, brand=%s, model=%s, product=%s, chromebook=%s",
      androidManufacturer.get(), androidBrand.get(), androidModel.get(),
      androidProduct.get(), androidProductIsChromebook ? "yes" : "no");

#elif defined(XP_LINUX)
  ret->first = Device::Linux_Unknown;

  long versionMajor = 0;
  FILE* fp = fopen("/etc/os-release", "r");
  if (fp) {
    char buf[512];
    while (fgets(buf, sizeof(buf), fp)) {
      if (strncmp(buf, "VERSION_ID=\"", 12) == 0) {
        ret->second.AppendPrintf("VERSION_ID=%.11s", buf + 11);
        versionMajor = strtol(buf + 12, nullptr, 10);
        if (ret->first != Device::Linux_Unknown) {
          break;
        }
      }

      if (strncmp(buf, "ID=", 3) == 0) {
        ret->second.AppendPrintf("ID=%.6s", buf + 3);
        if (strncmp(buf + 3, "ubuntu", 6) == 0) {
          ret->first = Device::Linux_Ubuntu_any;
        } else if (strncmp(buf + 3, "fedora", 6) == 0) {
          ret->first = Device::Linux_Fedora_any;
        }

        if (versionMajor) {
          break;
        }
      }
    }
    fclose(fp);
  }
  if (ret->first == Device::Linux_Ubuntu_any) {
    if (versionMajor == 20) {
      ret->first = Device::Linux_Ubuntu_20;
      ret->second.Insert(u"Ubuntu 20 - ", 0);
    } else if (versionMajor == 22) {
      ret->first = Device::Linux_Ubuntu_22;
      ret->second.Insert(u"Ubuntu 22 - ", 0);
    } else {
      ret->second.Insert(u"Ubuntu Unknown - ", 0);
    }
  } else if (ret->first == Device::Linux_Fedora_any) {
    if (versionMajor == 38) {
      ret->first = Device::Linux_Fedora_38;
      ret->second.Insert(u"Fedora 38 - ", 0);
    } else if (versionMajor == 39) {
      ret->first = Device::Linux_Fedora_39;
      ret->second.Insert(u"Fedora 39 - ", 0);
    } else {
      ret->second.Insert(u"Fedora Unknown - ", 0);
    }
  } else {
    ret->second.Insert(u"Linux Unknown - ", 0);
  }

#elif defined(XP_MACOSX)
  ret->first = Device::MacOS_Platform;
  ret->second.AppendASCII("macOS Platform");
#elif defined(XP_WIN)
  ret->first = Device::Windows_Platform;
  ret->second.AppendASCII("Windows Platform");
#else
  ret->first = Device::Unknown_Platform;
  ret->second.AppendASCII("Unknown Platform");
#endif

  return ret;
}

NS_IMETHODIMP
GfxInfoBase::GetFontVisibilityDetermination(
    Device* aFontVisibilityDetermination) {
  auto ret = GetFontVisibilityDeterminationPair();

  *aFontVisibilityDetermination = ret->first;
  return NS_OK;
}

NS_IMETHODIMP
GfxInfoBase::GetFontVisibilityDeterminationStr(
    nsAString& aFontVisibilityDeterminationStr) {
  auto ret = GetFontVisibilityDeterminationPair();
  aFontVisibilityDeterminationStr.Assign(ret->second);
  return NS_OK;
}

NS_IMETHODIMP
GfxInfoBase::GetContentBackend(nsAString& aContentBackend) {
  BackendType backend = gfxPlatform::GetPlatform()->GetDefaultContentBackend();
  nsString outStr;

  switch (backend) {
    case BackendType::DIRECT2D1_1: {
      outStr.AppendPrintf("Direct2D 1.1");
      break;
    }
    case BackendType::SKIA: {
      outStr.AppendPrintf("Skia");
      break;
    }
    case BackendType::CAIRO: {
      outStr.AppendPrintf("Cairo");
      break;
    }
    default:
      return NS_ERROR_FAILURE;
  }

  aContentBackend.Assign(outStr);
  return NS_OK;
}

NS_IMETHODIMP
GfxInfoBase::GetAzureCanvasBackend(nsAString& aBackend) {
  CopyASCIItoUTF16(mozilla::MakeStringSpan(
                       gfxPlatform::GetPlatform()->GetAzureCanvasBackend()),
                   aBackend);
  return NS_OK;
}

NS_IMETHODIMP
GfxInfoBase::GetAzureContentBackend(nsAString& aBackend) {
  CopyASCIItoUTF16(mozilla::MakeStringSpan(
                       gfxPlatform::GetPlatform()->GetAzureContentBackend()),
                   aBackend);
  return NS_OK;
}

NS_IMETHODIMP
GfxInfoBase::GetUsingGPUProcess(bool* aOutValue) {
  GPUProcessManager* gpu = GPUProcessManager::Get();
  if (!gpu) {
    // Not supported in content processes.
    return NS_ERROR_FAILURE;
  }

  *aOutValue = !!gpu->GetGPUChild();
  return NS_OK;
}

NS_IMETHODIMP
GfxInfoBase::GetUsingRemoteCanvas(bool* aOutValue) {
  *aOutValue = gfx::gfxVars::RemoteCanvasEnabled();
  return NS_OK;
}

NS_IMETHODIMP
GfxInfoBase::GetUsingAcceleratedCanvas(bool* aOutValue) {
  *aOutValue = gfx::gfxVars::UseAcceleratedCanvas2D();
  return NS_OK;
}

NS_IMETHODIMP_(int32_t)
GfxInfoBase::GetMaxRefreshRate(bool* aMixed) {
  if (aMixed) {
    *aMixed = false;
  }

  int32_t maxRefreshRate = 0;
  for (auto& screen : ScreenManager::GetSingleton().CurrentScreenList()) {
    int32_t refreshRate = screen->GetRefreshRate();
    if (aMixed && maxRefreshRate > 0 && maxRefreshRate != refreshRate) {
      *aMixed = true;
    }
    maxRefreshRate = std::max(maxRefreshRate, refreshRate);
  }

  return maxRefreshRate > 0 ? maxRefreshRate : -1;
}

NS_IMETHODIMP
GfxInfoBase::ControlGPUProcessForXPCShell(bool aEnable, bool* _retval) {
  gfxPlatform::GetPlatform();

  GPUProcessManager* gpm = GPUProcessManager::Get();
  if (aEnable) {
    if (!gfxConfig::IsEnabled(gfx::Feature::GPU_PROCESS)) {
      gfxConfig::UserForceEnable(gfx::Feature::GPU_PROCESS, "xpcshell-test");
    }
    DebugOnly<nsresult> rv = gpm->EnsureGPUReady();
    MOZ_ASSERT(rv != NS_ERROR_ILLEGAL_DURING_SHUTDOWN);
  } else {
    gfxConfig::UserDisable(gfx::Feature::GPU_PROCESS, "xpcshell-test");
    gpm->KillProcess();
  }

  *_retval = true;
  return NS_OK;
}

NS_IMETHODIMP GfxInfoBase::KillGPUProcessForTests() {
  GPUProcessManager* gpm = GPUProcessManager::Get();
  if (!gpm) {
    // gfxPlatform has not been initialized.
    return NS_ERROR_NOT_INITIALIZED;
  }

  gpm->KillProcess();
  return NS_OK;
}

NS_IMETHODIMP GfxInfoBase::CrashGPUProcessForTests() {
  GPUProcessManager* gpm = GPUProcessManager::Get();
  if (!gpm) {
    // gfxPlatform has not been initialized.
    return NS_ERROR_NOT_INITIALIZED;
  }

  gpm->CrashProcess();
  return NS_OK;
}

GfxInfoCollectorBase::GfxInfoCollectorBase() {
  GfxInfoBase::AddCollector(this);
}

GfxInfoCollectorBase::~GfxInfoCollectorBase() {
  GfxInfoBase::RemoveCollector(this);
}