summaryrefslogtreecommitdiffstats
path: root/gfx/gl/GLContext.cpp
blob: f67aedd0b24bf5bf2d3545855315fc95418e6918 (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
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "GLContext.h"

#include <algorithm>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <regex>
#include <string>
#include <vector>
#ifdef MOZ_WIDGET_ANDROID
#  include <sys/mman.h>
#endif
#if defined(XP_LINUX) && !defined(ANDROID)
// For MesaMemoryLeakWorkaround
#  include <dlfcn.h>
#  include <link.h>
#endif

#include "GLBlitHelper.h"
#include "GLReadTexImageHelper.h"
#include "GLScreenBuffer.h"

#include "gfxCrashReporterUtils.h"
#include "gfxEnv.h"
#include "gfxUtils.h"
#include "GLContextProvider.h"
#include "GLLibraryLoader.h"
#include "GLTextureImage.h"
#include "nsPrintfCString.h"
#include "nsThreadUtils.h"
#include "prenv.h"
#include "prlink.h"
#include "ScopedGLHelpers.h"
#include "SharedSurfaceGL.h"
#include "GfxTexturesReporter.h"
#include "gfx2DGlue.h"
#include "mozilla/StaticPrefs_gfx.h"
#include "mozilla/StaticPrefs_gl.h"
#include "mozilla/IntegerPrintfMacros.h"
#include "mozilla/gfx/Logging.h"
#include "mozilla/layers/BuildConstants.h"
#include "mozilla/layers/TextureForwarder.h"  // for LayersIPCChannel

#include "OGLShaderProgram.h"  // for ShaderProgramType

#include "mozilla/DebugOnly.h"
#include "mozilla/Maybe.h"

#ifdef XP_MACOSX
#  include <CoreServices/CoreServices.h>
#endif

#if defined(MOZ_WIDGET_COCOA)
#  include "nsCocoaFeatures.h"
#endif

#ifdef MOZ_WIDGET_ANDROID
#  include "mozilla/jni/Utils.h"
#endif

namespace mozilla {
namespace gl {

using namespace mozilla::gfx;
using namespace mozilla::layers;

// Zero-initialized after init().
MOZ_THREAD_LOCAL(const GLContext*) GLContext::sCurrentContext;

// If adding defines, don't forget to undefine symbols. See #undef block below.
// clang-format off
#define CORE_SYMBOL(x) { (PRFuncPtr*) &mSymbols.f##x, {{ "gl" #x }} }
#define CORE_EXT_SYMBOL2(x,y,z) { (PRFuncPtr*) &mSymbols.f##x, {{ "gl" #x, "gl" #x #y, "gl" #x #z }} }
#define EXT_SYMBOL2(x,y,z) { (PRFuncPtr*) &mSymbols.f##x, {{ "gl" #x #y, "gl" #x #z }} }
#define EXT_SYMBOL3(x,y,z,w) { (PRFuncPtr*) &mSymbols.f##x, {{ "gl" #x #y, "gl" #x #z, "gl" #x #w }} }
#define END_SYMBOLS { nullptr, {} }
// clang-format on

// should match the order of GLExtensions, and be null-terminated.
static const char* const sExtensionNames[] = {
    "NO_EXTENSION",
    "GL_AMD_compressed_ATC_texture",
    "GL_ANGLE_depth_texture",
    "GL_ANGLE_framebuffer_blit",
    "GL_ANGLE_framebuffer_multisample",
    "GL_ANGLE_instanced_arrays",
    "GL_ANGLE_multiview",
    "GL_ANGLE_provoking_vertex",
    "GL_ANGLE_texture_compression_dxt3",
    "GL_ANGLE_texture_compression_dxt5",
    "GL_ANGLE_timer_query",
    "GL_APPLE_client_storage",
    "GL_APPLE_fence",
    "GL_APPLE_framebuffer_multisample",
    "GL_APPLE_sync",
    "GL_APPLE_texture_range",
    "GL_APPLE_vertex_array_object",
    "GL_ARB_ES2_compatibility",
    "GL_ARB_ES3_compatibility",
    "GL_ARB_color_buffer_float",
    "GL_ARB_compatibility",
    "GL_ARB_copy_buffer",
    "GL_ARB_depth_texture",
    "GL_ARB_draw_buffers",
    "GL_ARB_draw_instanced",
    "GL_ARB_framebuffer_object",
    "GL_ARB_framebuffer_sRGB",
    "GL_ARB_geometry_shader4",
    "GL_ARB_half_float_pixel",
    "GL_ARB_instanced_arrays",
    "GL_ARB_internalformat_query",
    "GL_ARB_invalidate_subdata",
    "GL_ARB_map_buffer_range",
    "GL_ARB_occlusion_query2",
    "GL_ARB_pixel_buffer_object",
    "GL_ARB_provoking_vertex",
    "GL_ARB_robust_buffer_access_behavior",
    "GL_ARB_robustness",
    "GL_ARB_sampler_objects",
    "GL_ARB_seamless_cube_map",
    "GL_ARB_shader_texture_lod",
    "GL_ARB_sync",
    "GL_ARB_texture_compression",
    "GL_ARB_texture_compression_bptc",
    "GL_ARB_texture_compression_rgtc",
    "GL_ARB_texture_float",
    "GL_ARB_texture_non_power_of_two",
    "GL_ARB_texture_rectangle",
    "GL_ARB_texture_rg",
    "GL_ARB_texture_storage",
    "GL_ARB_texture_swizzle",
    "GL_ARB_timer_query",
    "GL_ARB_transform_feedback2",
    "GL_ARB_uniform_buffer_object",
    "GL_ARB_vertex_array_object",
    "GL_CHROMIUM_color_buffer_float_rgb",
    "GL_CHROMIUM_color_buffer_float_rgba",
    "GL_EXT_bgra",
    "GL_EXT_blend_minmax",
    "GL_EXT_color_buffer_float",
    "GL_EXT_color_buffer_half_float",
    "GL_EXT_copy_texture",
    "GL_EXT_disjoint_timer_query",
    "GL_EXT_draw_buffers",
    "GL_EXT_draw_buffers2",
    "GL_EXT_draw_instanced",
    "GL_EXT_float_blend",
    "GL_EXT_frag_depth",
    "GL_EXT_framebuffer_blit",
    "GL_EXT_framebuffer_multisample",
    "GL_EXT_framebuffer_object",
    "GL_EXT_framebuffer_sRGB",
    "GL_EXT_gpu_shader4",
    "GL_EXT_map_buffer_range",
    "GL_EXT_multisampled_render_to_texture",
    "GL_EXT_occlusion_query_boolean",
    "GL_EXT_packed_depth_stencil",
    "GL_EXT_provoking_vertex",
    "GL_EXT_read_format_bgra",
    "GL_EXT_robustness",
    "GL_EXT_sRGB",
    "GL_EXT_sRGB_write_control",
    "GL_EXT_shader_texture_lod",
    "GL_EXT_texture_compression_bptc",
    "GL_EXT_texture_compression_dxt1",
    "GL_EXT_texture_compression_rgtc",
    "GL_EXT_texture_compression_s3tc",
    "GL_EXT_texture_compression_s3tc_srgb",
    "GL_EXT_texture_filter_anisotropic",
    "GL_EXT_texture_format_BGRA8888",
    "GL_EXT_texture_norm16",
    "GL_EXT_texture_sRGB",
    "GL_EXT_texture_storage",
    "GL_EXT_timer_query",
    "GL_EXT_transform_feedback",
    "GL_EXT_unpack_subimage",
    "GL_IMG_read_format",
    "GL_IMG_texture_compression_pvrtc",
    "GL_IMG_texture_npot",
    "GL_KHR_debug",
    "GL_KHR_parallel_shader_compile",
    "GL_KHR_robust_buffer_access_behavior",
    "GL_KHR_robustness",
    "GL_KHR_texture_compression_astc_hdr",
    "GL_KHR_texture_compression_astc_ldr",
    "GL_NV_draw_instanced",
    "GL_NV_fence",
    "GL_NV_framebuffer_blit",
    "GL_NV_geometry_program4",
    "GL_NV_half_float",
    "GL_NV_instanced_arrays",
    "GL_NV_primitive_restart",
    "GL_NV_texture_barrier",
    "GL_NV_transform_feedback",
    "GL_NV_transform_feedback2",
    "GL_OES_EGL_image",
    "GL_OES_EGL_image_external",
    "GL_OES_EGL_sync",
    "GL_OES_compressed_ETC1_RGB8_texture",
    "GL_OES_depth24",
    "GL_OES_depth32",
    "GL_OES_depth_texture",
    "GL_OES_draw_buffers_indexed",
    "GL_OES_element_index_uint",
    "GL_OES_fbo_render_mipmap",
    "GL_OES_framebuffer_object",
    "GL_OES_packed_depth_stencil",
    "GL_OES_rgb8_rgba8",
    "GL_OES_standard_derivatives",
    "GL_OES_stencil8",
    "GL_OES_texture_3D",
    "GL_OES_texture_float",
    "GL_OES_texture_float_linear",
    "GL_OES_texture_half_float",
    "GL_OES_texture_half_float_linear",
    "GL_OES_texture_npot",
    "GL_OES_vertex_array_object",
    "GL_OVR_multiview2"};

static bool ShouldUseTLSIsCurrent(bool useTLSIsCurrent) {
  if (StaticPrefs::gl_use_tls_is_current() == 0) {
    return useTLSIsCurrent;
  }

  return StaticPrefs::gl_use_tls_is_current() > 0;
}

static bool ParseVersion(const std::string& versionStr,
                         uint32_t* const out_major, uint32_t* const out_minor) {
  static const std::regex kVersionRegex("([0-9]+)\\.([0-9]+)");
  std::smatch match;
  if (!std::regex_search(versionStr, match, kVersionRegex)) return false;

  const auto& majorStr = match.str(1);
  const auto& minorStr = match.str(2);
  *out_major = atoi(majorStr.c_str());
  *out_minor = atoi(minorStr.c_str());
  return true;
}

/*static*/
uint8_t GLContext::ChooseDebugFlags(const CreateContextFlags createFlags) {
  uint8_t debugFlags = 0;

#ifdef MOZ_GL_DEBUG_BUILD
  if (gfxEnv::MOZ_GL_DEBUG()) {
    debugFlags |= GLContext::DebugFlagEnabled;
  }

  // Enables extra verbose output, informing of the start and finish of every GL
  // call. Useful e.g. to record information to investigate graphics system
  // crashes/lockups
  if (gfxEnv::MOZ_GL_DEBUG_VERBOSE()) {
    debugFlags |= GLContext::DebugFlagTrace;
  }

  // Aborts on GL error. Can be useful to debug quicker code that is known not
  // to generate any GL error in principle.
  bool abortOnError = false;

  if (createFlags & CreateContextFlags::NO_VALIDATION) {
    abortOnError = true;

    const auto& env = gfxEnv::MOZ_GL_DEBUG_ABORT_ON_ERROR();
    if (env.as_str == "0") {
      abortOnError = false;
    }
  }

  if (abortOnError) {
    debugFlags |= GLContext::DebugFlagAbortOnError;
  }
#endif

  return debugFlags;
}

GLContext::GLContext(const GLContextDesc& desc, GLContext* sharedContext,
                     bool useTLSIsCurrent)
    : mDesc(desc),
      mUseTLSIsCurrent(ShouldUseTLSIsCurrent(useTLSIsCurrent)),
      mDebugFlags(ChooseDebugFlags(mDesc.flags)),
      mSharedContext(sharedContext),
      mOwningThreadId(Some(PlatformThread::CurrentId())),
      mWorkAroundDriverBugs(
          StaticPrefs::gfx_work_around_driver_bugs_AtStartup()) {}

GLContext::~GLContext() {
  NS_ASSERTION(
      IsDestroyed(),
      "GLContext implementation must call MarkDestroyed in destructor!");
#ifdef MOZ_GL_DEBUG_BUILD
  if (mSharedContext) {
    GLContext* tip = mSharedContext;
    while (tip->mSharedContext) tip = tip->mSharedContext;
    tip->SharedContextDestroyed(this);
    tip->ReportOutstandingNames();
  } else {
    ReportOutstandingNames();
  }
#endif
  // Ensure we clear sCurrentContext if we were the last context set and avoid
  // the memory getting reused.
  if (sCurrentContext.init() && sCurrentContext.get() == this) {
    sCurrentContext.set(nullptr);
  }
}

/*static*/
void GLContext::StaticDebugCallback(GLenum source, GLenum type, GLuint id,
                                    GLenum severity, GLsizei length,
                                    const GLchar* message,
                                    const GLvoid* userParam) {
  GLContext* gl = (GLContext*)userParam;
  gl->DebugCallback(source, type, id, severity, length, message);
}

bool GLContext::Init() {
  MOZ_RELEASE_ASSERT(!mSymbols.fBindFramebuffer,
                     "GFX: GLContext::Init should only be called once.");

  ScopedGfxFeatureReporter reporter("GL Context");

  if (!InitImpl()) {
    // If initialization fails, zero the symbols to avoid hard-to-understand
    // bugs.
    mSymbols = {};
    NS_WARNING("GLContext::InitWithPrefix failed!");
    return false;
  }

  reporter.SetSuccessful();
  return true;
}

static bool LoadSymbolsWithDesc(const SymbolLoader& loader,
                                const SymLoadStruct* list, const char* desc) {
  const auto warnOnFailure = bool(desc);
  if (loader.LoadSymbols(list, warnOnFailure)) return true;

  ClearSymbols(list);

  if (desc) {
    const nsPrintfCString err("Failed to load symbols for %s.", desc);
    NS_ERROR(err.BeginReading());
  }
  return false;
}

bool GLContext::LoadExtSymbols(const SymbolLoader& loader,
                               const SymLoadStruct* list, GLExtensions ext) {
  const char* extName = sExtensionNames[size_t(ext)];
  if (!LoadSymbolsWithDesc(loader, list, extName)) {
    MarkExtensionUnsupported(ext);
    return false;
  }
  return true;
};

bool GLContext::LoadFeatureSymbols(const SymbolLoader& loader,
                                   const SymLoadStruct* list,
                                   GLFeature feature) {
  const char* featureName = GetFeatureName(feature);
  if (!LoadSymbolsWithDesc(loader, list, featureName)) {
    MarkUnsupported(feature);
    return false;
  }
  return true;
};

bool GLContext::InitImpl() {
  if (!MakeCurrent(true)) return false;

  const auto loader = GetSymbolLoader();
  if (!loader) return false;

  const auto fnLoadSymbols = [&](const SymLoadStruct* const list,
                                 const char* const desc) {
    return LoadSymbolsWithDesc(*loader, list, desc);
  };

  // clang-format off
    const SymLoadStruct coreSymbols[] = {
        { (PRFuncPtr*) &mSymbols.fActiveTexture, {{ "glActiveTexture", "glActiveTextureARB" }} },
        { (PRFuncPtr*) &mSymbols.fAttachShader, {{ "glAttachShader", "glAttachShaderARB" }} },
        { (PRFuncPtr*) &mSymbols.fBindAttribLocation, {{ "glBindAttribLocation", "glBindAttribLocationARB" }} },
        { (PRFuncPtr*) &mSymbols.fBindBuffer, {{ "glBindBuffer", "glBindBufferARB" }} },
        { (PRFuncPtr*) &mSymbols.fBindTexture, {{ "glBindTexture", "glBindTextureARB" }} },
        { (PRFuncPtr*) &mSymbols.fBlendColor, {{ "glBlendColor" }} },
        { (PRFuncPtr*) &mSymbols.fBlendEquation, {{ "glBlendEquation" }} },
        { (PRFuncPtr*) &mSymbols.fBlendEquationSeparate, {{ "glBlendEquationSeparate", "glBlendEquationSeparateEXT" }} },
        { (PRFuncPtr*) &mSymbols.fBlendFunc, {{ "glBlendFunc" }} },
        { (PRFuncPtr*) &mSymbols.fBlendFuncSeparate, {{ "glBlendFuncSeparate", "glBlendFuncSeparateEXT" }} },
        { (PRFuncPtr*) &mSymbols.fBufferData, {{ "glBufferData" }} },
        { (PRFuncPtr*) &mSymbols.fBufferSubData, {{ "glBufferSubData" }} },
        { (PRFuncPtr*) &mSymbols.fClear, {{ "glClear" }} },
        { (PRFuncPtr*) &mSymbols.fClearColor, {{ "glClearColor" }} },
        { (PRFuncPtr*) &mSymbols.fClearStencil, {{ "glClearStencil" }} },
        { (PRFuncPtr*) &mSymbols.fColorMask, {{ "glColorMask" }} },
        { (PRFuncPtr*) &mSymbols.fCompressedTexImage2D, {{ "glCompressedTexImage2D" }} },
        { (PRFuncPtr*) &mSymbols.fCompressedTexSubImage2D, {{ "glCompressedTexSubImage2D" }} },
        { (PRFuncPtr*) &mSymbols.fCullFace, {{ "glCullFace" }} },
        { (PRFuncPtr*) &mSymbols.fDetachShader, {{ "glDetachShader", "glDetachShaderARB" }} },
        { (PRFuncPtr*) &mSymbols.fDepthFunc, {{ "glDepthFunc" }} },
        { (PRFuncPtr*) &mSymbols.fDepthMask, {{ "glDepthMask" }} },
        { (PRFuncPtr*) &mSymbols.fDisable, {{ "glDisable" }} },
        { (PRFuncPtr*) &mSymbols.fDisableVertexAttribArray, {{ "glDisableVertexAttribArray", "glDisableVertexAttribArrayARB" }} },
        { (PRFuncPtr*) &mSymbols.fDrawArrays, {{ "glDrawArrays" }} },
        { (PRFuncPtr*) &mSymbols.fDrawElements, {{ "glDrawElements" }} },
        { (PRFuncPtr*) &mSymbols.fEnable, {{ "glEnable" }} },
        { (PRFuncPtr*) &mSymbols.fEnableVertexAttribArray, {{ "glEnableVertexAttribArray", "glEnableVertexAttribArrayARB" }} },
        { (PRFuncPtr*) &mSymbols.fFinish, {{ "glFinish" }} },
        { (PRFuncPtr*) &mSymbols.fFlush, {{ "glFlush" }} },
        { (PRFuncPtr*) &mSymbols.fFrontFace, {{ "glFrontFace" }} },
        { (PRFuncPtr*) &mSymbols.fGetActiveAttrib, {{ "glGetActiveAttrib", "glGetActiveAttribARB" }} },
        { (PRFuncPtr*) &mSymbols.fGetActiveUniform, {{ "glGetActiveUniform", "glGetActiveUniformARB" }} },
        { (PRFuncPtr*) &mSymbols.fGetAttachedShaders, {{ "glGetAttachedShaders", "glGetAttachedShadersARB" }} },
        { (PRFuncPtr*) &mSymbols.fGetAttribLocation, {{ "glGetAttribLocation", "glGetAttribLocationARB" }} },
        { (PRFuncPtr*) &mSymbols.fGetIntegerv, {{ "glGetIntegerv" }} },
        { (PRFuncPtr*) &mSymbols.fGetFloatv, {{ "glGetFloatv" }} },
        { (PRFuncPtr*) &mSymbols.fGetBooleanv, {{ "glGetBooleanv" }} },
        { (PRFuncPtr*) &mSymbols.fGetBufferParameteriv, {{ "glGetBufferParameteriv", "glGetBufferParameterivARB" }} },
        { (PRFuncPtr*) &mSymbols.fGetError, {{ "glGetError" }} },
        { (PRFuncPtr*) &mSymbols.fGetProgramiv, {{ "glGetProgramiv", "glGetProgramivARB" }} },
        { (PRFuncPtr*) &mSymbols.fGetProgramInfoLog, {{ "glGetProgramInfoLog", "glGetProgramInfoLogARB" }} },
        { (PRFuncPtr*) &mSymbols.fTexParameteri, {{ "glTexParameteri" }} },
        { (PRFuncPtr*) &mSymbols.fTexParameteriv, {{ "glTexParameteriv" }} },
        { (PRFuncPtr*) &mSymbols.fTexParameterf, {{ "glTexParameterf" }} },
        { (PRFuncPtr*) &mSymbols.fGetString, {{ "glGetString" }} },
        { (PRFuncPtr*) &mSymbols.fGetTexParameterfv, {{ "glGetTexParameterfv" }} },
        { (PRFuncPtr*) &mSymbols.fGetTexParameteriv, {{ "glGetTexParameteriv" }} },
        { (PRFuncPtr*) &mSymbols.fGetUniformfv, {{ "glGetUniformfv", "glGetUniformfvARB" }} },
        { (PRFuncPtr*) &mSymbols.fGetUniformiv, {{ "glGetUniformiv", "glGetUniformivARB" }} },
        { (PRFuncPtr*) &mSymbols.fGetUniformLocation, {{ "glGetUniformLocation", "glGetUniformLocationARB" }} },
        { (PRFuncPtr*) &mSymbols.fGetVertexAttribfv, {{ "glGetVertexAttribfv", "glGetVertexAttribfvARB" }} },
        { (PRFuncPtr*) &mSymbols.fGetVertexAttribiv, {{ "glGetVertexAttribiv", "glGetVertexAttribivARB" }} },
        { (PRFuncPtr*) &mSymbols.fGetVertexAttribPointerv, {{ "glGetVertexAttribPointerv" }} },
        { (PRFuncPtr*) &mSymbols.fHint, {{ "glHint" }} },
        { (PRFuncPtr*) &mSymbols.fIsBuffer, {{ "glIsBuffer", "glIsBufferARB" }} },
        { (PRFuncPtr*) &mSymbols.fIsEnabled, {{ "glIsEnabled" }} },
        { (PRFuncPtr*) &mSymbols.fIsProgram, {{ "glIsProgram", "glIsProgramARB" }} },
        { (PRFuncPtr*) &mSymbols.fIsShader, {{ "glIsShader", "glIsShaderARB" }} },
        { (PRFuncPtr*) &mSymbols.fIsTexture, {{ "glIsTexture", "glIsTextureARB" }} },
        { (PRFuncPtr*) &mSymbols.fLineWidth, {{ "glLineWidth" }} },
        { (PRFuncPtr*) &mSymbols.fLinkProgram, {{ "glLinkProgram", "glLinkProgramARB" }} },
        { (PRFuncPtr*) &mSymbols.fPixelStorei, {{ "glPixelStorei" }} },
        { (PRFuncPtr*) &mSymbols.fPolygonOffset, {{ "glPolygonOffset" }} },
        { (PRFuncPtr*) &mSymbols.fReadPixels, {{ "glReadPixels" }} },
        { (PRFuncPtr*) &mSymbols.fSampleCoverage, {{ "glSampleCoverage" }} },
        { (PRFuncPtr*) &mSymbols.fScissor, {{ "glScissor" }} },
        { (PRFuncPtr*) &mSymbols.fStencilFunc, {{ "glStencilFunc" }} },
        { (PRFuncPtr*) &mSymbols.fStencilFuncSeparate, {{ "glStencilFuncSeparate", "glStencilFuncSeparateEXT" }} },
        { (PRFuncPtr*) &mSymbols.fStencilMask, {{ "glStencilMask" }} },
        { (PRFuncPtr*) &mSymbols.fStencilMaskSeparate, {{ "glStencilMaskSeparate", "glStencilMaskSeparateEXT" }} },
        { (PRFuncPtr*) &mSymbols.fStencilOp, {{ "glStencilOp" }} },
        { (PRFuncPtr*) &mSymbols.fStencilOpSeparate, {{ "glStencilOpSeparate", "glStencilOpSeparateEXT" }} },
        { (PRFuncPtr*) &mSymbols.fTexImage2D, {{ "glTexImage2D" }} },
        { (PRFuncPtr*) &mSymbols.fTexSubImage2D, {{ "glTexSubImage2D" }} },
        { (PRFuncPtr*) &mSymbols.fUniform1f, {{ "glUniform1f" }} },
        { (PRFuncPtr*) &mSymbols.fUniform1fv, {{ "glUniform1fv" }} },
        { (PRFuncPtr*) &mSymbols.fUniform1i, {{ "glUniform1i" }} },
        { (PRFuncPtr*) &mSymbols.fUniform1iv, {{ "glUniform1iv" }} },
        { (PRFuncPtr*) &mSymbols.fUniform2f, {{ "glUniform2f" }} },
        { (PRFuncPtr*) &mSymbols.fUniform2fv, {{ "glUniform2fv" }} },
        { (PRFuncPtr*) &mSymbols.fUniform2i, {{ "glUniform2i" }} },
        { (PRFuncPtr*) &mSymbols.fUniform2iv, {{ "glUniform2iv" }} },
        { (PRFuncPtr*) &mSymbols.fUniform3f, {{ "glUniform3f" }} },
        { (PRFuncPtr*) &mSymbols.fUniform3fv, {{ "glUniform3fv" }} },
        { (PRFuncPtr*) &mSymbols.fUniform3i, {{ "glUniform3i" }} },
        { (PRFuncPtr*) &mSymbols.fUniform3iv, {{ "glUniform3iv" }} },
        { (PRFuncPtr*) &mSymbols.fUniform4f, {{ "glUniform4f" }} },
        { (PRFuncPtr*) &mSymbols.fUniform4fv, {{ "glUniform4fv" }} },
        { (PRFuncPtr*) &mSymbols.fUniform4i, {{ "glUniform4i" }} },
        { (PRFuncPtr*) &mSymbols.fUniform4iv, {{ "glUniform4iv" }} },
        { (PRFuncPtr*) &mSymbols.fUniformMatrix2fv, {{ "glUniformMatrix2fv" }} },
        { (PRFuncPtr*) &mSymbols.fUniformMatrix3fv, {{ "glUniformMatrix3fv" }} },
        { (PRFuncPtr*) &mSymbols.fUniformMatrix4fv, {{ "glUniformMatrix4fv" }} },
        { (PRFuncPtr*) &mSymbols.fUseProgram, {{ "glUseProgram" }} },
        { (PRFuncPtr*) &mSymbols.fValidateProgram, {{ "glValidateProgram" }} },
        { (PRFuncPtr*) &mSymbols.fVertexAttribPointer, {{ "glVertexAttribPointer" }} },
        { (PRFuncPtr*) &mSymbols.fVertexAttrib1f, {{ "glVertexAttrib1f" }} },
        { (PRFuncPtr*) &mSymbols.fVertexAttrib2f, {{ "glVertexAttrib2f" }} },
        { (PRFuncPtr*) &mSymbols.fVertexAttrib3f, {{ "glVertexAttrib3f" }} },
        { (PRFuncPtr*) &mSymbols.fVertexAttrib4f, {{ "glVertexAttrib4f" }} },
        { (PRFuncPtr*) &mSymbols.fVertexAttrib1fv, {{ "glVertexAttrib1fv" }} },
        { (PRFuncPtr*) &mSymbols.fVertexAttrib2fv, {{ "glVertexAttrib2fv" }} },
        { (PRFuncPtr*) &mSymbols.fVertexAttrib3fv, {{ "glVertexAttrib3fv" }} },
        { (PRFuncPtr*) &mSymbols.fVertexAttrib4fv, {{ "glVertexAttrib4fv" }} },
        { (PRFuncPtr*) &mSymbols.fViewport, {{ "glViewport" }} },
        { (PRFuncPtr*) &mSymbols.fCompileShader, {{ "glCompileShader" }} },
        { (PRFuncPtr*) &mSymbols.fCopyTexImage2D, {{ "glCopyTexImage2D" }} },
        { (PRFuncPtr*) &mSymbols.fCopyTexSubImage2D, {{ "glCopyTexSubImage2D" }} },
        { (PRFuncPtr*) &mSymbols.fGetShaderiv, {{ "glGetShaderiv" }} },
        { (PRFuncPtr*) &mSymbols.fGetShaderInfoLog, {{ "glGetShaderInfoLog" }} },
        { (PRFuncPtr*) &mSymbols.fGetShaderSource, {{ "glGetShaderSource" }} },
        { (PRFuncPtr*) &mSymbols.fShaderSource, {{ "glShaderSource" }} },
        { (PRFuncPtr*) &mSymbols.fVertexAttribPointer, {{ "glVertexAttribPointer" }} },

        { (PRFuncPtr*) &mSymbols.fGenBuffers, {{ "glGenBuffers", "glGenBuffersARB" }} },
        { (PRFuncPtr*) &mSymbols.fGenTextures, {{ "glGenTextures" }} },
        { (PRFuncPtr*) &mSymbols.fCreateProgram, {{ "glCreateProgram", "glCreateProgramARB" }} },
        { (PRFuncPtr*) &mSymbols.fCreateShader, {{ "glCreateShader", "glCreateShaderARB" }} },

        { (PRFuncPtr*) &mSymbols.fDeleteBuffers, {{ "glDeleteBuffers", "glDeleteBuffersARB" }} },
        { (PRFuncPtr*) &mSymbols.fDeleteTextures, {{ "glDeleteTextures", "glDeleteTexturesARB" }} },
        { (PRFuncPtr*) &mSymbols.fDeleteProgram, {{ "glDeleteProgram", "glDeleteProgramARB" }} },
        { (PRFuncPtr*) &mSymbols.fDeleteShader, {{ "glDeleteShader", "glDeleteShaderARB" }} },

        END_SYMBOLS
    };
  // clang-format on

  if (!fnLoadSymbols(coreSymbols, "GL")) return false;

  {
    const SymLoadStruct symbols[] = {
        {(PRFuncPtr*)&mSymbols.fGetGraphicsResetStatus,
         {{"glGetGraphicsResetStatus", "glGetGraphicsResetStatusARB",
           "glGetGraphicsResetStatusKHR", "glGetGraphicsResetStatusEXT"}}},
        END_SYMBOLS};
    (void)fnLoadSymbols(symbols, nullptr);

    // We need to call the fGetError symbol directly here because if there is an
    // unflushed reset status, we don't want to mark the context as lost. That
    // would prevent us from recovering.
    auto err = mSymbols.fGetError();
    if (err == LOCAL_GL_CONTEXT_LOST) {
      MOZ_ASSERT(mSymbols.fGetGraphicsResetStatus);
      const auto status = fGetGraphicsResetStatus();
      if (status) {
        printf_stderr("Unflushed glGetGraphicsResetStatus: 0x%04x\n", status);
      }
      err = fGetError();
      MOZ_ASSERT(!err);
    }
    if (err) {
      MOZ_ASSERT(false);
      return false;
    }
  }

  ////////////////

  const auto* const versionRawStr = (const char*)fGetString(LOCAL_GL_VERSION);
  if (!versionRawStr || !*versionRawStr) {
    // This can happen with Pernosco.
    NS_WARNING("Empty GL version string");
    return false;
  }

  const std::string versionStr = versionRawStr;
  if (versionStr.find("OpenGL ES") == 0) {
    mProfile = ContextProfile::OpenGLES;
  }

  uint32_t majorVer, minorVer;
  if (!ParseVersion(versionStr, &majorVer, &minorVer)) {
    MOZ_ASSERT(false, "Failed to parse GL_VERSION");
    return false;
  }
  MOZ_ASSERT(majorVer < 10);
  MOZ_ASSERT(minorVer < 10);
  mVersion = majorVer * 100 + minorVer * 10;
  if (mVersion < 200) return false;

  ////

  const auto glslVersionStr =
      (const char*)fGetString(LOCAL_GL_SHADING_LANGUAGE_VERSION);
  if (!glslVersionStr) {
    // This happens on the Android emulators. We'll just return 100
    mShadingLanguageVersion = 100;
  } else if (ParseVersion(glslVersionStr, &majorVer, &minorVer)) {
    MOZ_ASSERT(majorVer < 10);
    MOZ_ASSERT(minorVer < 100);
    mShadingLanguageVersion = majorVer * 100 + minorVer;
  } else {
    MOZ_ASSERT(false, "Failed to parse GL_SHADING_LANGUAGE_VERSION");
    return false;
  }

  if (ShouldSpew()) {
    printf_stderr("GL version detected: %u\n", mVersion);
    printf_stderr("GLSL version detected: %u\n", mShadingLanguageVersion);
    printf_stderr("OpenGL vendor: %s\n", fGetString(LOCAL_GL_VENDOR));
    printf_stderr("OpenGL renderer: %s\n", fGetString(LOCAL_GL_RENDERER));
  }

  ////////////////

  // Load OpenGL ES 2.0 symbols, or desktop if we aren't using ES 2.
  if (mProfile == ContextProfile::OpenGLES) {
    const SymLoadStruct symbols[] = {CORE_SYMBOL(GetShaderPrecisionFormat),
                                     CORE_SYMBOL(ClearDepthf),
                                     CORE_SYMBOL(DepthRangef), END_SYMBOLS};

    if (!fnLoadSymbols(symbols, "OpenGL ES")) return false;
  } else {
    const SymLoadStruct symbols[] = {
        CORE_SYMBOL(ClearDepth), CORE_SYMBOL(DepthRange),
        CORE_SYMBOL(ReadBuffer), CORE_SYMBOL(MapBuffer),
        CORE_SYMBOL(UnmapBuffer), CORE_SYMBOL(PointParameterf),
        CORE_SYMBOL(DrawBuffer),
        // The following functions are only used by Skia/GL in desktop mode.
        // Other parts of Gecko should avoid using these
        CORE_SYMBOL(DrawBuffers), CORE_SYMBOL(ClientActiveTexture),
        CORE_SYMBOL(DisableClientState), CORE_SYMBOL(EnableClientState),
        CORE_SYMBOL(LoadIdentity), CORE_SYMBOL(LoadMatrixf),
        CORE_SYMBOL(MatrixMode), CORE_SYMBOL(PolygonMode), CORE_SYMBOL(TexGeni),
        CORE_SYMBOL(TexGenf), CORE_SYMBOL(TexGenfv), CORE_SYMBOL(VertexPointer),
        END_SYMBOLS};

    if (!fnLoadSymbols(symbols, "Desktop OpenGL")) return false;
  }

  ////////////////

  const char* glVendorString = (const char*)fGetString(LOCAL_GL_VENDOR);
  const char* glRendererString = (const char*)fGetString(LOCAL_GL_RENDERER);
  if (!glVendorString || !glRendererString) return false;

  // The order of these strings must match up with the order of the enum
  // defined in GLContext.h for vendor IDs.
  const char* vendorMatchStrings[size_t(GLVendor::Other) + 1] = {
      "Intel",   "NVIDIA",  "ATI",          "Qualcomm", "Imagination",
      "nouveau", "Vivante", "VMware, Inc.", "ARM",      "Unknown"};

  mVendor = GLVendor::Other;
  for (size_t i = 0; i < size_t(GLVendor::Other); ++i) {
    if (DoesStringMatch(glVendorString, vendorMatchStrings[i])) {
      mVendor = GLVendor(i);
      break;
    }
  }

  // The order of these strings must match up with the order of the enum
  // defined in GLContext.h for renderer IDs.
  const char* rendererMatchStrings[size_t(GLRenderer::Other) + 1] = {
      "Adreno 200",
      "Adreno 205",
      "Adreno (TM) 200",
      "Adreno (TM) 205",
      "Adreno (TM) 305",
      "Adreno (TM) 320",
      "Adreno (TM) 330",
      "Adreno (TM) 420",
      "Mali-400 MP",
      "Mali-450 MP",
      "Mali-T",
      "PowerVR SGX 530",
      "PowerVR SGX 540",
      "PowerVR SGX 544MP",
      "NVIDIA Tegra",
      "Android Emulator",
      "Gallium 0.4 on llvmpipe",
      "Intel HD Graphics 3000 OpenGL Engine",
      "Microsoft Basic Render Driver",
      "Unknown"};

  mRenderer = GLRenderer::Other;
  for (size_t i = 0; i < size_t(GLRenderer::Other); ++i) {
    if (DoesStringMatch(glRendererString, rendererMatchStrings[i])) {
      mRenderer = GLRenderer(i);
      break;
    }
  }

  {
    const auto versionStr = (const char*)fGetString(LOCAL_GL_VERSION);
    if (strstr(versionStr, "Mesa")) {
      mIsMesa = true;
    }
  }

  const auto Once = []() {
    static bool did = false;
    if (did) return false;
    did = true;
    return true;
  };

  bool printRenderer = ShouldSpew();
  printRenderer |= (kIsDebug && Once());
  if (printRenderer) {
    printf_stderr("GL_VENDOR: %s\n", glVendorString);
    printf_stderr("mVendor: %s\n", vendorMatchStrings[size_t(mVendor)]);
    printf_stderr("GL_RENDERER: %s\n", glRendererString);
    printf_stderr("mRenderer: %s\n", rendererMatchStrings[size_t(mRenderer)]);
    printf_stderr("mIsMesa: %i\n", int(mIsMesa));
  }

  ////////////////

  if (mVersion >= 300) {  // Both GL3 and ES3.
    const SymLoadStruct symbols[] = {
        {(PRFuncPtr*)&mSymbols.fGetStringi, {{"glGetStringi"}}}, END_SYMBOLS};

    if (!fnLoadSymbols(symbols, "GetStringi")) {
      MOZ_RELEASE_ASSERT(false, "GFX: GetStringi is required!");
      return false;
    }
  }

  InitExtensions();
  if (mProfile != ContextProfile::OpenGLES) {
    if (mVersion >= 310 && !IsExtensionSupported(ARB_compatibility)) {
      mProfile = ContextProfile::OpenGLCore;
    } else {
      mProfile = ContextProfile::OpenGLCompatibility;
    }
  }
  MOZ_ASSERT(mProfile != ContextProfile::Unknown);

  if (ShouldSpew()) {
    const char* profileStr = "";
    if (mProfile == ContextProfile::OpenGLES) {
      profileStr = " es";
    } else if (mProfile == ContextProfile::OpenGLCore) {
      profileStr = " core";
    }
    printf_stderr("Detected profile: %u%s\n", mVersion, profileStr);
  }

  InitFeatures();

  ////

  // Disable extensions with partial or incorrect support.
  if (WorkAroundDriverBugs()) {
    if (Renderer() == GLRenderer::AdrenoTM320) {
      MarkUnsupported(GLFeature::standard_derivatives);
    }

    if (Renderer() == GLRenderer::AndroidEmulator) {
      // Bug 1665300
      mSymbols.fGetGraphicsResetStatus = 0;
    }

    if (Vendor() == GLVendor::Vivante) {
      // bug 958256
      MarkUnsupported(GLFeature::standard_derivatives);
    }

    if (Renderer() == GLRenderer::MicrosoftBasicRenderDriver) {
      // Bug 978966: on Microsoft's "Basic Render Driver" (software renderer)
      // multisampling hardcodes blending with the default blendfunc, which
      // breaks WebGL.
      MarkUnsupported(GLFeature::framebuffer_multisample);
    }

    if (IsMesa()) {
      // DrawElementsInstanced hangs the driver.
      MarkUnsupported(GLFeature::robust_buffer_access_behavior);
    }
  }

  if (IsExtensionSupported(GLContext::ARB_pixel_buffer_object)) {
    MOZ_ASSERT(
        (mSymbols.fMapBuffer && mSymbols.fUnmapBuffer),
        "ARB_pixel_buffer_object supported without glMapBuffer/UnmapBuffer"
        " being available!");
  }

  ////////////////////////////////////////////////////////////////////////////

  const auto fnLoadForFeature = [&](const SymLoadStruct* list,
                                    GLFeature feature) {
    return this->LoadFeatureSymbols(*loader, list, feature);
  };

  // Check for ARB_framebuffer_objects
  if (IsSupported(GLFeature::framebuffer_object)) {
    // https://www.opengl.org/registry/specs/ARB/framebuffer_object.txt
    const SymLoadStruct symbols[] = {
        CORE_SYMBOL(IsRenderbuffer),
        CORE_SYMBOL(BindRenderbuffer),
        CORE_SYMBOL(DeleteRenderbuffers),
        CORE_SYMBOL(GenRenderbuffers),
        CORE_SYMBOL(RenderbufferStorage),
        CORE_SYMBOL(RenderbufferStorageMultisample),
        CORE_SYMBOL(GetRenderbufferParameteriv),
        CORE_SYMBOL(IsFramebuffer),
        CORE_SYMBOL(BindFramebuffer),
        CORE_SYMBOL(DeleteFramebuffers),
        CORE_SYMBOL(GenFramebuffers),
        CORE_SYMBOL(CheckFramebufferStatus),
        CORE_SYMBOL(FramebufferTexture2D),
        CORE_SYMBOL(FramebufferTextureLayer),
        CORE_SYMBOL(FramebufferRenderbuffer),
        CORE_SYMBOL(GetFramebufferAttachmentParameteriv),
        CORE_SYMBOL(BlitFramebuffer),
        CORE_SYMBOL(GenerateMipmap),
        END_SYMBOLS};
    fnLoadForFeature(symbols, GLFeature::framebuffer_object);
  }

  if (!IsSupported(GLFeature::framebuffer_object)) {
    // Check for aux symbols based on extensions
    if (IsSupported(GLFeature::framebuffer_object_EXT_OES)) {
      const SymLoadStruct symbols[] = {
          CORE_EXT_SYMBOL2(IsRenderbuffer, EXT, OES),
          CORE_EXT_SYMBOL2(BindRenderbuffer, EXT, OES),
          CORE_EXT_SYMBOL2(DeleteRenderbuffers, EXT, OES),
          CORE_EXT_SYMBOL2(GenRenderbuffers, EXT, OES),
          CORE_EXT_SYMBOL2(RenderbufferStorage, EXT, OES),
          CORE_EXT_SYMBOL2(GetRenderbufferParameteriv, EXT, OES),
          CORE_EXT_SYMBOL2(IsFramebuffer, EXT, OES),
          CORE_EXT_SYMBOL2(BindFramebuffer, EXT, OES),
          CORE_EXT_SYMBOL2(DeleteFramebuffers, EXT, OES),
          CORE_EXT_SYMBOL2(GenFramebuffers, EXT, OES),
          CORE_EXT_SYMBOL2(CheckFramebufferStatus, EXT, OES),
          CORE_EXT_SYMBOL2(FramebufferTexture2D, EXT, OES),
          CORE_EXT_SYMBOL2(FramebufferRenderbuffer, EXT, OES),
          CORE_EXT_SYMBOL2(GetFramebufferAttachmentParameteriv, EXT, OES),
          CORE_EXT_SYMBOL2(GenerateMipmap, EXT, OES),
          END_SYMBOLS};
      fnLoadForFeature(symbols, GLFeature::framebuffer_object_EXT_OES);
    }

    if (IsSupported(GLFeature::framebuffer_blit)) {
      const SymLoadStruct symbols[] = {
          EXT_SYMBOL3(BlitFramebuffer, ANGLE, EXT, NV), END_SYMBOLS};
      fnLoadForFeature(symbols, GLFeature::framebuffer_blit);
    }

    if (IsSupported(GLFeature::framebuffer_multisample)) {
      const SymLoadStruct symbols[] = {
          EXT_SYMBOL3(RenderbufferStorageMultisample, ANGLE, APPLE, EXT),
          END_SYMBOLS};
      fnLoadForFeature(symbols, GLFeature::framebuffer_multisample);
    }

    if (IsExtensionSupported(GLContext::ARB_geometry_shader4) ||
        IsExtensionSupported(GLContext::NV_geometry_program4)) {
      const SymLoadStruct symbols[] = {
          EXT_SYMBOL2(FramebufferTextureLayer, ARB, EXT), END_SYMBOLS};
      if (!fnLoadSymbols(symbols,
                         "ARB_geometry_shader4/NV_geometry_program4")) {
        MarkExtensionUnsupported(GLContext::ARB_geometry_shader4);
        MarkExtensionUnsupported(GLContext::NV_geometry_program4);
      }
    }
  }

  if (!IsSupported(GLFeature::framebuffer_object) &&
      !IsSupported(GLFeature::framebuffer_object_EXT_OES)) {
    NS_ERROR("GLContext requires support for framebuffer objects.");
    return false;
  }
  MOZ_RELEASE_ASSERT(mSymbols.fBindFramebuffer,
                     "GFX: mSymbols.fBindFramebuffer zero or not set.");

  ////////////////

  const auto err = fGetError();
  MOZ_RELEASE_ASSERT(!IsBadCallError(err));
  if (err) return false;

  LoadMoreSymbols(*loader);

  ////////////////////////////////////////////////////////////////////////////

  raw_fGetIntegerv(LOCAL_GL_VIEWPORT, mViewportRect);
  raw_fGetIntegerv(LOCAL_GL_SCISSOR_BOX, mScissorRect);
  raw_fGetIntegerv(LOCAL_GL_MAX_TEXTURE_SIZE, &mMaxTextureSize);
  raw_fGetIntegerv(LOCAL_GL_MAX_CUBE_MAP_TEXTURE_SIZE, &mMaxCubeMapTextureSize);
  raw_fGetIntegerv(LOCAL_GL_MAX_RENDERBUFFER_SIZE, &mMaxRenderbufferSize);
  raw_fGetIntegerv(LOCAL_GL_MAX_VIEWPORT_DIMS, mMaxViewportDims);

  if (mWorkAroundDriverBugs) {
    int maxTexSize = INT32_MAX;
    int maxCubeSize = INT32_MAX;
#ifdef XP_MACOSX
    if (!nsCocoaFeatures::IsAtLeastVersion(10, 12)) {
      if (mVendor == GLVendor::Intel) {
        // see bug 737182 for 2D textures, bug 684882 for cube map textures.
        maxTexSize = 4096;
        maxCubeSize = 512;
      } else if (mVendor == GLVendor::NVIDIA) {
        // See bug 879656.  8192 fails, 8191 works.
        maxTexSize = 8191;
      }
    } else {
      // https://bugzilla.mozilla.org/show_bug.cgi?id=1544446
      // Mojave exposes 16k textures, but gives FRAMEBUFFER_UNSUPPORTED for any
      // 16k*16k FB except rgba8 without depth/stencil.
      // The max supported sizes changes based on involved formats.
      // (RGBA32F more restrictive than RGBA16F)
      maxTexSize = 8192;
    }
#endif
#ifdef MOZ_X11
    if (mVendor == GLVendor::Nouveau) {
      // see bug 814716. Clamp MaxCubeMapTextureSize at 2K for Nouveau.
      maxCubeSize = 2048;
    } else if (mVendor == GLVendor::Intel) {
      // Bug 1199923. Driver seems to report a larger max size than
      // actually supported.
      maxTexSize = mMaxTextureSize / 2;
    }
    // Bug 1367570. Explicitly set vertex attributes [1,3] to opaque
    // black because Nvidia doesn't do it for us.
    if (mVendor == GLVendor::NVIDIA) {
      for (size_t i = 1; i <= 3; ++i) {
        mSymbols.fVertexAttrib4f(i, 0, 0, 0, 1);
      }
    }
#endif
    if (Renderer() == GLRenderer::AdrenoTM420) {
      // see bug 1194923. Calling glFlush before glDeleteFramebuffers
      // prevents occasional driver crash.
      mNeedsFlushBeforeDeleteFB = true;
    }
#ifdef MOZ_WIDGET_ANDROID
    if ((Renderer() == GLRenderer::AdrenoTM305 ||
         Renderer() == GLRenderer::AdrenoTM320 ||
         Renderer() == GLRenderer::AdrenoTM330) &&
        jni::GetAPIVersion() < 21) {
      // Bug 1164027. Driver crashes when functions such as
      // glTexImage2D fail due to virtual memory exhaustion.
      mTextureAllocCrashesOnMapFailure = true;
    }
#endif
#if MOZ_WIDGET_ANDROID
    if (Renderer() == GLRenderer::SGX540 && jni::GetAPIVersion() <= 15) {
      // Bug 1288446. Driver sometimes crashes when uploading data to a
      // texture if the render target has changed since the texture was
      // rendered from. Calling glCheckFramebufferStatus after
      // glFramebufferTexture2D prevents the crash.
      mNeedsCheckAfterAttachTextureToFb = true;
    }
#endif

    // -

    const auto fnLimit = [&](int* const driver, const int limit) {
      if (*driver > limit) {
        *driver = limit;
        mNeedsTextureSizeChecks = true;
      }
    };

    fnLimit(&mMaxTextureSize, maxTexSize);
    fnLimit(&mMaxRenderbufferSize, maxTexSize);

    maxCubeSize = std::min(maxCubeSize, maxTexSize);
    fnLimit(&mMaxCubeMapTextureSize, maxCubeSize);
  }

  if (IsSupported(GLFeature::framebuffer_multisample)) {
    fGetIntegerv(LOCAL_GL_MAX_SAMPLES, (GLint*)&mMaxSamples);
  }

  mMaxTexOrRbSize = std::min(mMaxTextureSize, mMaxRenderbufferSize);

  ////////////////////////////////////////////////////////////////////////////

  // We're ready for final setup.
  fBindFramebuffer(LOCAL_GL_FRAMEBUFFER, 0);
  MOZ_GL_ASSERT(this, IsCurrent());

  if (ShouldSpew() && IsExtensionSupported(KHR_debug)) {
    fEnable(LOCAL_GL_DEBUG_OUTPUT);
    fDisable(LOCAL_GL_DEBUG_OUTPUT_SYNCHRONOUS);
    fDebugMessageCallback(&StaticDebugCallback, (void*)this);
    fDebugMessageControl(LOCAL_GL_DONT_CARE, LOCAL_GL_DONT_CARE,
                         LOCAL_GL_DONT_CARE, 0, nullptr, true);
  }

  return true;
}

void GLContext::LoadMoreSymbols(const SymbolLoader& loader) {
  const auto fnLoadForExt = [&](const SymLoadStruct* list, GLExtensions ext) {
    return this->LoadExtSymbols(loader, list, ext);
  };

  const auto fnLoadForFeature = [&](const SymLoadStruct* list,
                                    GLFeature feature) {
    return this->LoadFeatureSymbols(loader, list, feature);
  };

  const auto fnLoadFeatureByCore = [&](const SymLoadStruct* coreList,
                                       const SymLoadStruct* extList,
                                       GLFeature feature) {
    const bool useCore = this->IsFeatureProvidedByCoreSymbols(feature);
    const auto list = useCore ? coreList : extList;
    return fnLoadForFeature(list, feature);
  };

  if (IsSupported(GLFeature::robustness)) {
    const auto resetStrategy =
        GetIntAs<GLuint>(LOCAL_GL_RESET_NOTIFICATION_STRATEGY);
    if (resetStrategy != LOCAL_GL_LOSE_CONTEXT_ON_RESET) {
      NS_WARNING(
          "Robustness supported, strategy is not LOSE_CONTEXT_ON_RESET!");
      if (ShouldSpew()) {
        const bool isDisabled =
            (resetStrategy == LOCAL_GL_NO_RESET_NOTIFICATION);
        printf_stderr("Strategy: %s (0x%04x)",
                      (isDisabled ? "disabled" : "unrecognized"),
                      resetStrategy);
      }
      MarkUnsupported(GLFeature::robustness);
    }
  }

  if (IsSupported(GLFeature::sync)) {
    const SymLoadStruct symbols[] = {
        CORE_SYMBOL(FenceSync),  CORE_SYMBOL(IsSync),
        CORE_SYMBOL(DeleteSync), CORE_SYMBOL(ClientWaitSync),
        CORE_SYMBOL(WaitSync),   CORE_SYMBOL(GetInteger64v),
        CORE_SYMBOL(GetSynciv),  END_SYMBOLS};
    fnLoadForFeature(symbols, GLFeature::sync);
  }

  if (IsExtensionSupported(OES_EGL_image)) {
    const SymLoadStruct symbols[] = {
        {(PRFuncPtr*)&mSymbols.fEGLImageTargetTexture2D,
         {{"glEGLImageTargetTexture2DOES"}}},
        {(PRFuncPtr*)&mSymbols.fEGLImageTargetRenderbufferStorage,
         {{"glEGLImageTargetRenderbufferStorageOES"}}},
        END_SYMBOLS};
    fnLoadForExt(symbols, OES_EGL_image);
  }

  if (IsExtensionSupported(APPLE_texture_range)) {
    const SymLoadStruct symbols[] = {CORE_SYMBOL(TextureRangeAPPLE),
                                     END_SYMBOLS};
    fnLoadForExt(symbols, APPLE_texture_range);
  }

  if (IsExtensionSupported(APPLE_fence)) {
    const SymLoadStruct symbols[] = {CORE_SYMBOL(FinishObjectAPPLE),
                                     CORE_SYMBOL(TestObjectAPPLE), END_SYMBOLS};
    fnLoadForExt(symbols, APPLE_fence);
  }

  // clang-format off

    if (IsSupported(GLFeature::vertex_array_object)) {
        const SymLoadStruct coreSymbols[] = {
            { (PRFuncPtr*) &mSymbols.fIsVertexArray, {{ "glIsVertexArray" }} },
            { (PRFuncPtr*) &mSymbols.fGenVertexArrays, {{ "glGenVertexArrays" }} },
            { (PRFuncPtr*) &mSymbols.fBindVertexArray, {{ "glBindVertexArray" }} },
            { (PRFuncPtr*) &mSymbols.fDeleteVertexArrays, {{ "glDeleteVertexArrays" }} },
            END_SYMBOLS
        };
        const SymLoadStruct extSymbols[] = {
            { (PRFuncPtr*) &mSymbols.fIsVertexArray, {{ "glIsVertexArrayARB", "glIsVertexArrayOES", "glIsVertexArrayAPPLE" }} },
            { (PRFuncPtr*) &mSymbols.fGenVertexArrays, {{ "glGenVertexArraysARB", "glGenVertexArraysOES", "glGenVertexArraysAPPLE" }} },
            { (PRFuncPtr*) &mSymbols.fBindVertexArray, {{ "glBindVertexArrayARB", "glBindVertexArrayOES", "glBindVertexArrayAPPLE" }} },
            { (PRFuncPtr*) &mSymbols.fDeleteVertexArrays, {{ "glDeleteVertexArraysARB", "glDeleteVertexArraysOES", "glDeleteVertexArraysAPPLE" }} },
            END_SYMBOLS
        };
        fnLoadFeatureByCore(coreSymbols, extSymbols, GLFeature::vertex_array_object);
    }

    if (IsSupported(GLFeature::draw_instanced)) {
        const SymLoadStruct coreSymbols[] = {
            { (PRFuncPtr*) &mSymbols.fDrawArraysInstanced, {{ "glDrawArraysInstanced" }} },
            { (PRFuncPtr*) &mSymbols.fDrawElementsInstanced, {{ "glDrawElementsInstanced" }} },
            END_SYMBOLS
        };
        const SymLoadStruct extSymbols[] = {
            { (PRFuncPtr*) &mSymbols.fDrawArraysInstanced, {{ "glDrawArraysInstancedARB", "glDrawArraysInstancedEXT", "glDrawArraysInstancedNV", "glDrawArraysInstancedANGLE" }} },
            { (PRFuncPtr*) &mSymbols.fDrawElementsInstanced, {{ "glDrawElementsInstancedARB", "glDrawElementsInstancedEXT", "glDrawElementsInstancedNV", "glDrawElementsInstancedANGLE" }}
            },
            END_SYMBOLS
        };
        fnLoadFeatureByCore(coreSymbols, extSymbols, GLFeature::draw_instanced);
    }

    if (IsSupported(GLFeature::instanced_arrays)) {
        const SymLoadStruct coreSymbols[] = {
            { (PRFuncPtr*) &mSymbols.fVertexAttribDivisor, {{ "glVertexAttribDivisor" }} },
            END_SYMBOLS
        };
        const SymLoadStruct extSymbols[] = {
            { (PRFuncPtr*) &mSymbols.fVertexAttribDivisor, {{ "glVertexAttribDivisorARB", "glVertexAttribDivisorNV", "glVertexAttribDivisorANGLE" }} },
            END_SYMBOLS
        };
        fnLoadFeatureByCore(coreSymbols, extSymbols, GLFeature::instanced_arrays);
    }

    if (IsSupported(GLFeature::texture_storage)) {
        const SymLoadStruct coreSymbols[] = {
            { (PRFuncPtr*) &mSymbols.fTexStorage2D, {{ "glTexStorage2D" }} },
            { (PRFuncPtr*) &mSymbols.fTexStorage3D, {{ "glTexStorage3D" }} },
            END_SYMBOLS
        };
        const SymLoadStruct extSymbols[] = {
            { (PRFuncPtr*) &mSymbols.fTexStorage2D, {{ "glTexStorage2DEXT" }} },
            { (PRFuncPtr*) &mSymbols.fTexStorage3D, {{ "glTexStorage3DEXT" }} },
            END_SYMBOLS
        };
        fnLoadFeatureByCore(coreSymbols, extSymbols, GLFeature::texture_storage);
    }

    if (IsSupported(GLFeature::sampler_objects)) {
        const SymLoadStruct symbols[] = {
            { (PRFuncPtr*) &mSymbols.fGenSamplers, {{ "glGenSamplers" }} },
            { (PRFuncPtr*) &mSymbols.fDeleteSamplers, {{ "glDeleteSamplers" }} },
            { (PRFuncPtr*) &mSymbols.fIsSampler, {{ "glIsSampler" }} },
            { (PRFuncPtr*) &mSymbols.fBindSampler, {{ "glBindSampler" }} },
            { (PRFuncPtr*) &mSymbols.fSamplerParameteri, {{ "glSamplerParameteri" }} },
            { (PRFuncPtr*) &mSymbols.fSamplerParameteriv, {{ "glSamplerParameteriv" }} },
            { (PRFuncPtr*) &mSymbols.fSamplerParameterf, {{ "glSamplerParameterf" }} },
            { (PRFuncPtr*) &mSymbols.fSamplerParameterfv, {{ "glSamplerParameterfv" }} },
            { (PRFuncPtr*) &mSymbols.fGetSamplerParameteriv, {{ "glGetSamplerParameteriv" }} },
            { (PRFuncPtr*) &mSymbols.fGetSamplerParameterfv, {{ "glGetSamplerParameterfv" }} },
            END_SYMBOLS
        };
        fnLoadForFeature(symbols, GLFeature::sampler_objects);
    }

    // ARB_transform_feedback2/NV_transform_feedback2 is a
    // superset of EXT_transform_feedback/NV_transform_feedback
    // and adds glPauseTransformFeedback &
    // glResumeTransformFeedback, which are required for WebGL2.
    if (IsSupported(GLFeature::transform_feedback2)) {
        const SymLoadStruct coreSymbols[] = {
            { (PRFuncPtr*) &mSymbols.fBindBufferBase, {{ "glBindBufferBase" }} },
            { (PRFuncPtr*) &mSymbols.fBindBufferRange, {{ "glBindBufferRange" }} },
            { (PRFuncPtr*) &mSymbols.fGenTransformFeedbacks, {{ "glGenTransformFeedbacks" }} },
            { (PRFuncPtr*) &mSymbols.fBindTransformFeedback, {{ "glBindTransformFeedback" }} },
            { (PRFuncPtr*) &mSymbols.fDeleteTransformFeedbacks, {{ "glDeleteTransformFeedbacks" }} },
            { (PRFuncPtr*) &mSymbols.fIsTransformFeedback, {{ "glIsTransformFeedback" }} },
            { (PRFuncPtr*) &mSymbols.fBeginTransformFeedback, {{ "glBeginTransformFeedback" }} },
            { (PRFuncPtr*) &mSymbols.fEndTransformFeedback, {{ "glEndTransformFeedback" }} },
            { (PRFuncPtr*) &mSymbols.fTransformFeedbackVaryings, {{ "glTransformFeedbackVaryings" }} },
            { (PRFuncPtr*) &mSymbols.fGetTransformFeedbackVarying, {{ "glGetTransformFeedbackVarying" }} },
            { (PRFuncPtr*) &mSymbols.fPauseTransformFeedback, {{ "glPauseTransformFeedback" }} },
            { (PRFuncPtr*) &mSymbols.fResumeTransformFeedback, {{ "glResumeTransformFeedback" }} },
            END_SYMBOLS
        };
        const SymLoadStruct extSymbols[] = {
            { (PRFuncPtr*) &mSymbols.fBindBufferBase, {{ "glBindBufferBaseEXT", "glBindBufferBaseNV" }} },
            { (PRFuncPtr*) &mSymbols.fBindBufferRange, {{ "glBindBufferRangeEXT", "glBindBufferRangeNV" }} },
            { (PRFuncPtr*) &mSymbols.fGenTransformFeedbacks, {{ "glGenTransformFeedbacksNV" }} },
            { (PRFuncPtr*) &mSymbols.fBindTransformFeedback, {{ "glBindTransformFeedbackNV" }} },
            { (PRFuncPtr*) &mSymbols.fDeleteTransformFeedbacks, {{ "glDeleteTransformFeedbacksNV" }} },
            { (PRFuncPtr*) &mSymbols.fIsTransformFeedback, {{ "glIsTransformFeedbackNV" }} },
            { (PRFuncPtr*) &mSymbols.fBeginTransformFeedback, {{ "glBeginTransformFeedbackEXT", "glBeginTransformFeedbackNV" }} },
            { (PRFuncPtr*) &mSymbols.fEndTransformFeedback, {{ "glEndTransformFeedbackEXT", "glEndTransformFeedbackNV" }} },
            { (PRFuncPtr*) &mSymbols.fTransformFeedbackVaryings, {{ "glTransformFeedbackVaryingsEXT", "glTransformFeedbackVaryingsNV" }} },
            { (PRFuncPtr*) &mSymbols.fGetTransformFeedbackVarying, {{ "glGetTransformFeedbackVaryingEXT", "glGetTransformFeedbackVaryingNV" }} },
            { (PRFuncPtr*) &mSymbols.fPauseTransformFeedback, {{ "glPauseTransformFeedbackNV" }} },
            { (PRFuncPtr*) &mSymbols.fResumeTransformFeedback, {{ "glResumeTransformFeedbackNV" }} },
            END_SYMBOLS
        };
        if (!fnLoadFeatureByCore(coreSymbols, extSymbols, GLFeature::transform_feedback2)) {
            // Also mark bind_buffer_offset as unsupported.
            MarkUnsupported(GLFeature::bind_buffer_offset);
        }
    }

    if (IsSupported(GLFeature::bind_buffer_offset)) {
        const SymLoadStruct coreSymbols[] = {
            { (PRFuncPtr*) &mSymbols.fBindBufferOffset, {{ "glBindBufferOffset" }} },
            END_SYMBOLS
        };
        const SymLoadStruct extSymbols[] = {
            { (PRFuncPtr*) &mSymbols.fBindBufferOffset,
              {{ "glBindBufferOffsetEXT", "glBindBufferOffsetNV" }}
            },
            END_SYMBOLS
        };
        fnLoadFeatureByCore(coreSymbols, extSymbols, GLFeature::bind_buffer_offset);
    }

    if (IsSupported(GLFeature::query_counter)) {
        const SymLoadStruct coreSymbols[] = {
            { (PRFuncPtr*) &mSymbols.fQueryCounter, {{ "glQueryCounter" }} },
            END_SYMBOLS
        };
        const SymLoadStruct extSymbols[] = {
            { (PRFuncPtr*) &mSymbols.fQueryCounter, {{ "glQueryCounterEXT", "glQueryCounterANGLE" }} },
            END_SYMBOLS
        };
        fnLoadFeatureByCore(coreSymbols, extSymbols, GLFeature::query_counter);
    }

    if (IsSupported(GLFeature::query_objects)) {
        const SymLoadStruct coreSymbols[] = {
            { (PRFuncPtr*) &mSymbols.fBeginQuery, {{ "glBeginQuery" }} },
            { (PRFuncPtr*) &mSymbols.fGenQueries, {{ "glGenQueries" }} },
            { (PRFuncPtr*) &mSymbols.fDeleteQueries, {{ "glDeleteQueries" }} },
            { (PRFuncPtr*) &mSymbols.fEndQuery, {{ "glEndQuery" }} },
            { (PRFuncPtr*) &mSymbols.fGetQueryiv, {{ "glGetQueryiv" }} },
            { (PRFuncPtr*) &mSymbols.fGetQueryObjectuiv, {{ "glGetQueryObjectuiv" }} },
            { (PRFuncPtr*) &mSymbols.fIsQuery, {{ "glIsQuery" }} },
            END_SYMBOLS
        };
        const SymLoadStruct extSymbols[] = {
            { (PRFuncPtr*) &mSymbols.fBeginQuery, {{ "glBeginQueryEXT", "glBeginQueryANGLE" }} },
            { (PRFuncPtr*) &mSymbols.fGenQueries, {{ "glGenQueriesEXT", "glGenQueriesANGLE" }} },
            { (PRFuncPtr*) &mSymbols.fDeleteQueries, {{ "glDeleteQueriesEXT", "glDeleteQueriesANGLE" }} },
            { (PRFuncPtr*) &mSymbols.fEndQuery, {{ "glEndQueryEXT", "glEndQueryANGLE" }} },
            { (PRFuncPtr*) &mSymbols.fGetQueryiv, {{ "glGetQueryivEXT", "glGetQueryivANGLE" }} },
            { (PRFuncPtr*) &mSymbols.fGetQueryObjectuiv, {{ "glGetQueryObjectuivEXT", "glGetQueryObjectuivANGLE" }} },
            { (PRFuncPtr*) &mSymbols.fIsQuery, {{ "glIsQueryEXT", "glIsQueryANGLE" }} },
            END_SYMBOLS
        };
        if (!fnLoadFeatureByCore(coreSymbols, extSymbols, GLFeature::query_objects)) {
            MarkUnsupported(GLFeature::get_query_object_i64v);
            MarkUnsupported(GLFeature::get_query_object_iv);
            MarkUnsupported(GLFeature::occlusion_query);
            MarkUnsupported(GLFeature::occlusion_query_boolean);
            MarkUnsupported(GLFeature::occlusion_query2);
        }
    }

    if (IsSupported(GLFeature::get_query_object_i64v)) {
        const SymLoadStruct coreSymbols[] = {
            { (PRFuncPtr*) &mSymbols.fGetQueryObjecti64v, {{ "glGetQueryObjecti64v" }} },
            { (PRFuncPtr*) &mSymbols.fGetQueryObjectui64v, {{ "glGetQueryObjectui64v" }} },
            END_SYMBOLS
        };
        const SymLoadStruct extSymbols[] = {
            { (PRFuncPtr*) &mSymbols.fGetQueryObjecti64v, {{ "glGetQueryObjecti64vEXT", "glGetQueryObjecti64vANGLE" }} },
            { (PRFuncPtr*) &mSymbols.fGetQueryObjectui64v, {{ "glGetQueryObjectui64vEXT", "glGetQueryObjectui64vANGLE" }} },
            END_SYMBOLS
        };
        if (!fnLoadFeatureByCore(coreSymbols, extSymbols, GLFeature::get_query_object_i64v)) {
            MarkUnsupported(GLFeature::query_counter);
        }
    }

    if (IsSupported(GLFeature::get_query_object_iv)) {
        const SymLoadStruct coreSymbols[] = {
            { (PRFuncPtr*) &mSymbols.fGetQueryObjectiv, {{ "glGetQueryObjectiv" }} },
            END_SYMBOLS
        };
        const SymLoadStruct extSymbols[] = {
            { (PRFuncPtr*) &mSymbols.fGetQueryObjectiv, {{ "glGetQueryObjectivEXT", "glGetQueryObjectivANGLE" }} },
            END_SYMBOLS
        };
        fnLoadFeatureByCore(coreSymbols, extSymbols, GLFeature::get_query_object_iv);
    }

    if (IsSupported(GLFeature::clear_buffers)) {
        const SymLoadStruct symbols[] = {
            { (PRFuncPtr*) &mSymbols.fClearBufferfi,  {{ "glClearBufferfi",  }} },
            { (PRFuncPtr*) &mSymbols.fClearBufferfv,  {{ "glClearBufferfv",  }} },
            { (PRFuncPtr*) &mSymbols.fClearBufferiv,  {{ "glClearBufferiv",  }} },
            { (PRFuncPtr*) &mSymbols.fClearBufferuiv, {{ "glClearBufferuiv" }} },
            END_SYMBOLS
        };
        fnLoadForFeature(symbols, GLFeature::clear_buffers);
    }

    if (IsSupported(GLFeature::copy_buffer)) {
        const SymLoadStruct symbols[] = {
            { (PRFuncPtr*) &mSymbols.fCopyBufferSubData, {{ "glCopyBufferSubData" }} },
            END_SYMBOLS
        };
        fnLoadForFeature(symbols, GLFeature::copy_buffer);
    }

    if (IsSupported(GLFeature::draw_buffers)) {
        const SymLoadStruct coreSymbols[] = {
            { (PRFuncPtr*) &mSymbols.fDrawBuffers, {{ "glDrawBuffers" }} },
            END_SYMBOLS
        };
        const SymLoadStruct extSymbols[] = {
            { (PRFuncPtr*) &mSymbols.fDrawBuffers, {{ "glDrawBuffersARB", "glDrawBuffersEXT" }} },
            END_SYMBOLS
        };
        fnLoadFeatureByCore(coreSymbols, extSymbols, GLFeature::draw_buffers);
    }

    if (IsSupported(GLFeature::draw_buffers_indexed)) {
        const SymLoadStruct coreSymbols[] = {
            { (PRFuncPtr*) &mSymbols.fBlendEquationSeparatei, {{ "glBlendEquationSeparatei" }} },
            { (PRFuncPtr*) &mSymbols.fBlendFuncSeparatei, {{ "glBlendFuncSeparatei" }} },
            { (PRFuncPtr*) &mSymbols.fColorMaski, {{ "glColorMaski" }} },
            { (PRFuncPtr*) &mSymbols.fDisablei, {{ "glDisablei" }} },
            { (PRFuncPtr*) &mSymbols.fEnablei, {{ "glEnablei" }} },
            END_SYMBOLS
        };
        const SymLoadStruct extSymbols[] = {
            { (PRFuncPtr*) &mSymbols.fBlendEquationSeparatei, {{ "glBlendEquationSeparateiOES" }} },
            { (PRFuncPtr*) &mSymbols.fBlendFuncSeparatei, {{ "glBlendFuncSeparateiOES" }} },
            { (PRFuncPtr*) &mSymbols.fColorMaski, {{ "glColorMaskiOES" }} },
            { (PRFuncPtr*) &mSymbols.fDisablei, {{ "glDisableiOES" }} },
            { (PRFuncPtr*) &mSymbols.fEnablei, {{ "glEnableiOES" }} },
            END_SYMBOLS
        };
        fnLoadFeatureByCore(coreSymbols, extSymbols, GLFeature::draw_buffers_indexed);
    }

    if (IsSupported(GLFeature::get_integer_indexed)) {
        const SymLoadStruct coreSymbols[] = {
            { (PRFuncPtr*) &mSymbols.fGetIntegeri_v, {{ "glGetIntegeri_v" }} },
            END_SYMBOLS
        };
        const SymLoadStruct extSymbols[] ={
            { (PRFuncPtr*) &mSymbols.fGetIntegeri_v, {{ "glGetIntegerIndexedvEXT" }} },
            END_SYMBOLS
        };
        fnLoadFeatureByCore(coreSymbols, extSymbols, GLFeature::get_integer_indexed);
    }

    if (IsSupported(GLFeature::get_integer64_indexed)) {
        const SymLoadStruct symbols[] = {
            { (PRFuncPtr*) &mSymbols.fGetInteger64i_v, {{ "glGetInteger64i_v" }} },
            END_SYMBOLS
        };
        fnLoadForFeature(symbols, GLFeature::get_integer64_indexed);
    }

    if (IsSupported(GLFeature::gpu_shader4)) {
        const SymLoadStruct symbols[] = {
            { (PRFuncPtr*) &mSymbols.fGetVertexAttribIiv, {{ "glGetVertexAttribIiv", "glGetVertexAttribIivEXT" }} },
            { (PRFuncPtr*) &mSymbols.fGetVertexAttribIuiv, {{ "glGetVertexAttribIuiv", "glGetVertexAttribIuivEXT" }} },
            { (PRFuncPtr*) &mSymbols.fVertexAttribI4i, {{ "glVertexAttribI4i", "glVertexAttribI4iEXT" }} },
            { (PRFuncPtr*) &mSymbols.fVertexAttribI4iv, {{ "glVertexAttribI4iv", "glVertexAttribI4ivEXT" }} },
            { (PRFuncPtr*) &mSymbols.fVertexAttribI4ui, {{ "glVertexAttribI4ui", "glVertexAttribI4uiEXT" }} },
            { (PRFuncPtr*) &mSymbols.fVertexAttribI4uiv, {{ "glVertexAttribI4uiv", "glVertexAttribI4uivEXT" }} },
            { (PRFuncPtr*) &mSymbols.fVertexAttribIPointer, {{ "glVertexAttribIPointer", "glVertexAttribIPointerEXT" }} },
            { (PRFuncPtr*) &mSymbols.fUniform1ui,  {{ "glUniform1ui", "glUniform1uiEXT" }} },
            { (PRFuncPtr*) &mSymbols.fUniform2ui,  {{ "glUniform2ui", "glUniform2uiEXT" }} },
            { (PRFuncPtr*) &mSymbols.fUniform3ui,  {{ "glUniform3ui", "glUniform3uiEXT" }} },
            { (PRFuncPtr*) &mSymbols.fUniform4ui,  {{ "glUniform4ui", "glUniform4uiEXT" }} },
            { (PRFuncPtr*) &mSymbols.fUniform1uiv, {{ "glUniform1uiv", "glUniform1uivEXT" }} },
            { (PRFuncPtr*) &mSymbols.fUniform2uiv, {{ "glUniform2uiv", "glUniform2uivEXT" }} },
            { (PRFuncPtr*) &mSymbols.fUniform3uiv, {{ "glUniform3uiv", "glUniform3uivEXT" }} },
            { (PRFuncPtr*) &mSymbols.fUniform4uiv, {{ "glUniform4uiv", "glUniform4uivEXT" }} },
            { (PRFuncPtr*) &mSymbols.fGetFragDataLocation, {{ "glGetFragDataLocation", "glGetFragDataLocationEXT" }} },
            { (PRFuncPtr*) &mSymbols.fGetUniformuiv, {{ "glGetUniformuiv", "glGetUniformuivEXT" }} },
            END_SYMBOLS
        };
        fnLoadForFeature(symbols, GLFeature::gpu_shader4);
    }

    if (IsSupported(GLFeature::map_buffer_range)) {
        const SymLoadStruct symbols[] = {
            { (PRFuncPtr*) &mSymbols.fMapBufferRange, {{ "glMapBufferRange" }} },
            { (PRFuncPtr*) &mSymbols.fFlushMappedBufferRange, {{ "glFlushMappedBufferRange" }} },
            { (PRFuncPtr*) &mSymbols.fUnmapBuffer, {{ "glUnmapBuffer" }} },
            END_SYMBOLS
        };
        fnLoadForFeature(symbols, GLFeature::map_buffer_range);
    }

    if (IsSupported(GLFeature::texture_3D)) {
        const SymLoadStruct coreSymbols[] = {
            { (PRFuncPtr*) &mSymbols.fTexImage3D, {{ "glTexImage3D" }} },
            { (PRFuncPtr*) &mSymbols.fTexSubImage3D, {{ "glTexSubImage3D" }} },
            END_SYMBOLS
        };
        const SymLoadStruct extSymbols[] = {
            { (PRFuncPtr*) &mSymbols.fTexImage3D, {{ "glTexImage3DOES" }} },
            { (PRFuncPtr*) &mSymbols.fTexSubImage3D, {{ "glTexSubImage3DOES" }} },
            END_SYMBOLS
        };
        fnLoadFeatureByCore(coreSymbols, extSymbols, GLFeature::texture_3D);
    }

    if (IsSupported(GLFeature::texture_3D_compressed)) {
        const SymLoadStruct coreSymbols[] = {
            { (PRFuncPtr*) &mSymbols.fCompressedTexImage3D, {{ "glCompressedTexImage3D" }} },
            { (PRFuncPtr*) &mSymbols.fCompressedTexSubImage3D, {{ "glCompressedTexSubImage3D" }} },
            END_SYMBOLS
        };
        const SymLoadStruct extSymbols[] = {
            { (PRFuncPtr*) &mSymbols.fCompressedTexImage3D, {{ "glCompressedTexImage3DARB", "glCompressedTexImage3DOES" }} },
            { (PRFuncPtr*) &mSymbols.fCompressedTexSubImage3D, {{ "glCompressedTexSubImage3DARB", "glCompressedTexSubImage3DOES" }} },
            END_SYMBOLS
        };
        fnLoadFeatureByCore(coreSymbols, extSymbols, GLFeature::texture_3D_compressed);
    }

    if (IsSupported(GLFeature::texture_3D_copy)) {
        const SymLoadStruct coreSymbols[] = {
            { (PRFuncPtr*) &mSymbols.fCopyTexSubImage3D, {{ "glCopyTexSubImage3D" }} },
            END_SYMBOLS
        };
        const SymLoadStruct extSymbols[] = {
            { (PRFuncPtr*) &mSymbols.fCopyTexSubImage3D, {{ "glCopyTexSubImage3DEXT", "glCopyTexSubImage3DOES" }} },
            END_SYMBOLS
        };
        fnLoadFeatureByCore(coreSymbols, extSymbols, GLFeature::texture_3D_copy);
    }

    if (IsSupported(GLFeature::uniform_buffer_object)) {
        // Note: Don't query for glGetActiveUniformName because it is not
        // supported by GL ES 3.
        const SymLoadStruct symbols[] = {
            { (PRFuncPtr*) &mSymbols.fGetUniformIndices, {{ "glGetUniformIndices" }} },
            { (PRFuncPtr*) &mSymbols.fGetActiveUniformsiv, {{ "glGetActiveUniformsiv" }} },
            { (PRFuncPtr*) &mSymbols.fGetUniformBlockIndex, {{ "glGetUniformBlockIndex" }} },
            { (PRFuncPtr*) &mSymbols.fGetActiveUniformBlockiv, {{ "glGetActiveUniformBlockiv" }} },
            { (PRFuncPtr*) &mSymbols.fGetActiveUniformBlockName, {{ "glGetActiveUniformBlockName" }} },
            { (PRFuncPtr*) &mSymbols.fUniformBlockBinding, {{ "glUniformBlockBinding" }} },
            END_SYMBOLS
        };
        fnLoadForFeature(symbols, GLFeature::uniform_buffer_object);
    }

    if (IsSupported(GLFeature::uniform_matrix_nonsquare)) {
        const SymLoadStruct symbols[] = {
            { (PRFuncPtr*) &mSymbols.fUniformMatrix2x3fv, {{ "glUniformMatrix2x3fv" }} },
            { (PRFuncPtr*) &mSymbols.fUniformMatrix2x4fv, {{ "glUniformMatrix2x4fv" }} },
            { (PRFuncPtr*) &mSymbols.fUniformMatrix3x2fv, {{ "glUniformMatrix3x2fv" }} },
            { (PRFuncPtr*) &mSymbols.fUniformMatrix3x4fv, {{ "glUniformMatrix3x4fv" }} },
            { (PRFuncPtr*) &mSymbols.fUniformMatrix4x2fv, {{ "glUniformMatrix4x2fv" }} },
            { (PRFuncPtr*) &mSymbols.fUniformMatrix4x3fv, {{ "glUniformMatrix4x3fv" }} },
            END_SYMBOLS
        };
        fnLoadForFeature(symbols, GLFeature::uniform_matrix_nonsquare);
    }

    if (IsSupported(GLFeature::internalformat_query)) {
        const SymLoadStruct symbols[] = {
            CORE_SYMBOL(GetInternalformativ),
            END_SYMBOLS
        };
        fnLoadForFeature(symbols, GLFeature::internalformat_query);
    }

    if (IsSupported(GLFeature::invalidate_framebuffer)) {
        const SymLoadStruct symbols[] = {
            { (PRFuncPtr*) &mSymbols.fInvalidateFramebuffer,    {{ "glInvalidateFramebuffer" }} },
            { (PRFuncPtr*) &mSymbols.fInvalidateSubFramebuffer, {{ "glInvalidateSubFramebuffer" }} },
            END_SYMBOLS
        };
        fnLoadForFeature(symbols, GLFeature::invalidate_framebuffer);
    }

    if (IsSupported(GLFeature::multiview)) {
        const SymLoadStruct symbols[] = {
            { (PRFuncPtr*) &mSymbols.fFramebufferTextureMultiview, {{
              "glFramebufferTextureMultiviewOVR",
              "glFramebufferTextureMultiviewLayeredANGLE"
            }} },
            END_SYMBOLS
        };
        fnLoadForFeature(symbols, GLFeature::multiview);
    }

    if (IsSupported(GLFeature::prim_restart)) {
        const SymLoadStruct symbols[] = {
            { (PRFuncPtr*) &mSymbols.fPrimitiveRestartIndex,    {{ "glPrimitiveRestartIndex", "glPrimitiveRestartIndexNV" }} },
            END_SYMBOLS
        };
        fnLoadForFeature(symbols, GLFeature::prim_restart);
    }

    if (IsExtensionSupported(KHR_debug)) {
        const SymLoadStruct symbols[] = {
            { (PRFuncPtr*) &mSymbols.fDebugMessageControl,  {{ "glDebugMessageControl",  "glDebugMessageControlKHR", }} },
            { (PRFuncPtr*) &mSymbols.fDebugMessageInsert,   {{ "glDebugMessageInsert",   "glDebugMessageInsertKHR",  }} },
            { (PRFuncPtr*) &mSymbols.fDebugMessageCallback, {{ "glDebugMessageCallback", "glDebugMessageCallbackKHR" }} },
            { (PRFuncPtr*) &mSymbols.fGetDebugMessageLog,   {{ "glGetDebugMessageLog",   "glGetDebugMessageLogKHR",  }} },
            { (PRFuncPtr*) &mSymbols.fGetPointerv,          {{ "glGetPointerv",          "glGetPointervKHR",         }} },
            { (PRFuncPtr*) &mSymbols.fPushDebugGroup,       {{ "glPushDebugGroup",       "glPushDebugGroupKHR",      }} },
            { (PRFuncPtr*) &mSymbols.fPopDebugGroup,        {{ "glPopDebugGroup",        "glPopDebugGroupKHR",       }} },
            { (PRFuncPtr*) &mSymbols.fObjectLabel,          {{ "glObjectLabel",          "glObjectLabelKHR",         }} },
            { (PRFuncPtr*) &mSymbols.fGetObjectLabel,       {{ "glGetObjectLabel",       "glGetObjectLabelKHR",      }} },
            { (PRFuncPtr*) &mSymbols.fObjectPtrLabel,       {{ "glObjectPtrLabel",       "glObjectPtrLabelKHR",      }} },
            { (PRFuncPtr*) &mSymbols.fGetObjectPtrLabel,    {{ "glGetObjectPtrLabel",    "glGetObjectPtrLabelKHR",   }} },
            END_SYMBOLS
        };
        fnLoadForExt(symbols, KHR_debug);
    }

    if (IsExtensionSupported(NV_fence)) {
        const SymLoadStruct symbols[] = {
            { (PRFuncPtr*) &mSymbols.fGenFences,    {{ "glGenFencesNV"    }} },
            { (PRFuncPtr*) &mSymbols.fDeleteFences, {{ "glDeleteFencesNV" }} },
            { (PRFuncPtr*) &mSymbols.fSetFence,     {{ "glSetFenceNV"     }} },
            { (PRFuncPtr*) &mSymbols.fTestFence,    {{ "glTestFenceNV"    }} },
            { (PRFuncPtr*) &mSymbols.fFinishFence,  {{ "glFinishFenceNV"  }} },
            { (PRFuncPtr*) &mSymbols.fIsFence,      {{ "glIsFenceNV"      }} },
            { (PRFuncPtr*) &mSymbols.fGetFenceiv,   {{ "glGetFenceivNV"   }} },
            END_SYMBOLS
        };
        fnLoadForExt(symbols, NV_fence);
    }

  // clang-format on

  if (IsExtensionSupported(NV_texture_barrier)) {
    const SymLoadStruct symbols[] = {
        {(PRFuncPtr*)&mSymbols.fTextureBarrier, {{"glTextureBarrierNV"}}},
        END_SYMBOLS};
    fnLoadForExt(symbols, NV_texture_barrier);
  }

  if (IsSupported(GLFeature::read_buffer)) {
    const SymLoadStruct symbols[] = {CORE_SYMBOL(ReadBuffer), END_SYMBOLS};
    fnLoadForFeature(symbols, GLFeature::read_buffer);
  }

  if (IsExtensionSupported(APPLE_framebuffer_multisample)) {
    const SymLoadStruct symbols[] = {
        CORE_SYMBOL(ResolveMultisampleFramebufferAPPLE), END_SYMBOLS};
    fnLoadForExt(symbols, APPLE_framebuffer_multisample);
  }

  if (IsSupported(GLFeature::provoking_vertex)) {
    const SymLoadStruct symbols[] = {{(PRFuncPtr*)&mSymbols.fProvokingVertex,
                                      {{
                                          "glProvokingVertex",
                                          "glProvokingVertexANGLE",
                                          "glProvokingVertexEXT",
                                      }}},
                                     END_SYMBOLS};
    fnLoadForFeature(symbols, GLFeature::provoking_vertex);
  }

  // Load developer symbols, don't fail if we can't find them.
  const SymLoadStruct devSymbols[] = {CORE_SYMBOL(GetTexImage),
                                      CORE_SYMBOL(GetTexLevelParameteriv),
                                      END_SYMBOLS};
  const bool warnOnFailures = ShouldSpew();
  (void)loader.LoadSymbols(devSymbols, warnOnFailures);
}

#undef CORE_SYMBOL
#undef CORE_EXT_SYMBOL2
#undef EXT_SYMBOL2
#undef EXT_SYMBOL3
#undef END_SYMBOLS

void GLContext::DebugCallback(GLenum source, GLenum type, GLuint id,
                              GLenum severity, GLsizei length,
                              const GLchar* message) {
  nsAutoCString sourceStr;
  switch (source) {
    case LOCAL_GL_DEBUG_SOURCE_API:
      sourceStr = "SOURCE_API"_ns;
      break;
    case LOCAL_GL_DEBUG_SOURCE_WINDOW_SYSTEM:
      sourceStr = "SOURCE_WINDOW_SYSTEM"_ns;
      break;
    case LOCAL_GL_DEBUG_SOURCE_SHADER_COMPILER:
      sourceStr = "SOURCE_SHADER_COMPILER"_ns;
      break;
    case LOCAL_GL_DEBUG_SOURCE_THIRD_PARTY:
      sourceStr = "SOURCE_THIRD_PARTY"_ns;
      break;
    case LOCAL_GL_DEBUG_SOURCE_APPLICATION:
      sourceStr = "SOURCE_APPLICATION"_ns;
      break;
    case LOCAL_GL_DEBUG_SOURCE_OTHER:
      sourceStr = "SOURCE_OTHER"_ns;
      break;
    default:
      sourceStr = nsPrintfCString("<source 0x%04x>", source);
      break;
  }

  nsAutoCString typeStr;
  switch (type) {
    case LOCAL_GL_DEBUG_TYPE_ERROR:
      typeStr = "TYPE_ERROR"_ns;
      break;
    case LOCAL_GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
      typeStr = "TYPE_DEPRECATED_BEHAVIOR"_ns;
      break;
    case LOCAL_GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:
      typeStr = "TYPE_UNDEFINED_BEHAVIOR"_ns;
      break;
    case LOCAL_GL_DEBUG_TYPE_PORTABILITY:
      typeStr = "TYPE_PORTABILITY"_ns;
      break;
    case LOCAL_GL_DEBUG_TYPE_PERFORMANCE:
      typeStr = "TYPE_PERFORMANCE"_ns;
      break;
    case LOCAL_GL_DEBUG_TYPE_OTHER:
      typeStr = "TYPE_OTHER"_ns;
      break;
    case LOCAL_GL_DEBUG_TYPE_MARKER:
      typeStr = "TYPE_MARKER"_ns;
      break;
    default:
      typeStr = nsPrintfCString("<type 0x%04x>", type);
      break;
  }

  nsAutoCString sevStr;
  switch (severity) {
    case LOCAL_GL_DEBUG_SEVERITY_HIGH:
      sevStr = "SEVERITY_HIGH"_ns;
      break;
    case LOCAL_GL_DEBUG_SEVERITY_MEDIUM:
      sevStr = "SEVERITY_MEDIUM"_ns;
      break;
    case LOCAL_GL_DEBUG_SEVERITY_LOW:
      sevStr = "SEVERITY_LOW"_ns;
      break;
    case LOCAL_GL_DEBUG_SEVERITY_NOTIFICATION:
      sevStr = "SEVERITY_NOTIFICATION"_ns;
      break;
    default:
      sevStr = nsPrintfCString("<severity 0x%04x>", severity);
      break;
  }

  printf_stderr("[KHR_debug: 0x%" PRIxPTR "] ID %u: %s, %s, %s:\n    %s\n",
                (uintptr_t)this, id, sourceStr.BeginReading(),
                typeStr.BeginReading(), sevStr.BeginReading(), message);
}

void GLContext::InitExtensions() {
  MOZ_GL_ASSERT(this, IsCurrent());

  std::vector<nsCString> driverExtensionList;

  [&]() {
    if (mSymbols.fGetStringi) {
      GLuint count = 0;
      if (GetPotentialInteger(LOCAL_GL_NUM_EXTENSIONS, (GLint*)&count)) {
        for (GLuint i = 0; i < count; i++) {
          // This is UTF-8.
          const char* rawExt = (const char*)fGetStringi(LOCAL_GL_EXTENSIONS, i);

          // We CANNOT use nsDependentCString here, because the spec doesn't
          // guarantee that the pointers returned are different, only that their
          // contents are. On Flame, each of these index string queries returns
          // the same address.
          driverExtensionList.push_back(nsCString(rawExt));
        }
        return;
      }
    }

    const char* rawExts = (const char*)fGetString(LOCAL_GL_EXTENSIONS);
    if (rawExts) {
      nsDependentCString exts(rawExts);
      SplitByChar(exts, ' ', &driverExtensionList);
    }
  }();
  const auto err = fGetError();
  MOZ_ALWAYS_TRUE(!IsBadCallError(err));

  const bool shouldDumpExts = ShouldDumpExts();
  if (shouldDumpExts) {
    printf_stderr("%i GL driver extensions: (*: recognized)\n",
                  (uint32_t)driverExtensionList.size());
  }

  MarkBitfieldByStrings(driverExtensionList, shouldDumpExts, sExtensionNames,
                        &mAvailableExtensions);

  if (WorkAroundDriverBugs()) {
    if (Vendor() == GLVendor::Qualcomm) {
      // Some Adreno drivers do not report GL_OES_EGL_sync, but they really do
      // support it.
      MarkExtensionSupported(OES_EGL_sync);
    }

    if (Vendor() == GLVendor::ATI) {
      // ATI drivers say this extension exists, but we can't
      // actually find the EGLImageTargetRenderbufferStorageOES
      // extension function pointer in the drivers.
      MarkExtensionUnsupported(OES_EGL_image);
    }

    if (Vendor() == GLVendor::Imagination && Renderer() == GLRenderer::SGX540) {
      // Bug 980048
      MarkExtensionUnsupported(OES_EGL_sync);
    }

#ifdef MOZ_WIDGET_ANDROID
    if (Vendor() == GLVendor::Imagination &&
        Renderer() == GLRenderer::SGX544MP && jni::GetAPIVersion() < 21) {
      // Bug 1026404
      MarkExtensionUnsupported(OES_EGL_image);
      MarkExtensionUnsupported(OES_EGL_image_external);
    }
#endif

    if (Vendor() == GLVendor::ARM && (Renderer() == GLRenderer::Mali400MP ||
                                      Renderer() == GLRenderer::Mali450MP)) {
      // Bug 1264505
      MarkExtensionUnsupported(OES_EGL_image_external);
    }

    if (Renderer() == GLRenderer::AndroidEmulator) {
      // the Android emulator, which we use to run B2G reftests on,
      // doesn't expose the OES_rgb8_rgba8 extension, but it seems to
      // support it (tautologically, as it only runs on desktop GL).
      MarkExtensionSupported(OES_rgb8_rgba8);
    }

    if (Vendor() == GLVendor::VMware &&
        Renderer() == GLRenderer::GalliumLlvmpipe) {
      // The llvmpipe driver that is used on linux try servers appears to have
      // buggy support for s3tc/dxt1 compressed textures.
      // See Bug 975824.
      MarkExtensionUnsupported(EXT_texture_compression_s3tc);
      MarkExtensionUnsupported(EXT_texture_compression_dxt1);
      MarkExtensionUnsupported(ANGLE_texture_compression_dxt3);
      MarkExtensionUnsupported(ANGLE_texture_compression_dxt5);
    }

#ifdef XP_MACOSX
    // Bug 1009642: On OSX Mavericks (10.9), the driver for Intel HD
    // 3000 appears to be buggy WRT updating sub-images of S3TC
    // textures with glCompressedTexSubImage2D. Works on Intel HD 4000
    // and Intel HD 5000/Iris that I tested.
    // Bug 1124996: Appears to be the same on OSX Yosemite (10.10)
    if (Renderer() == GLRenderer::IntelHD3000) {
      MarkExtensionUnsupported(EXT_texture_compression_s3tc);
    }

    // OSX supports EXT_texture_sRGB in Legacy contexts, but not in Core
    // contexts. Though EXT_texture_sRGB was included into GL2.1, it *excludes*
    // the interactions with s3tc. Strictly speaking, you must advertize support
    // for EXT_texture_sRGB in order to allow for srgb+s3tc on desktop GL. The
    // omission of EXT_texture_sRGB in OSX Core contexts appears to be a bug.
    MarkExtensionSupported(EXT_texture_sRGB);
#endif
  }

  if (shouldDumpExts) {
    printf_stderr("\nActivated extensions:\n");

    for (size_t i = 0; i < mAvailableExtensions.size(); i++) {
      if (!mAvailableExtensions[i]) continue;

      const char* ext = sExtensionNames[i];
      printf_stderr("[%i] %s\n", (uint32_t)i, ext);
    }
  }
}

void GLContext::PlatformStartup() {
  RegisterStrongMemoryReporter(new GfxTexturesReporter());
}

// Common code for checking for both GL extensions and GLX extensions.
bool GLContext::ListHasExtension(const GLubyte* extensions,
                                 const char* extension) {
  // fix bug 612572 - we were crashing as we were calling this function with
  // extensions==null
  if (extensions == nullptr || extension == nullptr) return false;

  const GLubyte* start;
  GLubyte* where;
  GLubyte* terminator;

  /* Extension names should not have spaces. */
  where = (GLubyte*)strchr(extension, ' ');
  if (where || *extension == '\0') return false;

  /*
   * It takes a bit of care to be fool-proof about parsing the
   * OpenGL extensions string. Don't be fooled by sub-strings,
   * etc.
   */
  start = extensions;
  for (;;) {
    where = (GLubyte*)strstr((const char*)start, extension);
    if (!where) {
      break;
    }
    terminator = where + strlen(extension);
    if (where == start || *(where - 1) == ' ') {
      if (*terminator == ' ' || *terminator == '\0') {
        return true;
      }
    }
    start = terminator;
  }
  return false;
}

bool GLContext::IsFramebufferComplete(GLuint fb, GLenum* pStatus) {
  MOZ_ASSERT(fb);

  ScopedBindFramebuffer autoFB(this, fb);
  MOZ_GL_ASSERT(this, fIsFramebuffer(fb));

  GLenum status = fCheckFramebufferStatus(LOCAL_GL_FRAMEBUFFER);
  if (pStatus) *pStatus = status;

  return status == LOCAL_GL_FRAMEBUFFER_COMPLETE;
}

void GLContext::AttachBuffersToFB(GLuint colorTex, GLuint colorRB,
                                  GLuint depthRB, GLuint stencilRB, GLuint fb,
                                  GLenum target) {
  MOZ_ASSERT(fb);
  MOZ_ASSERT(!(colorTex && colorRB));

  ScopedBindFramebuffer autoFB(this, fb);
  MOZ_GL_ASSERT(this, fIsFramebuffer(fb));  // It only counts after being bound.

  if (colorTex) {
    MOZ_GL_ASSERT(this, fIsTexture(colorTex));
    MOZ_ASSERT(target == LOCAL_GL_TEXTURE_2D ||
               target == LOCAL_GL_TEXTURE_RECTANGLE_ARB);
    fFramebufferTexture2D(LOCAL_GL_FRAMEBUFFER, LOCAL_GL_COLOR_ATTACHMENT0,
                          target, colorTex, 0);
  } else if (colorRB) {
    // On the Android 4.3 emulator, IsRenderbuffer may return false incorrectly.
    MOZ_GL_ASSERT(this, fIsRenderbuffer(colorRB) ||
                            Renderer() == GLRenderer::AndroidEmulator);
    fFramebufferRenderbuffer(LOCAL_GL_FRAMEBUFFER, LOCAL_GL_COLOR_ATTACHMENT0,
                             LOCAL_GL_RENDERBUFFER, colorRB);
  }

  if (depthRB) {
    MOZ_GL_ASSERT(this, fIsRenderbuffer(depthRB) ||
                            Renderer() == GLRenderer::AndroidEmulator);
    fFramebufferRenderbuffer(LOCAL_GL_FRAMEBUFFER, LOCAL_GL_DEPTH_ATTACHMENT,
                             LOCAL_GL_RENDERBUFFER, depthRB);
  }

  if (stencilRB) {
    MOZ_GL_ASSERT(this, fIsRenderbuffer(stencilRB) ||
                            Renderer() == GLRenderer::AndroidEmulator);
    fFramebufferRenderbuffer(LOCAL_GL_FRAMEBUFFER, LOCAL_GL_STENCIL_ATTACHMENT,
                             LOCAL_GL_RENDERBUFFER, stencilRB);
  }
}

bool GLContext::AssembleOffscreenFBs(const GLuint colorMSRB,
                                     const GLuint depthRB,
                                     const GLuint stencilRB,
                                     const GLuint texture, GLuint* drawFB_out,
                                     GLuint* readFB_out) {
  if (!colorMSRB && !texture) {
    MOZ_ASSERT(!depthRB && !stencilRB);

    if (drawFB_out) *drawFB_out = 0;
    if (readFB_out) *readFB_out = 0;

    return true;
  }

  ScopedBindFramebuffer autoFB(this);

  GLuint drawFB = 0;
  GLuint readFB = 0;

  if (texture) {
    readFB = 0;
    fGenFramebuffers(1, &readFB);
    BindFB(readFB);
    fFramebufferTexture2D(LOCAL_GL_FRAMEBUFFER, LOCAL_GL_COLOR_ATTACHMENT0,
                          LOCAL_GL_TEXTURE_2D, texture, 0);
  }

  if (colorMSRB) {
    drawFB = 0;
    fGenFramebuffers(1, &drawFB);
    BindFB(drawFB);
    fFramebufferRenderbuffer(LOCAL_GL_FRAMEBUFFER, LOCAL_GL_COLOR_ATTACHMENT0,
                             LOCAL_GL_RENDERBUFFER, colorMSRB);
  } else {
    drawFB = readFB;
  }
  MOZ_ASSERT(GetIntAs<GLuint>(LOCAL_GL_FRAMEBUFFER_BINDING) == drawFB);

  if (depthRB) {
    fFramebufferRenderbuffer(LOCAL_GL_FRAMEBUFFER, LOCAL_GL_DEPTH_ATTACHMENT,
                             LOCAL_GL_RENDERBUFFER, depthRB);
  }

  if (stencilRB) {
    fFramebufferRenderbuffer(LOCAL_GL_FRAMEBUFFER, LOCAL_GL_STENCIL_ATTACHMENT,
                             LOCAL_GL_RENDERBUFFER, stencilRB);
  }

  // We should be all resized.  Check for framebuffer completeness.
  GLenum status;
  bool isComplete = true;

  if (!IsFramebufferComplete(drawFB, &status)) {
    NS_WARNING("DrawFBO: Incomplete");
#ifdef MOZ_GL_DEBUG_BUILD
    if (ShouldSpew()) {
      printf_stderr("Framebuffer status: %X\n", status);
    }
#endif
    isComplete = false;
  }

  if (!IsFramebufferComplete(readFB, &status)) {
    NS_WARNING("ReadFBO: Incomplete");
#ifdef MOZ_GL_DEBUG_BUILD
    if (ShouldSpew()) {
      printf_stderr("Framebuffer status: %X\n", status);
    }
#endif
    isComplete = false;
  }

  if (drawFB_out) {
    *drawFB_out = drawFB;
  } else if (drawFB) {
    MOZ_CRASH("drawFB created when not requested!");
  }

  if (readFB_out) {
    *readFB_out = readFB;
  } else if (readFB) {
    MOZ_CRASH("readFB created when not requested!");
  }

  return isComplete;
}

void GLContext::MarkDestroyed() {
  if (IsDestroyed()) return;

  OnMarkDestroyed();

  // Null these before they're naturally nulled after dtor, as we want GLContext
  // to still be alive in *their* dtors.
  mBlitHelper = nullptr;
  mReadTexImageHelper = nullptr;

  mContextLost = true;
  mSymbols = {};
}

// -

#ifdef MOZ_GL_DEBUG_BUILD
/* static */
void GLContext::AssertNotPassingStackBufferToTheGL(const void* ptr) {
  int somethingOnTheStack;
  const void* someStackPtr = &somethingOnTheStack;
  const int page_bits = 12;
  intptr_t page = reinterpret_cast<uintptr_t>(ptr) >> page_bits;
  intptr_t someStackPage =
      reinterpret_cast<uintptr_t>(someStackPtr) >> page_bits;
  uintptr_t pageDistance = std::abs(page - someStackPage);

  // Explanation for the "distance <= 1" check here as opposed to just
  // an equality check.
  //
  // Here we assume that pages immediately adjacent to the someStackAddress
  // page, are also stack pages. That allows to catch the case where the calling
  // frame put a buffer on the stack, and we just crossed the page boundary.
  // That is likely to happen, precisely, when using stack arrays. I hit that
  // specifically with CompositorOGL::Initialize.
  //
  // In theory we could be unlucky and wrongly assert here. If that happens,
  // it will only affect debug builds, and looking at stacks we'll be able to
  // see that this assert is wrong and revert to the conservative and safe
  // approach of only asserting when address and someStackAddress are
  // on the same page.
  bool isStackAddress = pageDistance <= 1;
  MOZ_ASSERT(!isStackAddress,
             "Please don't pass stack arrays to the GL. "
             "Consider using HeapCopyOfStackArray. "
             "See bug 1005658.");
}

void GLContext::CreatedProgram(GLContext* aOrigin, GLuint aName) {
  mTrackedPrograms.AppendElement(NamedResource(aOrigin, aName));
}

void GLContext::CreatedShader(GLContext* aOrigin, GLuint aName) {
  mTrackedShaders.AppendElement(NamedResource(aOrigin, aName));
}

void GLContext::CreatedBuffers(GLContext* aOrigin, GLsizei aCount,
                               GLuint* aNames) {
  for (GLsizei i = 0; i < aCount; ++i) {
    mTrackedBuffers.AppendElement(NamedResource(aOrigin, aNames[i]));
  }
}

void GLContext::CreatedQueries(GLContext* aOrigin, GLsizei aCount,
                               GLuint* aNames) {
  for (GLsizei i = 0; i < aCount; ++i) {
    mTrackedQueries.AppendElement(NamedResource(aOrigin, aNames[i]));
  }
}

void GLContext::CreatedTextures(GLContext* aOrigin, GLsizei aCount,
                                GLuint* aNames) {
  for (GLsizei i = 0; i < aCount; ++i) {
    mTrackedTextures.AppendElement(NamedResource(aOrigin, aNames[i]));
  }
}

void GLContext::CreatedFramebuffers(GLContext* aOrigin, GLsizei aCount,
                                    GLuint* aNames) {
  for (GLsizei i = 0; i < aCount; ++i) {
    mTrackedFramebuffers.AppendElement(NamedResource(aOrigin, aNames[i]));
  }
}

void GLContext::CreatedRenderbuffers(GLContext* aOrigin, GLsizei aCount,
                                     GLuint* aNames) {
  for (GLsizei i = 0; i < aCount; ++i) {
    mTrackedRenderbuffers.AppendElement(NamedResource(aOrigin, aNames[i]));
  }
}

static void RemoveNamesFromArray(GLContext* aOrigin, GLsizei aCount,
                                 const GLuint* aNames,
                                 nsTArray<GLContext::NamedResource>& aArray) {
  for (GLsizei j = 0; j < aCount; ++j) {
    GLuint name = aNames[j];
    // name 0 can be ignored
    if (name == 0) continue;

    for (uint32_t i = 0; i < aArray.Length(); ++i) {
      if (aArray[i].name == name) {
        aArray.RemoveElementAt(i);
        break;
      }
    }
  }
}

void GLContext::DeletedProgram(GLContext* aOrigin, GLuint aName) {
  RemoveNamesFromArray(aOrigin, 1, &aName, mTrackedPrograms);
}

void GLContext::DeletedShader(GLContext* aOrigin, GLuint aName) {
  RemoveNamesFromArray(aOrigin, 1, &aName, mTrackedShaders);
}

void GLContext::DeletedBuffers(GLContext* aOrigin, GLsizei aCount,
                               const GLuint* aNames) {
  RemoveNamesFromArray(aOrigin, aCount, aNames, mTrackedBuffers);
}

void GLContext::DeletedQueries(GLContext* aOrigin, GLsizei aCount,
                               const GLuint* aNames) {
  RemoveNamesFromArray(aOrigin, aCount, aNames, mTrackedQueries);
}

void GLContext::DeletedTextures(GLContext* aOrigin, GLsizei aCount,
                                const GLuint* aNames) {
  RemoveNamesFromArray(aOrigin, aCount, aNames, mTrackedTextures);
}

void GLContext::DeletedFramebuffers(GLContext* aOrigin, GLsizei aCount,
                                    const GLuint* aNames) {
  RemoveNamesFromArray(aOrigin, aCount, aNames, mTrackedFramebuffers);
}

void GLContext::DeletedRenderbuffers(GLContext* aOrigin, GLsizei aCount,
                                     const GLuint* aNames) {
  RemoveNamesFromArray(aOrigin, aCount, aNames, mTrackedRenderbuffers);
}

static void MarkContextDestroyedInArray(
    GLContext* aContext, nsTArray<GLContext::NamedResource>& aArray) {
  for (uint32_t i = 0; i < aArray.Length(); ++i) {
    if (aArray[i].origin == aContext) aArray[i].originDeleted = true;
  }
}

void GLContext::SharedContextDestroyed(GLContext* aChild) {
  MarkContextDestroyedInArray(aChild, mTrackedPrograms);
  MarkContextDestroyedInArray(aChild, mTrackedShaders);
  MarkContextDestroyedInArray(aChild, mTrackedTextures);
  MarkContextDestroyedInArray(aChild, mTrackedFramebuffers);
  MarkContextDestroyedInArray(aChild, mTrackedRenderbuffers);
  MarkContextDestroyedInArray(aChild, mTrackedBuffers);
  MarkContextDestroyedInArray(aChild, mTrackedQueries);
}

static void ReportArrayContents(
    const char* title, const nsTArray<GLContext::NamedResource>& aArray) {
  if (aArray.Length() == 0) return;

  printf_stderr("%s:\n", title);

  nsTArray<GLContext::NamedResource> copy(aArray.Clone());
  copy.Sort();

  GLContext* lastContext = nullptr;
  for (uint32_t i = 0; i < copy.Length(); ++i) {
    if (lastContext != copy[i].origin) {
      if (lastContext) printf_stderr("\n");
      printf_stderr("  [%p - %s] ", copy[i].origin,
                    copy[i].originDeleted ? "deleted" : "live");
      lastContext = copy[i].origin;
    }
    printf_stderr("%d ", copy[i].name);
  }
  printf_stderr("\n");
}

void GLContext::ReportOutstandingNames() {
  if (!ShouldSpew()) return;

  printf_stderr("== GLContext %p Outstanding ==\n", this);

  ReportArrayContents("Outstanding Textures", mTrackedTextures);
  ReportArrayContents("Outstanding Buffers", mTrackedBuffers);
  ReportArrayContents("Outstanding Queries", mTrackedQueries);
  ReportArrayContents("Outstanding Programs", mTrackedPrograms);
  ReportArrayContents("Outstanding Shaders", mTrackedShaders);
  ReportArrayContents("Outstanding Framebuffers", mTrackedFramebuffers);
  ReportArrayContents("Outstanding Renderbuffers", mTrackedRenderbuffers);
}

#endif  // ifdef MOZ_GL_DEBUG_BUILD

bool GLContext::IsOffscreenSizeAllowed(const IntSize& aSize) const {
  int32_t biggerDimension = std::max(aSize.width, aSize.height);
  int32_t maxAllowed = std::min(mMaxRenderbufferSize, mMaxTextureSize);
  return biggerDimension <= maxAllowed;
}

bool GLContext::IsValidOwningThread() const {
  if (!mOwningThreadId) return true;  // Free for all!
  return PlatformThread::CurrentId() == *mOwningThreadId;
}

GLBlitHelper* GLContext::BlitHelper() {
  if (!mBlitHelper) {
    mBlitHelper.reset(new GLBlitHelper(this));
  }

  return mBlitHelper.get();
}

GLReadTexImageHelper* GLContext::ReadTexImageHelper() {
  if (!mReadTexImageHelper) {
    mReadTexImageHelper = MakeUnique<GLReadTexImageHelper>(this);
  }

  return mReadTexImageHelper.get();
}

void GLContext::FlushIfHeavyGLCallsSinceLastFlush() {
  if (!mHeavyGLCallsSinceLastFlush) {
    return;
  }
  if (MakeCurrent()) {
    fFlush();
  }
}

/*static*/
bool GLContext::ShouldDumpExts() { return gfxEnv::MOZ_GL_DUMP_EXTS(); }

bool DoesStringMatch(const char* aString, const char* aWantedString) {
  if (!aString || !aWantedString) return false;

  const char* occurrence = strstr(aString, aWantedString);

  // aWanted not found
  if (!occurrence) return false;

  // aWantedString preceded by alpha character
  if (occurrence != aString && isalpha(*(occurrence - 1))) return false;

  // aWantedVendor followed by alpha character
  const char* afterOccurrence = occurrence + strlen(aWantedString);
  if (isalpha(*afterOccurrence)) return false;

  return true;
}

/*static*/
bool GLContext::ShouldSpew() { return gfxEnv::MOZ_GL_SPEW(); }

void SplitByChar(const nsACString& str, const char delim,
                 std::vector<nsCString>* const out) {
  uint32_t start = 0;
  while (true) {
    int32_t end = str.FindChar(' ', start);
    if (end == -1) break;

    uint32_t len = (uint32_t)end - start;
    nsDependentCSubstring substr(str, start, len);
    out->push_back(nsCString(substr));

    start = end + 1;
  }

  nsDependentCSubstring substr(str, start);
  out->push_back(nsCString(substr));
}

void GLContext::fCopyTexImage2D(GLenum target, GLint level,
                                GLenum internalformat, GLint x, GLint y,
                                GLsizei width, GLsizei height, GLint border) {
  if (!IsTextureSizeSafeToPassToDriver(target, width, height)) {
    // pass wrong values to cause the GL to generate GL_INVALID_VALUE.
    // See bug 737182 and the comment in IsTextureSizeSafeToPassToDriver.
    level = -1;
    width = -1;
    height = -1;
    border = -1;
  }

  BeforeGLReadCall();
  raw_fCopyTexImage2D(target, level, internalformat, x, y, width, height,
                      border);
  AfterGLReadCall();
}

void GLContext::fGetIntegerv(const GLenum pname, GLint* const params) const {
  const auto AssertBinding = [&](const char* const name, const GLenum binding,
                                 const GLuint expected) {
    if (MOZ_LIKELY(!mDebugFlags)) return;
    GLuint actual = 0;
    raw_fGetIntegerv(binding, (GLint*)&actual);
    if (actual != expected) {
      gfxCriticalError() << "Misprediction: " << name << " expected "
                         << expected << ", was " << actual;
    }
  };

  switch (pname) {
    case LOCAL_GL_MAX_TEXTURE_SIZE:
      MOZ_ASSERT(mMaxTextureSize > 0);
      *params = mMaxTextureSize;
      return;

    case LOCAL_GL_MAX_CUBE_MAP_TEXTURE_SIZE:
      MOZ_ASSERT(mMaxCubeMapTextureSize > 0);
      *params = mMaxCubeMapTextureSize;
      return;

    case LOCAL_GL_MAX_RENDERBUFFER_SIZE:
      MOZ_ASSERT(mMaxRenderbufferSize > 0);
      *params = mMaxRenderbufferSize;
      return;

    case LOCAL_GL_VIEWPORT:
      for (size_t i = 0; i < 4; i++) {
        params[i] = mViewportRect[i];
      }
      return;

    case LOCAL_GL_SCISSOR_BOX:
      for (size_t i = 0; i < 4; i++) {
        params[i] = mScissorRect[i];
      }
      return;

    case LOCAL_GL_DRAW_FRAMEBUFFER_BINDING:
      if (mElideDuplicateBindFramebuffers) {
        static_assert(LOCAL_GL_DRAW_FRAMEBUFFER_BINDING ==
                      LOCAL_GL_FRAMEBUFFER_BINDING);
        AssertBinding("GL_DRAW_FRAMEBUFFER_BINDING",
                      LOCAL_GL_DRAW_FRAMEBUFFER_BINDING, mCachedDrawFb);
        *params = static_cast<GLint>(mCachedDrawFb);
        return;
      }
      break;

    case LOCAL_GL_READ_FRAMEBUFFER_BINDING:
      if (mElideDuplicateBindFramebuffers) {
        if (IsSupported(GLFeature::framebuffer_blit)) {
          AssertBinding("GL_READ_FRAMEBUFFER_BINDING",
                        LOCAL_GL_READ_FRAMEBUFFER_BINDING, mCachedReadFb);
        }
        *params = static_cast<GLint>(mCachedReadFb);
        return;
      }
      break;

    default:
      break;
  }
  raw_fGetIntegerv(pname, params);
}

void GLContext::fReadPixels(GLint x, GLint y, GLsizei width, GLsizei height,
                            GLenum format, GLenum type, GLvoid* pixels) {
  BeforeGLReadCall();
  raw_fReadPixels(x, y, width, height, format, type, pixels);
  AfterGLReadCall();

  // Check if GL is giving back 1.0 alpha for
  // RGBA reads to RGBA images from no-alpha buffers.
#ifdef XP_MACOSX
  if (WorkAroundDriverBugs() && Vendor() == gl::GLVendor::NVIDIA &&
      format == LOCAL_GL_RGBA && type == LOCAL_GL_UNSIGNED_BYTE &&
      !IsCoreProfile() && width && height) {
    GLint alphaBits = 0;
    fGetIntegerv(LOCAL_GL_ALPHA_BITS, &alphaBits);
    if (!alphaBits) {
      const uint32_t alphaMask = 0xff000000;

      uint32_t* itr = (uint32_t*)pixels;
      uint32_t testPixel = *itr;
      if ((testPixel & alphaMask) != alphaMask) {
        // We need to set the alpha channel to 1.0 manually.
        uint32_t* itrEnd =
            itr + width * height;  // Stride is guaranteed to be width*4.

        for (; itr != itrEnd; itr++) {
          *itr |= alphaMask;
        }
      }
    }
  }
#endif
}

void GLContext::fDeleteFramebuffers(GLsizei n, const GLuint* names) {
  // Avoid crash by flushing before glDeleteFramebuffers. See bug 1194923.
  if (mNeedsFlushBeforeDeleteFB) {
    fFlush();
  }

  if (n == 1 && *names == 0) {
    // Deleting framebuffer 0 causes hangs on the DROID. See bug 623228.
  } else {
    raw_fDeleteFramebuffers(n, names);
  }
  TRACKING_CONTEXT(DeletedFramebuffers(this, n, names));
}

#ifdef MOZ_WIDGET_ANDROID
/**
 * Conservatively estimate whether there is enough available
 * contiguous virtual address space to map a newly allocated texture.
 */
static bool WillTextureMapSucceed(GLsizei width, GLsizei height, GLenum format,
                                  GLenum type) {
  bool willSucceed = false;
  // Some drivers leave large gaps between textures, so require
  // there to be double the actual size of the texture available.
  size_t size = width * height * GetBytesPerTexel(format, type) * 2;

  void* p = mmap(nullptr, size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
  if (p != MAP_FAILED) {
    willSucceed = true;
    munmap(p, size);
  }

  return willSucceed;
}
#endif  // MOZ_WIDGET_ANDROID

void GLContext::fTexImage2D(GLenum target, GLint level, GLint internalformat,
                            GLsizei width, GLsizei height, GLint border,
                            GLenum format, GLenum type, const GLvoid* pixels) {
  if (!IsTextureSizeSafeToPassToDriver(target, width, height)) {
    // pass wrong values to cause the GL to generate GL_INVALID_VALUE.
    // See bug 737182 and the comment in IsTextureSizeSafeToPassToDriver.
    level = -1;
    width = -1;
    height = -1;
    border = -1;
  }
#if MOZ_WIDGET_ANDROID
  if (mTextureAllocCrashesOnMapFailure) {
    // We have no way of knowing whether this texture already has
    // storage allocated for it, and therefore whether this check
    // is necessary. We must therefore assume it does not and
    // always perform the check.
    if (!WillTextureMapSucceed(width, height, internalformat, type)) {
      return;
    }
  }
#endif
  raw_fTexImage2D(target, level, internalformat, width, height, border, format,
                  type, pixels);
}

UniquePtr<Texture> CreateTexture(GLContext& gl, const gfx::IntSize& size) {
  const GLenum target = LOCAL_GL_TEXTURE_2D;
  const GLenum format = LOCAL_GL_RGBA;

  auto tex = MakeUnique<Texture>(gl);
  ScopedBindTexture autoTex(&gl, tex->name, target);

  gl.fTexParameteri(target, LOCAL_GL_TEXTURE_MIN_FILTER, LOCAL_GL_LINEAR);
  gl.fTexParameteri(target, LOCAL_GL_TEXTURE_MAG_FILTER, LOCAL_GL_LINEAR);
  gl.fTexParameteri(target, LOCAL_GL_TEXTURE_WRAP_S, LOCAL_GL_CLAMP_TO_EDGE);
  gl.fTexParameteri(target, LOCAL_GL_TEXTURE_WRAP_T, LOCAL_GL_CLAMP_TO_EDGE);

  gl.fTexImage2D(target, 0, format, size.width, size.height, 0, format,
                 LOCAL_GL_UNSIGNED_BYTE, nullptr);

  return tex;
}

uint32_t GetBytesPerTexel(GLenum format, GLenum type) {
  // If there is no defined format or type, we're not taking up any memory
  if (!format || !type) {
    return 0;
  }

  if (format == LOCAL_GL_DEPTH_COMPONENT) {
    if (type == LOCAL_GL_UNSIGNED_SHORT)
      return 2;
    else if (type == LOCAL_GL_UNSIGNED_INT)
      return 4;
  } else if (format == LOCAL_GL_DEPTH_STENCIL) {
    if (type == LOCAL_GL_UNSIGNED_INT_24_8_EXT) return 4;
  }

  if (type == LOCAL_GL_UNSIGNED_BYTE || type == LOCAL_GL_FLOAT ||
      type == LOCAL_GL_UNSIGNED_INT_8_8_8_8_REV) {
    uint32_t multiplier = type == LOCAL_GL_UNSIGNED_BYTE ? 1 : 4;
    switch (format) {
      case LOCAL_GL_ALPHA:
      case LOCAL_GL_LUMINANCE:
      case LOCAL_GL_R8:
        return 1 * multiplier;
      case LOCAL_GL_LUMINANCE_ALPHA:
      case LOCAL_GL_R16:
        return 2 * multiplier;
      case LOCAL_GL_RGB:
        return 3 * multiplier;
      case LOCAL_GL_RGBA:
      case LOCAL_GL_BGRA_EXT:
        return 4 * multiplier;
      default:
        break;
    }
  } else if (type == LOCAL_GL_UNSIGNED_SHORT_4_4_4_4 ||
             type == LOCAL_GL_UNSIGNED_SHORT_5_5_5_1 ||
             type == LOCAL_GL_UNSIGNED_SHORT_5_6_5 ||
             type == LOCAL_GL_UNSIGNED_SHORT) {
    return 2;
  }

  gfxCriticalError() << "Unknown texture type " << type << " or format "
                     << format;
  return 0;
}

bool GLContext::MakeCurrent(bool aForce) const {
  if (MOZ_UNLIKELY(IsContextLost())) return false;

  if (MOZ_LIKELY(!aForce)) {
    bool isCurrent;
    if (mUseTLSIsCurrent && sCurrentContext.init()) {
      isCurrent = (sCurrentContext.get() == this);
    } else {
      isCurrent = IsCurrentImpl();
    }
    if (MOZ_LIKELY(isCurrent)) {
      MOZ_ASSERT(IsCurrentImpl() ||
                 !MakeCurrentImpl());  // Might have lost context.
      return true;
    }
  }
  if (!IsValidOwningThread()) {
    gfxCriticalError() << "MakeCurrent called on a thread other than the"
                       << " creating thread!";
    if (gfxEnv::MOZ_GL_RELEASE_ASSERT_CONTEXT_OWNERSHIP()) {
      MOZ_CRASH("MOZ_GL_RELEASE_ASSERT_CONTEXT_OWNERSHIP");
    }
  }
  if (!MakeCurrentImpl()) return false;

  if (sCurrentContext.init()) {
    sCurrentContext.set(this);
  }
  return true;
}

void GLContext::ResetSyncCallCount(const char* resetReason) const {
  if (ShouldSpew()) {
    printf_stderr("On %s, mSyncGLCallCount = %" PRIu64 "\n", resetReason,
                  mSyncGLCallCount);
  }

  mSyncGLCallCount = 0;
}

// -

bool CheckContextLost(const GLContext* const gl) {
  return gl->CheckContextLost();
}

// -

GLenum GLContext::GetError() const {
  if (mContextLost) return LOCAL_GL_CONTEXT_LOST;

  if (mImplicitMakeCurrent) {
    (void)MakeCurrent();
  }

  const auto fnGetError = [&]() {
    const auto ret = mSymbols.fGetError();
    if (ret == LOCAL_GL_CONTEXT_LOST) {
      OnContextLostError();
      mTopError = ret;  // Promote to top!
    }
    return ret;
  };

  auto ret = fnGetError();

  {
    auto flushedErr = ret;
    uint32_t i = 1;
    while (flushedErr && !mContextLost) {
      if (i == 100) {
        gfxCriticalError() << "Flushing glGetError still "
                           << gfx::hexa(flushedErr) << " after " << i
                           << " calls.";
        break;
      }
      flushedErr = fnGetError();
      i += 1;
    }
  }

  if (mTopError) {
    ret = mTopError;
    mTopError = 0;
  }

  if (mDebugFlags & DebugFlagTrace) {
    const auto errStr = GLErrorToString(ret);
    printf_stderr("[gl:%p] GetError() -> %s\n", this, errStr.c_str());
  }
  return ret;
}

GLenum GLContext::fGetGraphicsResetStatus() const {
  OnSyncCall();

  GLenum ret = 0;
  if (mSymbols.fGetGraphicsResetStatus) {
    if (mImplicitMakeCurrent) {
      (void)MakeCurrent();
    }
    ret = mSymbols.fGetGraphicsResetStatus();
  } else {
    if (!MakeCurrent(true)) {
      ret = LOCAL_GL_UNKNOWN_CONTEXT_RESET_ARB;
    }
  }

  if (mDebugFlags & DebugFlagTrace) {
    printf_stderr("[gl:%p] GetGraphicsResetStatus() -> 0x%04x\n", this, ret);
  }

  return ret;
}

void GLContext::OnContextLostError() const {
  if (mDebugFlags & DebugFlagTrace) {
    printf_stderr("[gl:%p] CONTEXT_LOST\n", this);
  }
  mContextLost = true;
}

// --

/*static*/ std::string GLContext::GLErrorToString(const GLenum err) {
  switch (err) {
    case LOCAL_GL_NO_ERROR:
      return "GL_NO_ERROR";
    case LOCAL_GL_INVALID_ENUM:
      return "GL_INVALID_ENUM";
    case LOCAL_GL_INVALID_VALUE:
      return "GL_INVALID_VALUE";
    case LOCAL_GL_INVALID_OPERATION:
      return "GL_INVALID_OPERATION";
    case LOCAL_GL_STACK_OVERFLOW:
      return "GL_STACK_OVERFLOW";
    case LOCAL_GL_STACK_UNDERFLOW:
      return "GL_STACK_UNDERFLOW";
    case LOCAL_GL_OUT_OF_MEMORY:
      return "GL_OUT_OF_MEMORY";
    case LOCAL_GL_TABLE_TOO_LARGE:
      return "GL_TABLE_TOO_LARGE";
    case LOCAL_GL_INVALID_FRAMEBUFFER_OPERATION:
      return "GL_INVALID_FRAMEBUFFER_OPERATION";
    case LOCAL_GL_CONTEXT_LOST:
      return "GL_CONTEXT_LOST";
  }

  const nsPrintfCString hex("<enum 0x%04x>", err);
  return hex.BeginReading();
}

// --

void GLContext::BeforeGLCall_Debug(const char* const funcName) const {
  MOZ_ASSERT(mDebugFlags);

  if (mDebugFlags & DebugFlagTrace) {
    printf_stderr("[gl:%p] > %s\n", this, funcName);
  }

  MOZ_ASSERT(!mDebugErrorScope);
  mDebugErrorScope.reset(new LocalErrorScope(*this));
}

void GLContext::AfterGLCall_Debug(const char* const funcName) const {
  MOZ_ASSERT(mDebugFlags);

  // calling fFinish() immediately after every GL call makes sure that if this
  // GL command crashes, the stack trace will actually point to it. Otherwise,
  // OpenGL being an asynchronous API, stack traces tend to be meaningless
  mSymbols.fFinish();

  const auto err = mDebugErrorScope->GetError();
  mDebugErrorScope = nullptr;
  if (!mTopError) {
    mTopError = err;
  }

  if (mDebugFlags & DebugFlagTrace) {
    printf_stderr("[gl:%p] < %s [%s]\n", this, funcName,
                  GLErrorToString(err).c_str());
  }

  if (err && !mLocalErrorScopeStack.size()) {
    const auto errStr = GLErrorToString(err);
    const auto text = nsPrintfCString("%s: Generated unexpected %s error",
                                      funcName, errStr.c_str());
    printf_stderr("[gl:%p] %s.\n", this, text.BeginReading());

    const bool abortOnError = mDebugFlags & DebugFlagAbortOnError;
    if (abortOnError && err != LOCAL_GL_CONTEXT_LOST) {
      gfxCriticalErrorOnce() << text.BeginReading();
      MOZ_CRASH(
          "Aborting... (Run with MOZ_GL_DEBUG_ABORT_ON_ERROR=0 to disable)");
    }
  }
}

/*static*/
void GLContext::OnImplicitMakeCurrentFailure(const char* const funcName) {
  gfxCriticalError() << "Ignoring call to " << funcName << " with failed"
                     << " mImplicitMakeCurrent.";
}

bool GLContext::CreateOffscreenDefaultFb(const gfx::IntSize& size) {
  mOffscreenDefaultFb = MozFramebuffer::Create(this, size, 0, true);
  return bool(mOffscreenDefaultFb);
}

// Some of Mesa's drivers allocate heap memory when loaded and don't
// free it when unloaded; this causes Leak Sanitizer to detect leaks and
// fail to unwind the stack, so suppressions don't work.  This
// workaround leaks a reference to the driver library so that it's never
// unloaded.  Because the leak isn't significant for real usage, only
// ASan runs in CI, this is applied only to the software renderer.
//
// See bug 1702394 for more details.
void MesaMemoryLeakWorkaround() {
#if defined(XP_LINUX) && !defined(ANDROID)
  Maybe<nsAutoCString> foundPath;

  dl_iterate_phdr(
      [](dl_phdr_info* info, size_t size, void* data) {
        auto& foundPath = *reinterpret_cast<Maybe<nsAutoCString>*>(data);
        nsDependentCString thisPath(info->dlpi_name);
        if (StringEndsWith(thisPath, "/swrast_dri.so"_ns)) {
          foundPath.emplace(thisPath);
          return 1;
        }
        return 0;
      },
      &foundPath);

  if (foundPath) {
    // Deliberately leak to prevent unload
    Unused << dlopen(foundPath->get(), RTLD_LAZY);
  }
#endif  // XP_LINUX but not ANDROID
}

} /* namespace gl */
} /* namespace mozilla */