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
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
|
// Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef V8_HEAP_HEAP_H_
#define V8_HEAP_HEAP_H_
#include <atomic>
#include <cmath>
#include <memory>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// Clients of this interface shouldn't depend on lots of heap internals.
// Do not include anything from src/heap here!
#include "include/v8-callbacks.h"
#include "include/v8-embedder-heap.h"
#include "include/v8-internal.h"
#include "include/v8-isolate.h"
#include "src/base/atomic-utils.h"
#include "src/base/enum-set.h"
#include "src/base/platform/condition-variable.h"
#include "src/base/platform/mutex.h"
#include "src/builtins/accessors.h"
#include "src/common/assert-scope.h"
#include "src/common/code-memory-access.h"
#include "src/common/globals.h"
#include "src/heap/allocation-observer.h"
#include "src/heap/allocation-result.h"
#include "src/heap/base/stack.h"
#include "src/heap/gc-callbacks.h"
#include "src/heap/heap-allocator.h"
#include "src/init/heap-symbols.h"
#include "src/objects/allocation-site.h"
#include "src/objects/fixed-array.h"
#include "src/objects/hash-table.h"
#include "src/objects/heap-object.h"
#include "src/objects/js-array-buffer.h"
#include "src/objects/objects.h"
#include "src/objects/smi.h"
#include "src/objects/visitors.h"
#include "src/roots/roots.h"
#include "src/utils/allocation.h"
#include "testing/gtest/include/gtest/gtest_prod.h" // nogncheck
namespace cppgc {
namespace internal {
enum class HeapObjectNameForUnnamedObject : uint8_t;
class ClassNameAsHeapObjectNameScope;
} // namespace internal
} // namespace cppgc
namespace heap {
namespace base {
class Stack;
} // namespace base
} // namespace heap
namespace v8 {
namespace debug {
using OutOfMemoryCallback = void (*)(void* data);
} // namespace debug
namespace internal {
namespace heap {
class HeapTester;
class TestMemoryAllocatorScope;
} // namespace heap
namespace third_party_heap {
class Heap;
class Impl;
} // namespace third_party_heap
class IncrementalMarking;
class BackingStore;
class JSArrayBuffer;
class JSPromise;
class NativeContext;
using v8::MemoryPressureLevel;
class ArrayBufferCollector;
class ArrayBufferSweeper;
class BasicMemoryChunk;
class CodeLargeObjectSpace;
class CodeRange;
class CollectionBarrier;
class ConcurrentAllocator;
class ConcurrentMarking;
class CppHeap;
class GCIdleTimeHandler;
class GCIdleTimeHeapState;
class GCTracer;
template <typename T>
class GlobalHandleVector;
class IsolateSafepoint;
class HeapObjectAllocationTracker;
class HeapObjectsFilter;
class HeapStats;
class Isolate;
class JSFinalizationRegistry;
class LinearAllocationArea;
class LocalEmbedderHeapTracer;
class LocalHeap;
class MemoryAllocator;
class MemoryChunk;
class MemoryMeasurement;
class MemoryReducer;
class MinorMarkCompactCollector;
class NopRwxMemoryWriteScope;
class ObjectIterator;
class ObjectStats;
class Page;
class PagedSpace;
class PagedNewSpace;
class ReadOnlyHeap;
class RootVisitor;
class RwxMemoryWriteScope;
class SafepointScope;
class ScavengeJob;
class Scavenger;
class ScavengerCollector;
class SharedReadOnlySpace;
class Space;
class StressScavengeObserver;
class TimedHistogram;
class WeakObjectRetainer;
enum ArrayStorageAllocationMode {
DONT_INITIALIZE_ARRAY_ELEMENTS,
INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE
};
enum class ClearRecordedSlots { kYes, kNo };
enum class InvalidateRecordedSlots { kYes, kNo };
enum class ClearFreedMemoryMode { kClearFreedMemory, kDontClearFreedMemory };
enum ExternalBackingStoreType { kArrayBuffer, kExternalString, kNumTypes };
enum class RetainingPathOption { kDefault, kTrackEphemeronPath };
// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused. If you add new items here, update
// src/tools/metrics/histograms/enums.xml in chromium.
enum class GarbageCollectionReason : int {
kUnknown = 0,
kAllocationFailure = 1,
kAllocationLimit = 2,
kContextDisposal = 3,
kCountersExtension = 4,
kDebugger = 5,
kDeserializer = 6,
kExternalMemoryPressure = 7,
kFinalizeMarkingViaStackGuard = 8,
kFinalizeMarkingViaTask = 9,
kFullHashtable = 10,
kHeapProfiler = 11,
kTask = 12,
kLastResort = 13,
kLowMemoryNotification = 14,
kMakeHeapIterable = 15,
kMemoryPressure = 16,
kMemoryReducer = 17,
kRuntime = 18,
kSamplingProfiler = 19,
kSnapshotCreator = 20,
kTesting = 21,
kExternalFinalize = 22,
kGlobalAllocationLimit = 23,
kMeasureMemory = 24,
kBackgroundAllocationFailure = 25,
kFinalizeMinorMC = 26,
kCppHeapAllocationFailure = 27,
kLastReason = kCppHeapAllocationFailure,
};
static_assert(kGarbageCollectionReasonMaxValue ==
static_cast<int>(GarbageCollectionReason::kLastReason),
"The value of kGarbageCollectionReasonMaxValue is inconsistent.");
enum class YoungGenerationHandling {
kRegularScavenge = 0,
kFastPromotionDuringScavenge = 1,
// Histogram::InspectConstructionArguments in chromium requires us to have at
// least three buckets.
kUnusedBucket = 2,
// If you add new items here, then update the young_generation_handling in
// counters.h.
// Also update src/tools/metrics/histograms/histograms.xml in chromium.
};
enum class GCIdleTimeAction : uint8_t;
enum class SkipRoot {
kExternalStringTable,
kGlobalHandles,
kOldGeneration,
kStack,
kMainThreadHandles,
kUnserializable,
kWeak
};
enum UnprotectMemoryOrigin {
kMainThread,
kMaybeOffMainThread,
};
class StrongRootsEntry final {
explicit StrongRootsEntry(const char* label) : label(label) {}
// Label that identifies the roots in tooling.
const char* label;
FullObjectSlot start;
FullObjectSlot end;
StrongRootsEntry* prev;
StrongRootsEntry* next;
friend class Heap;
};
#ifdef DEBUG
struct CommentStatistic {
const char* comment;
int size;
int count;
void Clear() {
comment = nullptr;
size = 0;
count = 0;
}
// Must be small, since an iteration is used for lookup.
static const int kMaxComments = 64;
};
#endif
using EphemeronRememberedSet =
std::unordered_map<EphemeronHashTable, std::unordered_set<int>,
Object::Hasher>;
class Heap {
public:
// Stores ephemeron entries where the EphemeronHashTable is in old-space,
// and the key of the entry is in new-space. Such keys do not appear in the
// usual OLD_TO_NEW remembered set.
EphemeronRememberedSet ephemeron_remembered_set_;
enum FindMementoMode { kForRuntime, kForGC };
enum class HeapGrowingMode { kSlow, kConservative, kMinimal, kDefault };
enum HeapState {
NOT_IN_GC,
SCAVENGE,
MARK_COMPACT,
MINOR_MARK_COMPACT,
TEAR_DOWN
};
// Emits GC events for DevTools timeline.
class V8_NODISCARD DevToolsTraceEventScope {
public:
DevToolsTraceEventScope(Heap* heap, const char* event_name,
const char* event_type);
~DevToolsTraceEventScope();
private:
Heap* heap_;
const char* event_name_;
};
class ExternalMemoryAccounting {
public:
int64_t total() { return total_.load(std::memory_order_relaxed); }
int64_t limit() { return limit_.load(std::memory_order_relaxed); }
int64_t low_since_mark_compact() {
return low_since_mark_compact_.load(std::memory_order_relaxed);
}
void ResetAfterGC() {
set_low_since_mark_compact(total());
set_limit(total() + kExternalAllocationSoftLimit);
}
int64_t Update(int64_t delta) {
const int64_t amount =
total_.fetch_add(delta, std::memory_order_relaxed) + delta;
if (amount < low_since_mark_compact()) {
set_low_since_mark_compact(amount);
set_limit(amount + kExternalAllocationSoftLimit);
}
return amount;
}
int64_t AllocatedSinceMarkCompact() {
int64_t total_bytes = total();
int64_t low_since_mark_compact_bytes = low_since_mark_compact();
if (total_bytes <= low_since_mark_compact_bytes) {
return 0;
}
return static_cast<uint64_t>(total_bytes - low_since_mark_compact_bytes);
}
private:
void set_total(int64_t value) {
total_.store(value, std::memory_order_relaxed);
}
void set_limit(int64_t value) {
limit_.store(value, std::memory_order_relaxed);
}
void set_low_since_mark_compact(int64_t value) {
low_since_mark_compact_.store(value, std::memory_order_relaxed);
}
// The amount of external memory registered through the API.
std::atomic<int64_t> total_{0};
// The limit when to trigger memory pressure from the API.
std::atomic<int64_t> limit_{kExternalAllocationSoftLimit};
// Caches the amount of external memory registered at the last MC.
std::atomic<int64_t> low_since_mark_compact_{0};
};
using PretenuringFeedbackMap =
std::unordered_map<AllocationSite, size_t, Object::Hasher>;
// Taking this mutex prevents the GC from entering a phase that relocates
// object references.
base::Mutex* relocation_mutex() { return &relocation_mutex_; }
// Support for context snapshots. After calling this we have a linear
// space to write objects in each space.
struct Chunk {
uint32_t size;
Address start;
Address end;
};
using Reservation = std::vector<Chunk>;
#if V8_OS_ANDROID
// Don't apply pointer multiplier on Android since it has no swap space and
// should instead adapt it's heap size based on available physical memory.
static const int kPointerMultiplier = 1;
static const int kHeapLimitMultiplier = 1;
#else
static const int kPointerMultiplier = kTaggedSize / 4;
// The heap limit needs to be computed based on the system pointer size
// because we want a pointer-compressed heap to have larger limit than
// an ordinary 32-bit which that is constrained by 2GB virtual address space.
static const int kHeapLimitMultiplier = kSystemPointerSize / 4;
#endif
static const size_t kMaxInitialOldGenerationSize =
256 * MB * kHeapLimitMultiplier;
// These constants control heap configuration based on the physical memory.
static constexpr size_t kPhysicalMemoryToOldGenerationRatio = 4;
// Young generation size is the same for compressed heaps and 32-bit heaps.
static constexpr size_t kOldGenerationToSemiSpaceRatio =
128 * kHeapLimitMultiplier / kPointerMultiplier;
static constexpr size_t kOldGenerationToSemiSpaceRatioLowMemory =
256 * kHeapLimitMultiplier / kPointerMultiplier;
static constexpr size_t kOldGenerationLowMemory =
128 * MB * kHeapLimitMultiplier;
static constexpr size_t kNewLargeObjectSpaceToSemiSpaceRatio = 1;
#if ENABLE_HUGEPAGE
static constexpr size_t kMinSemiSpaceSize =
kHugePageSize * kPointerMultiplier;
static constexpr size_t kMaxSemiSpaceSize =
kHugePageSize * 16 * kPointerMultiplier;
#else
static constexpr size_t kMinSemiSpaceSize = 512 * KB * kPointerMultiplier;
static constexpr size_t kMaxSemiSpaceSize = 8192 * KB * kPointerMultiplier;
#endif
static_assert(kMinSemiSpaceSize % (1 << kPageSizeBits) == 0);
static_assert(kMaxSemiSpaceSize % (1 << kPageSizeBits) == 0);
static const int kTraceRingBufferSize = 512;
static const int kStacktraceBufferSize = 512;
static const int kNoGCFlags = 0;
static const int kReduceMemoryFootprintMask = 1;
// GCs that are forced, either through testing configurations (requiring
// --expose-gc) or through DevTools (using LowMemoryNotification).
static const int kForcedGC = 2;
// The minimum size of a HeapObject on the heap.
static const int kMinObjectSizeInTaggedWords = 2;
static const int kMinPromotedPercentForFastPromotionMode = 90;
static_assert(static_cast<int>(RootIndex::kUndefinedValue) ==
Internals::kUndefinedValueRootIndex);
static_assert(static_cast<int>(RootIndex::kTheHoleValue) ==
Internals::kTheHoleValueRootIndex);
static_assert(static_cast<int>(RootIndex::kNullValue) ==
Internals::kNullValueRootIndex);
static_assert(static_cast<int>(RootIndex::kTrueValue) ==
Internals::kTrueValueRootIndex);
static_assert(static_cast<int>(RootIndex::kFalseValue) ==
Internals::kFalseValueRootIndex);
static_assert(static_cast<int>(RootIndex::kempty_string) ==
Internals::kEmptyStringRootIndex);
// Calculates the maximum amount of filler that could be required by the
// given alignment.
V8_EXPORT_PRIVATE static int GetMaximumFillToAlign(
AllocationAlignment alignment);
// Calculates the actual amount of filler required for a given address at the
// given alignment.
V8_EXPORT_PRIVATE static int GetFillToAlign(Address address,
AllocationAlignment alignment);
// Returns the size of the initial area of a code-range, which is marked
// writable and reserved to contain unwind information.
static size_t GetCodeRangeReservedAreaSize();
[[noreturn]] void FatalProcessOutOfMemory(const char* location);
// Checks whether the space is valid.
static bool IsValidAllocationSpace(AllocationSpace space);
// Zapping is needed for verify heap, and always done in debug builds.
static inline bool ShouldZapGarbage() {
#ifdef DEBUG
return true;
#else
#ifdef VERIFY_HEAP
return v8_flags.verify_heap;
#else
return false;
#endif
#endif
}
// Helper function to get the bytecode flushing mode based on the flags. This
// is required because it is not safe to access flags in concurrent marker.
static inline base::EnumSet<CodeFlushMode> GetCodeFlushMode(Isolate* isolate);
static uintptr_t ZapValue() {
return v8_flags.clear_free_memory ? kClearedFreeMemoryValue : kZapValue;
}
static inline bool IsYoungGenerationCollector(GarbageCollector collector) {
return collector == GarbageCollector::SCAVENGER ||
collector == GarbageCollector::MINOR_MARK_COMPACTOR;
}
static inline GarbageCollector YoungGenerationCollector() {
return (v8_flags.minor_mc) ? GarbageCollector::MINOR_MARK_COMPACTOR
: GarbageCollector::SCAVENGER;
}
static inline const char* CollectorName(GarbageCollector collector) {
switch (collector) {
case GarbageCollector::SCAVENGER:
return "Scavenger";
case GarbageCollector::MARK_COMPACTOR:
return "Mark-Compact";
case GarbageCollector::MINOR_MARK_COMPACTOR:
return "Minor Mark-Compact";
}
return "Unknown collector";
}
static inline const char* CollectorName(v8::GCType gc_type) {
switch (gc_type) {
case kGCTypeScavenge:
return "Scavenger";
case kGCTypeMarkSweepCompact:
return "Mark-Compact";
case kGCTypeMinorMarkCompact:
return "Minor Mark-Compact";
default:
break;
}
return "Unknown collector";
}
// Copy block of memory from src to dst. Size of block should be aligned
// by pointer size.
static inline void CopyBlock(Address dst, Address src, int byte_size);
// Executes generational and/or marking write barrier for a [start, end) range
// of non-weak slots inside |object|.
template <typename TSlot>
V8_EXPORT_PRIVATE void WriteBarrierForRange(HeapObject object, TSlot start,
TSlot end);
// Implements slow path of both generational & shared heap barrier.
V8_EXPORT_PRIVATE static void CombinedGenerationalAndSharedBarrierSlow(
HeapObject object, Address slot, HeapObject value);
V8_EXPORT_PRIVATE static void
CombinedGenerationalAndSharedEphemeronBarrierSlow(EphemeronHashTable table,
Address slot,
HeapObject value);
V8_EXPORT_PRIVATE static void GenerationalBarrierSlow(HeapObject object,
Address slot,
HeapObject value);
V8_EXPORT_PRIVATE static void SharedHeapBarrierSlow(HeapObject object,
Address slot);
V8_EXPORT_PRIVATE inline void RecordEphemeronKeyWrite(
EphemeronHashTable table, Address key_slot);
V8_EXPORT_PRIVATE static void EphemeronKeyWriteBarrierFromCode(
Address raw_object, Address address, Isolate* isolate);
V8_EXPORT_PRIVATE static void GenerationalBarrierForCodeSlow(
Code host, RelocInfo* rinfo, HeapObject value);
V8_EXPORT_PRIVATE static bool PageFlagsAreConsistent(HeapObject object);
// Notifies the heap that is ok to start marking or other activities that
// should not happen during deserialization.
void NotifyDeserializationComplete();
void NotifyBootstrapComplete();
void NotifyOldGenerationExpansion(AllocationSpace space, MemoryChunk* chunk);
inline Address* NewSpaceAllocationTopAddress();
inline Address* NewSpaceAllocationLimitAddress();
inline Address* OldSpaceAllocationTopAddress();
inline Address* OldSpaceAllocationLimitAddress();
size_t NewSpaceSize();
size_t NewSpaceCapacity();
// Move len non-weak tagged elements from src_slot to dst_slot of dst_object.
// The source and destination memory ranges can overlap.
V8_EXPORT_PRIVATE void MoveRange(HeapObject dst_object, ObjectSlot dst_slot,
ObjectSlot src_slot, int len,
WriteBarrierMode mode);
// Copy len non-weak tagged elements from src_slot to dst_slot of dst_object.
// The source and destination memory ranges must not overlap.
template <typename TSlot>
void CopyRange(HeapObject dst_object, TSlot dst_slot, TSlot src_slot, int len,
WriteBarrierMode mode);
// Initialize a filler object to keep the ability to iterate over the heap
// when introducing gaps within pages. This method will verify that no slots
// are recorded in this free memory.
V8_EXPORT_PRIVATE void CreateFillerObjectAt(Address addr, int size);
// Initialize a filler object at a specific address. Unlike
// `CreateFillerObjectAt` this method will not perform slot verification since
// this would race on background threads.
void CreateFillerObjectAtBackground(Address addr, int size);
template <typename T>
void CreateFillerForArray(T object, int elements_to_trim, int bytes_to_trim);
bool CanMoveObjectStart(HeapObject object);
bool IsImmovable(HeapObject object);
V8_EXPORT_PRIVATE static bool IsLargeObject(HeapObject object);
// Trim the given array from the left. Note that this relocates the object
// start and hence is only valid if there is only a single reference to it.
V8_EXPORT_PRIVATE FixedArrayBase LeftTrimFixedArray(FixedArrayBase obj,
int elements_to_trim);
// Trim the given array from the right.
V8_EXPORT_PRIVATE void RightTrimFixedArray(FixedArrayBase obj,
int elements_to_trim);
void RightTrimWeakFixedArray(WeakFixedArray obj, int elements_to_trim);
// Converts the given boolean condition to JavaScript boolean value.
inline Oddball ToBoolean(bool condition);
// Notify the heap that a context has been disposed.
V8_EXPORT_PRIVATE int NotifyContextDisposed(bool dependant_context);
void set_native_contexts_list(Object object) {
native_contexts_list_.store(object.ptr(), std::memory_order_release);
}
Object native_contexts_list() const {
return Object(native_contexts_list_.load(std::memory_order_acquire));
}
void set_allocation_sites_list(Object object) {
allocation_sites_list_ = object;
}
Object allocation_sites_list() { return allocation_sites_list_; }
void set_dirty_js_finalization_registries_list(Object object) {
dirty_js_finalization_registries_list_ = object;
}
Object dirty_js_finalization_registries_list() {
return dirty_js_finalization_registries_list_;
}
void set_dirty_js_finalization_registries_list_tail(Object object) {
dirty_js_finalization_registries_list_tail_ = object;
}
Object dirty_js_finalization_registries_list_tail() {
return dirty_js_finalization_registries_list_tail_;
}
// Used in CreateAllocationSiteStub and the (de)serializer.
Address allocation_sites_list_address() {
return reinterpret_cast<Address>(&allocation_sites_list_);
}
// Traverse all the allocation_sites [nested_site and weak_next] in the list
// and foreach call the visitor
void ForeachAllocationSite(
Object list, const std::function<void(AllocationSite)>& visitor);
// Number of mark-sweeps.
int ms_count() const { return ms_count_; }
// Checks whether the given object is allowed to be migrated from it's
// current space into the given destination space. Used for debugging.
bool AllowedToBeMigrated(Map map, HeapObject object, AllocationSpace dest);
void CheckHandleCount();
// Print short heap statistics.
void PrintShortHeapStatistics();
// Print statistics of freelists of old_space:
// with v8_flags.trace_gc_freelists: summary of each FreeListCategory.
// with v8_flags.trace_gc_freelists_verbose: also prints the statistics of
// each FreeListCategory of each page.
void PrintFreeListsStats();
// Dump heap statistics in JSON format.
void DumpJSONHeapStatistics(std::stringstream& stream);
bool write_protect_code_memory() const {
if (V8_HAS_PTHREAD_JIT_WRITE_PROTECT) {
// On MacOS on ARM64 ("Apple M1"/Apple Silicon) code modification
// protection must be used. It can be achieved by one of the following
// approaches:
// 1) switching memory protection between RW-RX as on other architectures
// => return true,
// 2) fast W^X machinery (see V8_HEAP_USE_PTHREAD_JIT_WRITE_PROTECT) which
// doesn not require memory protection changes => return false.
return !V8_HEAP_USE_PTHREAD_JIT_WRITE_PROTECT;
}
return write_protect_code_memory_;
}
uintptr_t code_space_memory_modification_scope_depth() {
return code_space_memory_modification_scope_depth_;
}
void increment_code_space_memory_modification_scope_depth() {
code_space_memory_modification_scope_depth_++;
}
void decrement_code_space_memory_modification_scope_depth() {
code_space_memory_modification_scope_depth_--;
}
void UnprotectAndRegisterMemoryChunk(MemoryChunk* chunk,
UnprotectMemoryOrigin origin);
V8_EXPORT_PRIVATE void UnprotectAndRegisterMemoryChunk(
HeapObject object, UnprotectMemoryOrigin origin);
void UnregisterUnprotectedMemoryChunk(MemoryChunk* chunk);
V8_EXPORT_PRIVATE void ProtectUnprotectedMemoryChunks();
inline void IncrementCodePageCollectionMemoryModificationScopeDepth();
inline bool DecrementCodePageCollectionMemoryModificationScopeDepth();
inline uintptr_t code_page_collection_memory_modification_scope_depth();
inline HeapState gc_state() const {
return gc_state_.load(std::memory_order_relaxed);
}
void SetGCState(HeapState state);
bool IsTearingDown() const { return gc_state() == TEAR_DOWN; }
bool force_oom() const { return force_oom_; }
bool ignore_local_gc_requests() const {
return ignore_local_gc_requests_depth_ > 0;
}
inline bool IsInGCPostProcessing() { return gc_post_processing_depth_ > 0; }
bool IsGCWithStack() const;
// If an object has an AllocationMemento trailing it, return it, otherwise
// return a null AllocationMemento.
template <FindMementoMode mode>
inline AllocationMemento FindAllocationMemento(Map map, HeapObject object);
// Performs GC after background allocation failure.
void CollectGarbageForBackground(LocalHeap* local_heap);
//
// Support for the API.
//
void CreateApiObjects();
// Implements the corresponding V8 API function.
bool IdleNotification(double deadline_in_seconds);
bool IdleNotification(int idle_time_in_ms);
V8_EXPORT_PRIVATE void MemoryPressureNotification(MemoryPressureLevel level,
bool is_isolate_locked);
void CheckMemoryPressure();
V8_EXPORT_PRIVATE void AddNearHeapLimitCallback(v8::NearHeapLimitCallback,
void* data);
V8_EXPORT_PRIVATE void RemoveNearHeapLimitCallback(
v8::NearHeapLimitCallback callback, size_t heap_limit);
V8_EXPORT_PRIVATE void AutomaticallyRestoreInitialHeapLimit(
double threshold_percent);
void AppendArrayBufferExtension(JSArrayBuffer object,
ArrayBufferExtension* extension);
void DetachArrayBufferExtension(JSArrayBuffer object,
ArrayBufferExtension* extension);
IsolateSafepoint* safepoint() { return safepoint_.get(); }
V8_EXPORT_PRIVATE double MonotonicallyIncreasingTimeInMs() const;
#if DEBUG
void VerifyNewSpaceTop();
#endif // DEBUG
void RecordStats(HeapStats* stats, bool take_snapshot = false);
bool MeasureMemory(std::unique_ptr<v8::MeasureMemoryDelegate> delegate,
v8::MeasureMemoryExecution execution);
std::unique_ptr<v8::MeasureMemoryDelegate> MeasureMemoryDelegate(
Handle<NativeContext> context, Handle<JSPromise> promise,
v8::MeasureMemoryMode mode);
// Check new space expansion criteria and expand semispaces if it was hit.
void CheckNewSpaceExpansionCriteria();
void VisitExternalResources(v8::ExternalResourceVisitor* visitor);
void IncrementDeferredCount(v8::Isolate::UseCounterFeature feature);
inline int NextScriptId();
inline int NextDebuggingId();
inline int GetNextTemplateSerialNumber();
void SetSerializedObjects(FixedArray objects);
void SetSerializedGlobalProxySizes(FixedArray sizes);
void SetBasicBlockProfilingData(Handle<ArrayList> list);
// For post mortem debugging.
void RememberUnmappedPage(Address page, bool compacted);
int64_t external_memory_hard_limit() { return max_old_generation_size() / 2; }
V8_INLINE int64_t external_memory();
V8_EXPORT_PRIVATE int64_t external_memory_limit();
V8_INLINE int64_t update_external_memory(int64_t delta);
V8_EXPORT_PRIVATE size_t YoungArrayBufferBytes();
V8_EXPORT_PRIVATE size_t OldArrayBufferBytes();
uint64_t backing_store_bytes() const {
return backing_store_bytes_.load(std::memory_order_relaxed);
}
void CompactWeakArrayLists();
V8_EXPORT_PRIVATE void AddRetainedMap(Handle<NativeContext> context,
Handle<Map> map);
// This event is triggered after object is moved to a new place.
void OnMoveEvent(HeapObject source, HeapObject target, int size_in_bytes);
bool deserialization_complete() const { return deserialization_complete_; }
// We can only invoke Safepoint() on the main thread local heap after
// deserialization is complete. Before that, main_thread_local_heap_ might be
// null.
V8_INLINE bool CanSafepoint() const { return deserialization_complete(); }
bool HasLowAllocationRate();
bool HasHighFragmentation();
bool HasHighFragmentation(size_t used, size_t committed);
void ActivateMemoryReducerIfNeeded();
V8_EXPORT_PRIVATE bool ShouldOptimizeForMemoryUsage();
bool HighMemoryPressure() {
return memory_pressure_level_.load(std::memory_order_relaxed) !=
MemoryPressureLevel::kNone;
}
bool CollectionRequested();
void CheckCollectionRequested();
void RestoreHeapLimit(size_t heap_limit) {
// Do not set the limit lower than the live size + some slack.
size_t min_limit = SizeOfObjects() + SizeOfObjects() / 4;
set_max_old_generation_size(
std::min(max_old_generation_size(), std::max(heap_limit, min_limit)));
}
#if V8_ENABLE_WEBASSEMBLY
// TODO(manoskouk): Inline this if STRONG_MUTABLE_MOVABLE_ROOT_LIST setters
// become public.
void EnsureWasmCanonicalRttsSize(int length);
#endif
// ===========================================================================
// Initialization. ===========================================================
// ===========================================================================
void ConfigureHeap(const v8::ResourceConstraints& constraints);
void ConfigureHeapDefault();
// Prepares the heap, setting up for deserialization.
void SetUp(LocalHeap* main_thread_local_heap);
// Sets read-only heap and space.
void SetUpFromReadOnlyHeap(ReadOnlyHeap* ro_heap);
void ReplaceReadOnlySpace(SharedReadOnlySpace* shared_ro_space);
// Sets up the heap memory without creating any objects.
void SetUpSpaces(LinearAllocationArea& new_allocation_info,
LinearAllocationArea& old_allocation_info);
// Prepares the heap, setting up for deserialization.
void InitializeMainThreadLocalHeap(LocalHeap* main_thread_local_heap);
// (Re-)Initialize hash seed from flag or RNG.
void InitializeHashSeed();
// Invoked once for the process from V8::Initialize.
static void InitializeOncePerProcess();
// Bootstraps the object heap with the core set of objects required to run.
// Returns whether it succeeded.
bool CreateHeapObjects();
// Create ObjectStats if live_object_stats_ or dead_object_stats_ are nullptr.
void CreateObjectStats();
// Sets the TearDown state, so no new GC tasks get posted.
void StartTearDown();
// Destroys all memory allocated by the heap.
void TearDown();
// Returns whether SetUp has been called.
bool HasBeenSetUp() const;
// ===========================================================================
// Getters for spaces. =======================================================
// ===========================================================================
inline Address NewSpaceTop();
NewSpace* new_space() const { return new_space_; }
inline PagedNewSpace* paged_new_space() const;
OldSpace* old_space() const { return old_space_; }
OldSpace* shared_old_space() const { return shared_old_space_; }
CodeSpace* code_space() const { return code_space_; }
MapSpace* map_space() const { return map_space_; }
inline PagedSpace* space_for_maps();
OldLargeObjectSpace* lo_space() const { return lo_space_; }
OldLargeObjectSpace* shared_lo_space() const { return shared_lo_space_; }
CodeLargeObjectSpace* code_lo_space() const { return code_lo_space_; }
NewLargeObjectSpace* new_lo_space() const { return new_lo_space_; }
ReadOnlySpace* read_only_space() const { return read_only_space_; }
inline PagedSpace* paged_space(int idx);
inline Space* space(int idx);
// ===========================================================================
// Getters to other components. ==============================================
// ===========================================================================
GCTracer* tracer() { return tracer_.get(); }
MemoryAllocator* memory_allocator() { return memory_allocator_.get(); }
const MemoryAllocator* memory_allocator() const {
return memory_allocator_.get();
}
inline ConcurrentAllocator* concurrent_allocator_for_maps();
inline Isolate* isolate() const;
#ifdef DEBUG
// Check if we run on isolate's main thread.
inline bool IsMainThread() const;
// Check if we run on the current main thread of the shared isolate during
// shared GC.
inline bool IsSharedMainThread() const;
#endif
MarkCompactCollector* mark_compact_collector() {
return mark_compact_collector_.get();
}
MinorMarkCompactCollector* minor_mark_compact_collector() {
return minor_mark_compact_collector_.get();
}
ArrayBufferSweeper* array_buffer_sweeper() {
return array_buffer_sweeper_.get();
}
// The potentially overreserved address space region reserved by the code
// range if it exists or empty region otherwise.
const base::AddressRegion& code_region();
CodeRange* code_range() { return code_range_.get(); }
// The base of the code range if it exists or null address.
inline Address code_range_base();
LocalHeap* main_thread_local_heap() { return main_thread_local_heap_; }
Heap* AsHeap() { return this; }
// ===========================================================================
// Root set access. ==========================================================
// ===========================================================================
// Shortcut to the roots table stored in the Isolate.
V8_INLINE RootsTable& roots_table();
// Heap root getters.
#define ROOT_ACCESSOR(type, name, CamelName) inline type name();
MUTABLE_ROOT_LIST(ROOT_ACCESSOR)
#undef ROOT_ACCESSOR
V8_INLINE FixedArray single_character_string_table();
V8_INLINE void SetRootMaterializedObjects(FixedArray objects);
V8_INLINE void SetRootScriptList(Object value);
V8_INLINE void SetRootNoScriptSharedFunctionInfos(Object value);
V8_INLINE void SetMessageListeners(TemplateList value);
V8_INLINE void SetPendingOptimizeForTestBytecode(Object bytecode);
StrongRootsEntry* RegisterStrongRoots(const char* label, FullObjectSlot start,
FullObjectSlot end);
void UnregisterStrongRoots(StrongRootsEntry* entry);
void UpdateStrongRoots(StrongRootsEntry* entry, FullObjectSlot start,
FullObjectSlot end);
void SetBuiltinsConstantsTable(FixedArray cache);
void SetDetachedContexts(WeakArrayList detached_contexts);
void EnqueueDirtyJSFinalizationRegistry(
JSFinalizationRegistry finalization_registry,
std::function<void(HeapObject object, ObjectSlot slot, Object target)>
gc_notify_updated_slot);
MaybeHandle<JSFinalizationRegistry> DequeueDirtyJSFinalizationRegistry();
// Called from Heap::NotifyContextDisposed to remove all
// FinalizationRegistries with {context} from the dirty list when the context
// e.g. navigates away or is detached. If the dirty list is empty afterwards,
// the cleanup task is aborted if needed.
void RemoveDirtyFinalizationRegistriesOnContext(NativeContext context);
inline bool HasDirtyJSFinalizationRegistries();
void PostFinalizationRegistryCleanupTaskIfNeeded();
void set_is_finalization_registry_cleanup_task_posted(bool posted) {
is_finalization_registry_cleanup_task_posted_ = posted;
}
bool is_finalization_registry_cleanup_task_posted() {
return is_finalization_registry_cleanup_task_posted_;
}
V8_EXPORT_PRIVATE void KeepDuringJob(Handle<JSReceiver> target);
void ClearKeptObjects();
// ===========================================================================
// Inline allocation. ========================================================
// ===========================================================================
// Switch whether inline bump-pointer allocation should be used.
V8_EXPORT_PRIVATE void EnableInlineAllocation();
V8_EXPORT_PRIVATE void DisableInlineAllocation();
// ===========================================================================
// Methods triggering GCs. ===================================================
// ===========================================================================
// Performs garbage collection operation.
// Returns whether there is a chance that another major GC could
// collect more garbage.
V8_EXPORT_PRIVATE bool CollectGarbage(
AllocationSpace space, GarbageCollectionReason gc_reason,
const GCCallbackFlags gc_callback_flags = kNoGCCallbackFlags);
// Performs a full garbage collection.
V8_EXPORT_PRIVATE void CollectAllGarbage(
int flags, GarbageCollectionReason gc_reason,
const GCCallbackFlags gc_callback_flags = kNoGCCallbackFlags);
// Last hope GC, should try to squeeze as much as possible.
V8_EXPORT_PRIVATE void CollectAllAvailableGarbage(
GarbageCollectionReason gc_reason);
// Precise garbage collection that potentially finalizes already running
// incremental marking before performing an atomic garbage collection.
// Only use if absolutely necessary or in tests to avoid floating garbage!
V8_EXPORT_PRIVATE void PreciseCollectAllGarbage(
int flags, GarbageCollectionReason gc_reason,
const GCCallbackFlags gc_callback_flags = kNoGCCallbackFlags);
// Performs garbage collection operation for the shared heap.
V8_EXPORT_PRIVATE void CollectSharedGarbage(
GarbageCollectionReason gc_reason);
// Reports and external memory pressure event, either performs a major GC or
// completes incremental marking in order to free external resources.
void ReportExternalMemoryPressure();
using GetExternallyAllocatedMemoryInBytesCallback =
v8::Isolate::GetExternallyAllocatedMemoryInBytesCallback;
void SetGetExternallyAllocatedMemoryInBytesCallback(
GetExternallyAllocatedMemoryInBytesCallback callback) {
external_memory_callback_ = callback;
}
// Invoked when GC was requested via the stack guard.
void HandleGCRequest();
// ===========================================================================
// Iterators. ================================================================
// ===========================================================================
// None of these methods iterate over the read-only roots. To do this use
// ReadOnlyRoots::Iterate. Read-only root iteration is not necessary for
// garbage collection and is usually only performed as part of
// (de)serialization or heap verification.
// Iterates over the strong roots and the weak roots.
void IterateRoots(RootVisitor* v, base::EnumSet<SkipRoot> options);
void IterateRootsIncludingClients(RootVisitor* v,
base::EnumSet<SkipRoot> options);
void IterateRootsFromStackIncludingClient(RootVisitor* v);
// Iterates over entries in the smi roots list. Only interesting to the
// serializer/deserializer, since GC does not care about smis.
void IterateSmiRoots(RootVisitor* v);
// Iterates over weak string tables.
void IterateWeakRoots(RootVisitor* v, base::EnumSet<SkipRoot> options);
void IterateWeakGlobalHandles(RootVisitor* v);
void IterateBuiltins(RootVisitor* v);
void IterateStackRoots(RootVisitor* v);
// ===========================================================================
// Remembered set API. =======================================================
// ===========================================================================
// Used for query incremental marking status in generated code.
uint8_t* IsMarkingFlagAddress();
uint8_t* IsMinorMarkingFlagAddress();
void ClearRecordedSlot(HeapObject object, ObjectSlot slot);
void ClearRecordedSlotRange(Address start, Address end);
static int InsertIntoRememberedSetFromCode(MemoryChunk* chunk, Address slot);
#ifdef DEBUG
void VerifyClearedSlot(HeapObject object, ObjectSlot slot);
void VerifySlotRangeHasNoRecordedSlots(Address start, Address end);
#endif
// ===========================================================================
// Incremental marking API. ==================================================
// ===========================================================================
int GCFlagsForIncrementalMarking() {
return ShouldOptimizeForMemoryUsage() ? kReduceMemoryFootprintMask
: kNoGCFlags;
}
// Start incremental marking and ensure that idle time handler can perform
// incremental steps.
V8_EXPORT_PRIVATE void StartIdleIncrementalMarking(
GarbageCollectionReason gc_reason,
GCCallbackFlags gc_callback_flags = GCCallbackFlags::kNoGCCallbackFlags);
// Starts incremental marking assuming incremental marking is currently
// stopped.
V8_EXPORT_PRIVATE void StartIncrementalMarking(
int gc_flags, GarbageCollectionReason gc_reason,
GCCallbackFlags gc_callback_flags = GCCallbackFlags::kNoGCCallbackFlags,
GarbageCollector collector = GarbageCollector::MARK_COMPACTOR);
V8_EXPORT_PRIVATE void StartIncrementalMarkingIfAllocationLimitIsReached(
int gc_flags,
GCCallbackFlags gc_callback_flags = GCCallbackFlags::kNoGCCallbackFlags);
void StartIncrementalMarkingIfAllocationLimitIsReachedBackground();
void FinalizeIncrementalMarkingIfComplete(GarbageCollectionReason gc_reason);
// Synchronously finalizes incremental marking.
V8_EXPORT_PRIVATE void FinalizeIncrementalMarkingAtomically(
GarbageCollectionReason gc_reason);
V8_EXPORT_PRIVATE void CompleteSweepingFull();
void CompleteSweepingYoung(GarbageCollector collector);
// Ensures that sweeping is finished for that object's page.
void EnsureSweepingCompleted(HeapObject object);
IncrementalMarking* incremental_marking() const {
return incremental_marking_.get();
}
// ===========================================================================
// Concurrent marking API. ===================================================
// ===========================================================================
ConcurrentMarking* concurrent_marking() const {
return concurrent_marking_.get();
}
// The runtime uses this function to notify potentially unsafe object layout
// changes that require special synchronization with the concurrent marker.
// By default recorded slots in the object are invalidated. Pass
// InvalidateRecordedSlots::kNo if this is not necessary or to perform this
// manually.
void NotifyObjectLayoutChange(
HeapObject object, const DisallowGarbageCollection&,
InvalidateRecordedSlots invalidate_recorded_slots, int new_size = 0);
// The runtime uses this function to inform the GC of object size changes. The
// GC will fill this area with a filler object and might clear recorded slots
// in that area.
void NotifyObjectSizeChange(HeapObject, int old_size, int new_size,
ClearRecordedSlots clear_recorded_slots);
// ===========================================================================
// Deoptimization support API. ===============================================
// ===========================================================================
// Setters for code offsets of well-known deoptimization targets.
void SetConstructStubCreateDeoptPCOffset(int pc_offset);
void SetConstructStubInvokeDeoptPCOffset(int pc_offset);
void SetInterpreterEntryReturnPCOffset(int pc_offset);
// Invalidates references in the given {code} object that are referenced
// transitively from the deoptimization data. Mutates write-protected code.
void InvalidateCodeDeoptimizationData(Code code);
void DeoptMarkedAllocationSites();
bool DeoptMaybeTenuredAllocationSites();
// ===========================================================================
// Embedder heap tracer support. =============================================
// ===========================================================================
LocalEmbedderHeapTracer* local_embedder_heap_tracer() const {
return local_embedder_heap_tracer_.get();
}
START_ALLOW_USE_DEPRECATED()
V8_EXPORT_PRIVATE void SetEmbedderHeapTracer(EmbedderHeapTracer* tracer);
EmbedderHeapTracer* GetEmbedderHeapTracer() const;
EmbedderHeapTracer::TraceFlags flags_for_embedder_tracer() const;
END_ALLOW_USE_DEPRECATED()
void RegisterExternallyReferencedObject(Address* location);
// ===========================================================================
// Unified heap (C++) support. ===============================================
// ===========================================================================
V8_EXPORT_PRIVATE void AttachCppHeap(v8::CppHeap* cpp_heap);
V8_EXPORT_PRIVATE void DetachCppHeap();
v8::CppHeap* cpp_heap() const { return cpp_heap_; }
const cppgc::EmbedderStackState* overriden_stack_state() const;
V8_EXPORT_PRIVATE void SetStackStart(void* stack_start);
::heap::base::Stack& stack();
// ===========================================================================
// Embedder roots optimizations. =============================================
// ===========================================================================
V8_EXPORT_PRIVATE
void SetEmbedderRootsHandler(EmbedderRootsHandler* handler);
EmbedderRootsHandler* GetEmbedderRootsHandler() const;
// ===========================================================================
// External string table API. ================================================
// ===========================================================================
// Registers an external string.
inline void RegisterExternalString(String string);
// Called when a string's resource is changed. The size of the payload is sent
// as argument of the method.
V8_EXPORT_PRIVATE void UpdateExternalString(String string, size_t old_payload,
size_t new_payload);
// Finalizes an external string by deleting the associated external
// data and clearing the resource pointer.
inline void FinalizeExternalString(String string);
static String UpdateYoungReferenceInExternalStringTableEntry(
Heap* heap, FullObjectSlot pointer);
// ===========================================================================
// Methods checking/returning the space of a given object/address. ===========
// ===========================================================================
// Returns whether the object resides in new space.
static inline bool InYoungGeneration(Object object);
static inline bool InYoungGeneration(MaybeObject object);
static inline bool InYoungGeneration(HeapObject heap_object);
static inline bool InFromPage(Object object);
static inline bool InFromPage(MaybeObject object);
static inline bool InFromPage(HeapObject heap_object);
static inline bool InToPage(Object object);
static inline bool InToPage(MaybeObject object);
static inline bool InToPage(HeapObject heap_object);
// Returns whether the object resides in old space.
inline bool InOldSpace(Object object);
// Checks whether an address/object is in the non-read-only heap (including
// auxiliary area and unused area). Use IsValidHeapObject if checking both
// heaps is required.
V8_EXPORT_PRIVATE bool Contains(HeapObject value) const;
// Same as above, but checks whether the object resides in any of the code
// spaces.
V8_EXPORT_PRIVATE bool ContainsCode(HeapObject value) const;
// Checks whether object resides in the non-read-only shared heap.
static inline bool InSharedWritableHeap(MaybeObject object);
// Checks whether an address/object is in the non-read-only heap (including
// auxiliary area and unused area). Use IsValidHeapObject if checking both
// heaps is required.
V8_EXPORT_PRIVATE bool SharedHeapContains(HeapObject value) const;
// Returns whether the object must be in the shared old space.
V8_EXPORT_PRIVATE bool MustBeInSharedOldSpace(HeapObject value);
// Checks whether an address/object in a space.
// Currently used by tests, serialization and heap verification only.
V8_EXPORT_PRIVATE bool InSpace(HeapObject value, AllocationSpace space) const;
// Returns true when this heap is shared.
V8_EXPORT_PRIVATE bool IsShared();
// Slow methods that can be used for verification as they can also be used
// with off-heap Addresses.
V8_EXPORT_PRIVATE bool InSpaceSlow(Address addr, AllocationSpace space) const;
static inline Heap* FromWritableHeapObject(HeapObject obj);
// ===========================================================================
// Object statistics tracking. ===============================================
// ===========================================================================
// Returns the number of buckets used by object statistics tracking during a
// major GC. Note that the following methods fail gracefully when the bounds
// are exceeded though.
size_t NumberOfTrackedHeapObjectTypes();
// Returns object statistics about count and size at the last major GC.
// Objects are being grouped into buckets that roughly resemble existing
// instance types.
size_t ObjectCountAtLastGC(size_t index);
size_t ObjectSizeAtLastGC(size_t index);
// Retrieves names of buckets used by object statistics tracking.
bool GetObjectTypeName(size_t index, const char** object_type,
const char** object_sub_type);
// The total number of native contexts object on the heap.
size_t NumberOfNativeContexts();
// The total number of native contexts that were detached but were not
// garbage collected yet.
size_t NumberOfDetachedContexts();
// ===========================================================================
// Code statistics. ==========================================================
// ===========================================================================
// Collect code (Code and BytecodeArray objects) statistics.
void CollectCodeStatistics();
// ===========================================================================
// GC statistics. ============================================================
// ===========================================================================
// Returns the maximum amount of memory reserved for the heap.
V8_EXPORT_PRIVATE size_t MaxReserved();
size_t MaxSemiSpaceSize() { return max_semi_space_size_; }
size_t InitialSemiSpaceSize() { return initial_semispace_size_; }
size_t MaxOldGenerationSize() { return max_old_generation_size(); }
// Limit on the max old generation size imposed by the underlying allocator.
V8_EXPORT_PRIVATE static size_t AllocatorLimitOnMaxOldGenerationSize();
V8_EXPORT_PRIVATE static size_t HeapSizeFromPhysicalMemory(
uint64_t physical_memory);
V8_EXPORT_PRIVATE static void GenerationSizesFromHeapSize(
size_t heap_size, size_t* young_generation_size,
size_t* old_generation_size);
V8_EXPORT_PRIVATE static size_t YoungGenerationSizeFromOldGenerationSize(
size_t old_generation_size);
V8_EXPORT_PRIVATE static size_t YoungGenerationSizeFromSemiSpaceSize(
size_t semi_space_size);
V8_EXPORT_PRIVATE static size_t SemiSpaceSizeFromYoungGenerationSize(
size_t young_generation_size);
V8_EXPORT_PRIVATE static size_t MinYoungGenerationSize();
V8_EXPORT_PRIVATE static size_t MinOldGenerationSize();
V8_EXPORT_PRIVATE static size_t MaxOldGenerationSize(
uint64_t physical_memory);
// Returns the capacity of the heap in bytes w/o growing. Heap grows when
// more spaces are needed until it reaches the limit.
size_t Capacity();
// Returns the capacity of the old generation.
V8_EXPORT_PRIVATE size_t OldGenerationCapacity();
// Returns the amount of memory currently held alive by the unmapper.
size_t CommittedMemoryOfUnmapper();
// Returns the amount of memory currently committed for the heap.
size_t CommittedMemory();
// Returns the amount of memory currently committed for the old space.
size_t CommittedOldGenerationMemory();
// Returns the amount of executable memory currently committed for the heap.
size_t CommittedMemoryExecutable();
// Returns the amount of physical memory currently committed for the heap.
size_t CommittedPhysicalMemory();
// Returns the maximum amount of memory ever committed for the heap.
size_t MaximumCommittedMemory() { return maximum_committed_; }
// Updates the maximum committed memory for the heap. Should be called
// whenever a space grows.
void UpdateMaximumCommitted();
// Returns the available bytes in space w/o growing.
// Heap doesn't guarantee that it can allocate an object that requires
// all available bytes. Check MaxHeapObjectSize() instead.
size_t Available();
// Returns size of all objects residing in the heap.
V8_EXPORT_PRIVATE size_t SizeOfObjects();
// Returns size of all global handles in the heap.
V8_EXPORT_PRIVATE size_t TotalGlobalHandlesSize();
// Returns size of all allocated/used global handles in the heap.
V8_EXPORT_PRIVATE size_t UsedGlobalHandlesSize();
void UpdateSurvivalStatistics(int start_new_space_size);
inline void IncrementPromotedObjectsSize(size_t object_size) {
promoted_objects_size_ += object_size;
}
inline size_t promoted_objects_size() { return promoted_objects_size_; }
inline void IncrementSemiSpaceCopiedObjectSize(size_t object_size) {
semi_space_copied_object_size_ += object_size;
}
inline size_t semi_space_copied_object_size() {
return semi_space_copied_object_size_;
}
inline size_t SurvivedYoungObjectSize() {
return promoted_objects_size_ + semi_space_copied_object_size_;
}
inline void IncrementNodesDiedInNewSpace(int count) {
nodes_died_in_new_space_ += count;
}
inline void IncrementNodesCopiedInNewSpace() { nodes_copied_in_new_space_++; }
inline void IncrementNodesPromoted() { nodes_promoted_++; }
inline void IncrementYoungSurvivorsCounter(size_t survived) {
survived_last_scavenge_ = survived;
survived_since_last_expansion_ += survived;
}
void UpdateNewSpaceAllocationCounter();
V8_EXPORT_PRIVATE size_t NewSpaceAllocationCounter();
// This should be used only for testing.
void set_new_space_allocation_counter(size_t new_value) {
new_space_allocation_counter_ = new_value;
}
void UpdateOldGenerationAllocationCounter() {
old_generation_allocation_counter_at_last_gc_ =
OldGenerationAllocationCounter();
old_generation_size_at_last_gc_ = 0;
}
size_t OldGenerationAllocationCounter() {
return old_generation_allocation_counter_at_last_gc_ +
PromotedSinceLastGC();
}
size_t EmbedderAllocationCounter() const;
// This should be used only for testing.
void set_old_generation_allocation_counter_at_last_gc(size_t new_value) {
old_generation_allocation_counter_at_last_gc_ = new_value;
}
size_t PromotedSinceLastGC() {
size_t old_generation_size = OldGenerationSizeOfObjects();
return old_generation_size > old_generation_size_at_last_gc_
? old_generation_size - old_generation_size_at_last_gc_
: 0;
}
int gc_count() const { return gc_count_; }
bool is_current_gc_forced() const { return is_current_gc_forced_; }
GarbageCollector current_or_last_garbage_collector() const {
return current_or_last_garbage_collector_;
}
// Returns whether the currently in-progress GC should avoid increasing the
// ages on any objects that live for a set number of collections.
bool ShouldCurrentGCKeepAgesUnchanged() const {
return is_current_gc_forced_ || is_current_gc_for_heap_profiler_;
}
// Returns the size of objects residing in non-new spaces.
// Excludes external memory held by those objects.
V8_EXPORT_PRIVATE size_t OldGenerationSizeOfObjects();
// Returns the size of objects held by the EmbedderHeapTracer.
V8_EXPORT_PRIVATE size_t EmbedderSizeOfObjects() const;
// Returns the global size of objects (embedder + V8 non-new spaces).
V8_EXPORT_PRIVATE size_t GlobalSizeOfObjects();
// We allow incremental marking to overshoot the V8 and global allocation
// limit for performance reasons. If the overshoot is too large then we are
// more eager to finalize incremental marking.
bool AllocationLimitOvershotByLargeMargin();
// Return the maximum size objects can be before having to allocate them as
// large objects. This takes into account allocating in the code space for
// which the size of the allocatable space per V8 page may depend on the OS
// page size at runtime. You may use kMaxRegularHeapObjectSize as a constant
// instead if you know the allocation isn't in the code spaces.
inline V8_EXPORT_PRIVATE int MaxRegularHeapObjectSize(
AllocationType allocation);
// ===========================================================================
// Prologue/epilogue callback methods.========================================
// ===========================================================================
void AddGCPrologueCallback(v8::Isolate::GCCallbackWithData callback,
GCType gc_type_filter, void* data);
void RemoveGCPrologueCallback(v8::Isolate::GCCallbackWithData callback,
void* data);
void AddGCEpilogueCallback(v8::Isolate::GCCallbackWithData callback,
GCType gc_type_filter, void* data);
void RemoveGCEpilogueCallback(v8::Isolate::GCCallbackWithData callback,
void* data);
void CallGCPrologueCallbacks(GCType gc_type, GCCallbackFlags flags);
void CallGCEpilogueCallbacks(GCType gc_type, GCCallbackFlags flags);
// ===========================================================================
// Allocation methods. =======================================================
// ===========================================================================
// Creates a filler object and returns a heap object immediately after it.
V8_EXPORT_PRIVATE HeapObject PrecedeWithFiller(HeapObject object,
int filler_size);
// Creates a filler object if needed for alignment and returns a heap object
// immediately after it. If any space is left after the returned object,
// another filler object is created so the over allocated memory is iterable.
V8_WARN_UNUSED_RESULT HeapObject
AlignWithFiller(HeapObject object, int object_size, int allocation_size,
AllocationAlignment alignment);
// Allocate an external backing store with the given allocation callback.
// If the callback fails (indicated by a nullptr result) then this function
// will re-try the allocation after performing GCs. This is useful for
// external backing stores that may be retained by (unreachable) V8 objects
// such as ArrayBuffers, ExternalStrings, etc.
//
// The function may also proactively trigger GCs even if the allocation
// callback does not fail to keep the memory usage low.
V8_EXPORT_PRIVATE void* AllocateExternalBackingStore(
const std::function<void*(size_t)>& allocate, size_t byte_length);
// ===========================================================================
// Allocation site tracking. =================================================
// ===========================================================================
// Updates the AllocationSite of a given {object}. The entry (including the
// count) is cached on the local pretenuring feedback.
inline void UpdateAllocationSite(
Map map, HeapObject object, PretenuringFeedbackMap* pretenuring_feedback);
// Merges local pretenuring feedback into the global one. Note that this
// method needs to be called after evacuation, as allocation sites may be
// evacuated and this method resolves forward pointers accordingly.
void MergeAllocationSitePretenuringFeedback(
const PretenuringFeedbackMap& local_pretenuring_feedback);
// Adds an allocation site to the list of sites to be pretenured during the
// next collection. Added allocation sites are pretenured independent of
// their feedback.
V8_EXPORT_PRIVATE void PretenureAllocationSiteOnNextCollection(
AllocationSite site);
// ===========================================================================
// Allocation tracking. ======================================================
// ===========================================================================
// Adds {new_space_observer} to new space and {observer} to any other space.
void AddAllocationObserversToAllSpaces(
AllocationObserver* observer, AllocationObserver* new_space_observer);
// Removes {new_space_observer} from new space and {observer} from any other
// space.
void RemoveAllocationObserversFromAllSpaces(
AllocationObserver* observer, AllocationObserver* new_space_observer);
// Check if the given object was recently allocated and its fields may appear
// as uninitialized to background threads.
// This predicate may be invoked from a background thread.
inline bool IsPendingAllocation(HeapObject object);
inline bool IsPendingAllocation(Object object);
// Notifies that all previously allocated objects are properly initialized
// and ensures that IsPendingAllocation returns false for them. This function
// may be invoked only on the main thread.
V8_EXPORT_PRIVATE void PublishPendingAllocations();
// ===========================================================================
// Heap object allocation tracking. ==========================================
// ===========================================================================
V8_EXPORT_PRIVATE void AddHeapObjectAllocationTracker(
HeapObjectAllocationTracker* tracker);
V8_EXPORT_PRIVATE void RemoveHeapObjectAllocationTracker(
HeapObjectAllocationTracker* tracker);
bool has_heap_object_allocation_tracker() const {
return !allocation_trackers_.empty();
}
// ===========================================================================
// Retaining path tracking. ==================================================
// ===========================================================================
// Adds the given object to the weak table of retaining path targets.
// On each GC if the marker discovers the object, it will print the retaining
// path. This requires --track-retaining-path flag.
void AddRetainingPathTarget(Handle<HeapObject> object,
RetainingPathOption option);
// ===========================================================================
// Stack frame support. ======================================================
// ===========================================================================
// Searches for compiled code or embedded builtins code object by given
// interior pointer.
// Crashes process on unsuccessful lookup if {die_on_unsuccessful_lookup}
// is true. All code lookups made by GC must succeed.
CodeLookupResult GcSafeFindCodeForInnerPointer(
Address inner_pointer, bool die_on_unsuccessful_lookup = true);
// Same as GcSafeFindCodeForInnerPointer() but it doesn't crash the process
// on unsuccessful lookup.
// It's intended to be used only from gdb's 'jco' macro.
CodeLookupResult GcSafeFindCodeForInnerPointerForPrinting(
Address inner_pointer);
// Returns true if {addr} is contained within {code} and false otherwise.
// Mostly useful for debugging.
bool GcSafeCodeContains(Code code, Address addr);
// Casts a heap object to a code object and checks if the inner_pointer is
// within the object.
CodeLookupResult GcSafeCastToCode(HeapObject object, Address inner_pointer);
// Returns the map of an object. Can be used during garbage collection, i.e.
// it supports a forwarded map. Fails if the map is not the code map.
Map GcSafeMapOfCodeSpaceObject(HeapObject object);
// =============================================================================
#ifdef V8_ENABLE_ALLOCATION_TIMEOUT
void V8_EXPORT_PRIVATE set_allocation_timeout(int allocation_timeout);
#endif // V8_ENABLE_ALLOCATION_TIMEOUT
#ifdef DEBUG
void VerifyCountersAfterSweeping();
void VerifyCountersBeforeConcurrentSweeping();
void VerifyCommittedPhysicalMemory();
void Print();
void PrintHandles();
// Report code statistics.
void ReportCodeStatistics(const char* title);
#endif // DEBUG
void* GetRandomMmapAddr() {
void* result = v8::internal::GetRandomMmapAddr();
#if V8_TARGET_ARCH_X64
#if V8_OS_DARWIN
// The Darwin kernel [as of macOS 10.12.5] does not clean up page
// directory entries [PDE] created from mmap or mach_vm_allocate, even
// after the region is destroyed. Using a virtual address space that is
// too large causes a leak of about 1 wired [can never be paged out] page
// per call to mmap(). The page is only reclaimed when the process is
// killed. Confine the hint to a 32-bit section of the virtual address
// space. See crbug.com/700928.
uintptr_t offset = reinterpret_cast<uintptr_t>(result) & kMmapRegionMask;
result = reinterpret_cast<void*>(mmap_region_base_ + offset);
#endif // V8_OS_DARWIN
#endif // V8_TARGET_ARCH_X64
return result;
}
void RegisterCodeObject(Handle<Code> code);
static const char* GarbageCollectionReasonToString(
GarbageCollectionReason gc_reason);
// Calculates the nof entries for the full sized number to string cache.
inline int MaxNumberToStringCacheSize() const;
static Isolate* GetIsolateFromWritableObject(HeapObject object);
// Ensure that we have swept all spaces in such a way that we can iterate
// over all objects.
void MakeHeapIterable();
V8_EXPORT_PRIVATE bool CanPromoteYoungAndExpandOldGeneration(size_t size);
V8_EXPORT_PRIVATE bool CanExpandOldGeneration(size_t size);
inline bool ShouldReduceMemory() const {
return (current_gc_flags_ & kReduceMemoryFootprintMask) != 0;
}
private:
class AllocationTrackerForDebugging;
using ExternalStringTableUpdaterCallback = String (*)(Heap* heap,
FullObjectSlot pointer);
// External strings table is a place where all external strings are
// registered. We need to keep track of such strings to properly
// finalize them.
class ExternalStringTable {
public:
explicit ExternalStringTable(Heap* heap) : heap_(heap) {}
ExternalStringTable(const ExternalStringTable&) = delete;
ExternalStringTable& operator=(const ExternalStringTable&) = delete;
// Registers an external string.
inline void AddString(String string);
bool Contains(String string);
void IterateAll(RootVisitor* v);
void IterateYoung(RootVisitor* v);
void PromoteYoung();
// Restores internal invariant and gets rid of collected strings. Must be
// called after each Iterate*() that modified the strings.
void CleanUpAll();
void CleanUpYoung();
// Finalize all registered external strings and clear tables.
void TearDown();
void UpdateYoungReferences(
Heap::ExternalStringTableUpdaterCallback updater_func);
void UpdateReferences(
Heap::ExternalStringTableUpdaterCallback updater_func);
private:
void Verify();
void VerifyYoung();
Heap* const heap_;
// To speed up scavenge collections young string are kept separate from old
// strings.
std::vector<Object> young_strings_;
std::vector<Object> old_strings_;
};
struct StringTypeTable {
InstanceType type;
int size;
RootIndex index;
};
struct ConstantStringTable {
const char* contents;
RootIndex index;
};
struct StructTable {
InstanceType type;
int size;
RootIndex index;
};
static const int kInitialEvalCacheSize = 64;
static const int kInitialNumberStringCacheSize = 256;
static const int kRememberedUnmappedPages = 128;
static const StringTypeTable string_type_table[];
static const ConstantStringTable constant_string_table[];
static const StructTable struct_table[];
static const int kYoungSurvivalRateHighThreshold = 90;
static const int kYoungSurvivalRateAllowedDeviation = 15;
static const int kOldSurvivalRateLowThreshold = 10;
static const int kMaxMarkCompactsInIdleRound = 7;
static const int kInitialFeedbackCapacity = 256;
Heap();
~Heap();
Heap(const Heap&) = delete;
Heap& operator=(const Heap&) = delete;
static bool IsRegularObjectAllocation(AllocationType allocation) {
return AllocationType::kYoung == allocation ||
AllocationType::kOld == allocation;
}
static size_t DefaultGetExternallyAllocatedMemoryInBytesCallback() {
return 0;
}
#define ROOT_ACCESSOR(type, name, CamelName) inline void set_##name(type value);
ROOT_LIST(ROOT_ACCESSOR)
#undef ROOT_ACCESSOR
void set_current_gc_flags(int flags) { current_gc_flags_ = flags; }
int NumberOfScavengeTasks();
// Checks whether a global GC is necessary
GarbageCollector SelectGarbageCollector(AllocationSpace space,
GarbageCollectionReason gc_reason,
const char** reason);
// Free all LABs in the heap.
void FreeLinearAllocationAreas();
// Free all shared LABs.
void FreeSharedLinearAllocationAreas();
// Free all shared LABs of main thread.
void FreeMainThreadSharedLinearAllocationAreas();
// Performs garbage collection in a safepoint.
// Returns the number of freed global handles.
size_t PerformGarbageCollection(
GarbageCollector collector, GarbageCollectionReason gc_reason,
const char* collector_reason,
const GCCallbackFlags gc_callback_flags = kNoGCCallbackFlags);
// Performs garbage collection in the shared heap.
void PerformSharedGarbageCollection(Isolate* initiator,
GarbageCollectionReason gc_reason);
inline void UpdateOldSpaceLimits();
bool CreateInitialMaps();
void CreateInternalAccessorInfoObjects();
void CreateInitialObjects();
// Zaps the memory of a code object.
V8_EXPORT_PRIVATE void ZapCodeObject(Address start_address,
int size_in_bytes);
// Updates invalidated object size in all remembered sets.
void UpdateInvalidatedObjectSize(HeapObject object, int new_size);
enum class VerifyNoSlotsRecorded { kYes, kNo };
// This method is used by the sweeper on free memory ranges to make the page
// iterable again. Unlike `CreateFillerObjectAt` this method will not verify
// slots since the sweeper can run concurrently.
void CreateFillerObjectAtSweeper(Address addr, int size);
// Creates a filler object in the specified memory area. This method is the
// internal method used by all CreateFillerObjectAtXXX-methods.
void CreateFillerObjectAtRaw(Address addr, int size,
ClearFreedMemoryMode clear_memory_mode,
ClearRecordedSlots clear_slots_mode,
VerifyNoSlotsRecorded verify_no_slots_recorded);
// Range write barrier implementation.
template <int kModeMask, typename TSlot>
V8_INLINE void WriteBarrierForRangeImpl(MemoryChunk* source_page,
HeapObject object, TSlot start_slot,
TSlot end_slot);
// Deopts all code that contains allocation instruction which are tenured or
// not tenured. Moreover it clears the pretenuring allocation site statistics.
void ResetAllAllocationSitesDependentCode(AllocationType allocation);
// Evaluates local pretenuring for the old space and calls
// ResetAllTenuredAllocationSitesDependentCode if too many objects died in
// the old space.
void EvaluateOldSpaceLocalPretenuring(uint64_t size_of_objects_before_gc);
// Record statistics after garbage collection.
void ReportStatisticsAfterGC();
// Flush the number to string cache.
void FlushNumberStringCache();
void ConfigureInitialOldGenerationSize();
double ComputeMutatorUtilization(const char* tag, double mutator_speed,
double gc_speed);
bool HasLowYoungGenerationAllocationRate();
bool HasLowOldGenerationAllocationRate();
bool HasLowEmbedderAllocationRate();
void ReduceNewSpaceSize();
GCIdleTimeHeapState ComputeHeapState();
bool PerformIdleTimeAction(GCIdleTimeAction action,
GCIdleTimeHeapState heap_state,
double deadline_in_ms);
void IdleNotificationEpilogue(GCIdleTimeAction action,
GCIdleTimeHeapState heap_state, double start_ms,
double deadline_in_ms);
void PrintMaxMarkingLimitReached();
void PrintMaxNewSpaceSizeReached();
int NextStressMarkingLimit();
void AddToRingBuffer(const char* string);
void GetFromRingBuffer(char* buffer);
void CompactRetainedMaps(WeakArrayList retained_maps);
void CollectGarbageOnMemoryPressure();
void EagerlyFreeExternalMemory();
bool InvokeNearHeapLimitCallback();
void InvokeIncrementalMarkingPrologueCallbacks();
void InvokeIncrementalMarkingEpilogueCallbacks();
// ===========================================================================
// Pretenuring. ==============================================================
// ===========================================================================
// Pretenuring decisions are made based on feedback collected during new space
// evacuation. Note that between feedback collection and calling this method
// object in old space must not move.
void ProcessPretenuringFeedback();
// Removes an entry from the global pretenuring storage.
void RemoveAllocationSitePretenuringFeedback(AllocationSite site);
// ===========================================================================
// Actual GC. ================================================================
// ===========================================================================
// Code that should be run before and after each GC. Includes some
// reporting/verification activities when compiled with DEBUG set.
void GarbageCollectionPrologue(GarbageCollectionReason gc_reason,
const v8::GCCallbackFlags gc_callback_flags);
void GarbageCollectionPrologueInSafepoint();
void GarbageCollectionEpilogue(GarbageCollector collector);
void GarbageCollectionEpilogueInSafepoint(GarbageCollector collector);
// Performs a major collection in the whole heap.
void MarkCompact();
// Performs a minor collection of just the young generation.
void MinorMarkCompact();
// Code to be run before and after mark-compact.
void MarkCompactPrologue();
void MarkCompactEpilogue();
// Performs a minor collection in new generation.
void Scavenge();
void UpdateYoungReferencesInExternalStringTable(
ExternalStringTableUpdaterCallback updater_func);
void UpdateReferencesInExternalStringTable(
ExternalStringTableUpdaterCallback updater_func);
void ProcessAllWeakReferences(WeakObjectRetainer* retainer);
void ProcessNativeContexts(WeakObjectRetainer* retainer);
void ProcessAllocationSites(WeakObjectRetainer* retainer);
void ProcessDirtyJSFinalizationRegistries(WeakObjectRetainer* retainer);
void ProcessWeakListRoots(WeakObjectRetainer* retainer);
// ===========================================================================
// GC statistics. ============================================================
// ===========================================================================
inline size_t OldGenerationSpaceAvailable() {
uint64_t bytes = OldGenerationSizeOfObjects() +
AllocatedExternalMemorySinceMarkCompact();
if (old_generation_allocation_limit() <= bytes) return 0;
return old_generation_allocation_limit() - static_cast<size_t>(bytes);
}
void UpdateTotalGCTime(double duration);
bool MaximumSizeScavenge() { return maximum_size_scavenges_ > 0; }
bool IsIneffectiveMarkCompact(size_t old_generation_size,
double mutator_utilization);
void CheckIneffectiveMarkCompact(size_t old_generation_size,
double mutator_utilization);
inline void IncrementExternalBackingStoreBytes(ExternalBackingStoreType type,
size_t amount);
inline void DecrementExternalBackingStoreBytes(ExternalBackingStoreType type,
size_t amount);
// ===========================================================================
// Growing strategy. =========================================================
// ===========================================================================
MemoryReducer* memory_reducer() { return memory_reducer_.get(); }
// For some webpages RAIL mode does not switch from PERFORMANCE_LOAD.
// This constant limits the effect of load RAIL mode on GC.
// The value is arbitrary and chosen as the largest load time observed in
// v8 browsing benchmarks.
static const int kMaxLoadTimeMs = 7000;
bool ShouldOptimizeForLoadTime();
size_t old_generation_allocation_limit() const {
return old_generation_allocation_limit_.load(std::memory_order_relaxed);
}
void set_old_generation_allocation_limit(size_t newlimit) {
old_generation_allocation_limit_.store(newlimit, std::memory_order_relaxed);
}
size_t global_allocation_limit() const { return global_allocation_limit_; }
size_t max_old_generation_size() {
return max_old_generation_size_.load(std::memory_order_relaxed);
}
void set_max_old_generation_size(size_t value) {
max_old_generation_size_.store(value, std::memory_order_relaxed);
}
bool always_allocate() { return always_allocate_scope_count_ != 0; }
V8_EXPORT_PRIVATE bool CanExpandOldGenerationBackground(LocalHeap* local_heap,
size_t size);
bool ShouldExpandOldGenerationOnSlowAllocation(
LocalHeap* local_heap = nullptr);
bool IsRetryOfFailedAllocation(LocalHeap* local_heap);
bool IsMainThreadParked(LocalHeap* local_heap);
bool IsMajorMarkingComplete(LocalHeap* local_heap);
HeapGrowingMode CurrentHeapGrowingMode();
double PercentToOldGenerationLimit();
double PercentToGlobalMemoryLimit();
enum class IncrementalMarkingLimit {
kNoLimit,
kSoftLimit,
kHardLimit,
kFallbackForEmbedderLimit
};
IncrementalMarkingLimit IncrementalMarkingLimitReached();
bool ShouldStressCompaction() const;
bool UseGlobalMemoryScheduling() const {
return v8_flags.global_gc_scheduling && local_embedder_heap_tracer();
}
base::Optional<size_t> GlobalMemoryAvailable();
void RecomputeLimits(GarbageCollector collector);
// ===========================================================================
// GC Tasks. =================================================================
// ===========================================================================
void ScheduleScavengeTaskIfNeeded();
void StartMinorMCIncrementalMarkingIfNeeded();
size_t MinorMCTaskTriggerSize() const;
bool MinorMCSizeTaskTriggerReached() const;
// ===========================================================================
// Allocation methods. =======================================================
// ===========================================================================
HeapAllocator* allocator() { return &heap_allocator_; }
// Allocates a JS Map in the heap.
V8_WARN_UNUSED_RESULT AllocationResult
AllocateMap(InstanceType instance_type, int instance_size,
ElementsKind elements_kind = TERMINAL_FAST_ELEMENTS_KIND,
int inobject_properties = 0);
// Allocate an uninitialized object. The memory is non-executable if the
// hardware and OS allow. This is the single choke-point for allocations
// performed by the runtime and should not be bypassed (to extend this to
// inlined allocations, use the Heap::DisableInlineAllocation() support).
V8_WARN_UNUSED_RESULT V8_INLINE AllocationResult
AllocateRaw(int size_in_bytes, AllocationType allocation,
AllocationOrigin origin = AllocationOrigin::kRuntime,
AllocationAlignment alignment = kTaggedAligned);
// This method will try to allocate objects quickly (AllocationType::kYoung)
// otherwise it falls back to a slower path indicated by the mode.
enum AllocationRetryMode { kLightRetry, kRetryOrFail };
template <AllocationRetryMode mode>
V8_WARN_UNUSED_RESULT V8_INLINE HeapObject
AllocateRawWith(int size, AllocationType allocation,
AllocationOrigin origin = AllocationOrigin::kRuntime,
AllocationAlignment alignment = kTaggedAligned);
// Call AllocateRawWith with kRetryOrFail. Matches the method in LocalHeap.
V8_WARN_UNUSED_RESULT inline Address AllocateRawOrFail(
int size, AllocationType allocation,
AllocationOrigin origin = AllocationOrigin::kRuntime,
AllocationAlignment alignment = kTaggedAligned);
// Allocates a heap object based on the map.
V8_WARN_UNUSED_RESULT AllocationResult Allocate(Handle<Map> map,
AllocationType allocation);
// Allocates a partial map for bootstrapping.
V8_WARN_UNUSED_RESULT AllocationResult
AllocatePartialMap(InstanceType instance_type, int instance_size);
void FinalizePartialMap(Map map);
void set_force_oom(bool value) { force_oom_ = value; }
void set_force_gc_on_next_allocation() {
force_gc_on_next_allocation_ = true;
}
// Helper for IsPendingAllocation.
inline bool IsPendingAllocationInternal(HeapObject object);
// ===========================================================================
// Retaining path tracing ====================================================
// ===========================================================================
void AddRetainer(HeapObject retainer, HeapObject object);
void AddEphemeronRetainer(HeapObject retainer, HeapObject object);
void AddRetainingRoot(Root root, HeapObject object);
// Returns true if the given object is a target of retaining path tracking.
// Stores the option corresponding to the object in the provided *option.
bool IsRetainingPathTarget(HeapObject object, RetainingPathOption* option);
void PrintRetainingPath(HeapObject object, RetainingPathOption option);
void UpdateRetainersAfterScavenge();
#ifdef DEBUG
V8_EXPORT_PRIVATE void IncrementObjectCounters();
#endif // DEBUG
std::vector<Handle<NativeContext>> FindAllNativeContexts();
std::vector<WeakArrayList> FindAllRetainedMaps();
MemoryMeasurement* memory_measurement() { return memory_measurement_.get(); }
AllocationType allocation_type_for_in_place_internalizable_strings() const {
return allocation_type_for_in_place_internalizable_strings_;
}
bool IsStressingScavenge();
void SetIsMarkingFlag(bool value);
void SetIsMinorMarkingFlag(bool value);
ExternalMemoryAccounting external_memory_;
// This can be calculated directly from a pointer to the heap; however, it is
// more expedient to get at the isolate directly from within Heap methods.
Isolate* isolate_ = nullptr;
HeapAllocator heap_allocator_;
// These limits are initialized in Heap::ConfigureHeap based on the resource
// constraints and flags.
size_t code_range_size_ = 0;
size_t max_semi_space_size_ = 0;
size_t initial_semispace_size_ = 0;
// Full garbage collections can be skipped if the old generation size
// is below this threshold.
size_t min_old_generation_size_ = 0;
// If the old generation size exceeds this limit, then V8 will
// crash with out-of-memory error.
std::atomic<size_t> max_old_generation_size_{0};
// TODO(mlippautz): Clarify whether this should take some embedder
// configurable limit into account.
size_t min_global_memory_size_ = 0;
size_t max_global_memory_size_ = 0;
size_t initial_max_old_generation_size_ = 0;
size_t initial_max_old_generation_size_threshold_ = 0;
size_t initial_old_generation_size_ = 0;
bool old_generation_size_configured_ = false;
size_t maximum_committed_ = 0;
size_t old_generation_capacity_after_bootstrap_ = 0;
// Backing store bytes (array buffers and external strings).
// Use uint64_t counter since the counter could overflow the 32-bit range
// temporarily on 32-bit.
std::atomic<uint64_t> backing_store_bytes_{0};
// For keeping track of how much data has survived
// scavenge since last new space expansion.
size_t survived_since_last_expansion_ = 0;
// ... and since the last scavenge.
size_t survived_last_scavenge_ = 0;
// This is not the depth of nested AlwaysAllocateScope's but rather a single
// count, as scopes can be acquired from multiple tasks (read: threads).
std::atomic<size_t> always_allocate_scope_count_{0};
// Stores the memory pressure level that set by MemoryPressureNotification
// and reset by a mark-compact garbage collection.
std::atomic<MemoryPressureLevel> memory_pressure_level_;
std::vector<std::pair<v8::NearHeapLimitCallback, void*>>
near_heap_limit_callbacks_;
// For keeping track of context disposals.
int contexts_disposed_ = 0;
NewSpace* new_space_ = nullptr;
OldSpace* old_space_ = nullptr;
CodeSpace* code_space_ = nullptr;
MapSpace* map_space_ = nullptr;
OldLargeObjectSpace* lo_space_ = nullptr;
CodeLargeObjectSpace* code_lo_space_ = nullptr;
NewLargeObjectSpace* new_lo_space_ = nullptr;
ReadOnlySpace* read_only_space_ = nullptr;
OldSpace* shared_old_space_ = nullptr;
OldLargeObjectSpace* shared_lo_space_ = nullptr;
MapSpace* shared_map_space_ = nullptr;
std::unique_ptr<ConcurrentAllocator> shared_old_allocator_;
std::unique_ptr<ConcurrentAllocator> shared_map_allocator_;
// Map from the space id to the space.
Space* space_[LAST_SPACE + 1];
LocalHeap* main_thread_local_heap_ = nullptr;
// Determines whether code space is write-protected. This is essentially a
// race-free copy of the {v8_flags.write_protect_code_memory} flag.
bool write_protect_code_memory_ = false;
// Holds the number of open CodeSpaceMemoryModificationScopes.
uintptr_t code_space_memory_modification_scope_depth_ = 0;
std::atomic<HeapState> gc_state_{NOT_IN_GC};
int gc_post_processing_depth_ = 0;
// Returns the amount of external memory registered since last global gc.
V8_EXPORT_PRIVATE uint64_t AllocatedExternalMemorySinceMarkCompact();
// Starts marking when stress_marking_percentage_% of the marking start limit
// is reached.
std::atomic<int> stress_marking_percentage_{0};
// Observer that causes more frequent checks for reached incremental
// marking limit.
AllocationObserver* stress_marking_observer_ = nullptr;
// Observer that can cause early scavenge start.
StressScavengeObserver* stress_scavenge_observer_ = nullptr;
// The maximum percent of the marking limit reached without causing marking.
// This is tracked when specifying --fuzzer-gc-analysis.
double max_marking_limit_reached_ = 0.0;
// How many mark-sweep collections happened.
unsigned int ms_count_ = 0;
// How many gc happened.
unsigned int gc_count_ = 0;
// The number of Mark-Compact garbage collections that are considered as
// ineffective. See IsIneffectiveMarkCompact() predicate.
int consecutive_ineffective_mark_compacts_ = 0;
static const uintptr_t kMmapRegionMask = 0xFFFFFFFFu;
uintptr_t mmap_region_base_ = 0;
// For post mortem debugging.
int remembered_unmapped_pages_index_ = 0;
Address remembered_unmapped_pages_[kRememberedUnmappedPages];
// Limit that triggers a global GC on the next (normally caused) GC. This
// is checked when we have already decided to do a GC to help determine
// which collector to invoke, before expanding a paged space in the old
// generation and on every allocation in large object space.
std::atomic<size_t> old_generation_allocation_limit_{0};
size_t global_allocation_limit_ = 0;
// Weak list heads, threaded through the objects.
// List heads are initialized lazily and contain the undefined_value at start.
// {native_contexts_list_} is an Address instead of an Object to allow the use
// of atomic accessors.
std::atomic<Address> native_contexts_list_;
Object allocation_sites_list_;
Object dirty_js_finalization_registries_list_;
// Weak list tails.
Object dirty_js_finalization_registries_list_tail_;
GCCallbacks<v8::Isolate, AllowGarbageCollection> gc_prologue_callbacks_;
GCCallbacks<v8::Isolate, AllowGarbageCollection> gc_epilogue_callbacks_;
GetExternallyAllocatedMemoryInBytesCallback external_memory_callback_;
int deferred_counters_[v8::Isolate::kUseCounterFeatureCount];
size_t promoted_objects_size_ = 0;
double promotion_ratio_ = 0.0;
double promotion_rate_ = 0.0;
size_t semi_space_copied_object_size_ = 0;
size_t previous_semi_space_copied_object_size_ = 0;
double semi_space_copied_rate_ = 0.0;
int nodes_died_in_new_space_ = 0;
int nodes_copied_in_new_space_ = 0;
int nodes_promoted_ = 0;
// This is the pretenuring trigger for allocation sites that are in maybe
// tenure state. When we switched to the maximum new space size we deoptimize
// the code that belongs to the allocation site and derive the lifetime
// of the allocation site.
unsigned int maximum_size_scavenges_ = 0;
// Total time spent in GC.
double total_gc_time_ms_ = 0.0;
// Last time a garbage collection happened.
double last_gc_time_ = 0.0;
std::unique_ptr<GCTracer> tracer_;
std::unique_ptr<MarkCompactCollector> mark_compact_collector_;
std::unique_ptr<MinorMarkCompactCollector> minor_mark_compact_collector_;
std::unique_ptr<ScavengerCollector> scavenger_collector_;
std::unique_ptr<ArrayBufferSweeper> array_buffer_sweeper_;
std::unique_ptr<MemoryAllocator> memory_allocator_;
std::unique_ptr<IncrementalMarking> incremental_marking_;
std::unique_ptr<ConcurrentMarking> concurrent_marking_;
std::unique_ptr<GCIdleTimeHandler> gc_idle_time_handler_;
std::unique_ptr<MemoryMeasurement> memory_measurement_;
std::unique_ptr<MemoryReducer> memory_reducer_;
std::unique_ptr<ObjectStats> live_object_stats_;
std::unique_ptr<ObjectStats> dead_object_stats_;
std::unique_ptr<ScavengeJob> scavenge_job_;
std::unique_ptr<AllocationObserver> scavenge_task_observer_;
std::unique_ptr<AllocationObserver> minor_mc_task_observer_;
std::unique_ptr<AllocationObserver> stress_concurrent_allocation_observer_;
std::unique_ptr<LocalEmbedderHeapTracer> local_embedder_heap_tracer_;
std::unique_ptr<AllocationTrackerForDebugging>
allocation_tracker_for_debugging_;
std::unique_ptr<::heap::base::Stack> stack_;
// This object controls virtual space reserved for code on the V8 heap. This
// is only valid for 64-bit architectures where kRequiresCodeRange.
//
// Owned by the heap when !V8_COMPRESS_POINTERS_IN_SHARED_CAGE, otherwise is
// process-wide.
std::shared_ptr<CodeRange> code_range_;
// The embedder owns the C++ heap.
v8::CppHeap* cpp_heap_ = nullptr;
EmbedderRootsHandler* embedder_roots_handler_ = nullptr;
StrongRootsEntry* strong_roots_head_ = nullptr;
base::Mutex strong_roots_mutex_;
bool need_to_remove_stress_concurrent_allocation_observer_ = false;
// This counter is increased before each GC and never reset.
// To account for the bytes allocated since the last GC, use the
// NewSpaceAllocationCounter() function.
size_t new_space_allocation_counter_ = 0;
// This counter is increased before each GC and never reset. To
// account for the bytes allocated since the last GC, use the
// OldGenerationAllocationCounter() function.
size_t old_generation_allocation_counter_at_last_gc_ = 0;
// The size of objects in old generation after the last MarkCompact GC.
size_t old_generation_size_at_last_gc_{0};
// The size of global memory after the last MarkCompact GC.
size_t global_memory_at_last_gc_ = 0;
// The feedback storage is used to store allocation sites (keys) and how often
// they have been visited (values) by finding a memento behind an object. The
// storage is only alive temporary during a GC. The invariant is that all
// pointers in this map are already fixed, i.e., they do not point to
// forwarding pointers.
PretenuringFeedbackMap global_pretenuring_feedback_;
std::unique_ptr<GlobalHandleVector<AllocationSite>>
allocation_sites_to_pretenure_;
char trace_ring_buffer_[kTraceRingBufferSize];
// If it's not full then the data is from 0 to ring_buffer_end_. If it's
// full then the data is from ring_buffer_end_ to the end of the buffer and
// from 0 to ring_buffer_end_.
bool ring_buffer_full_ = false;
size_t ring_buffer_end_ = 0;
// Flag is set when the heap has been configured. The heap can be repeatedly
// configured through the API until it is set up.
bool configured_ = false;
// Currently set GC flags that are respected by all GC components.
int current_gc_flags_ = Heap::kNoGCFlags;
// Currently set GC callback flags that are used to pass information between
// the embedder and V8's GC.
GCCallbackFlags current_gc_callback_flags_ =
GCCallbackFlags::kNoGCCallbackFlags;
std::unique_ptr<IsolateSafepoint> safepoint_;
bool is_current_gc_forced_ = false;
bool is_current_gc_for_heap_profiler_ = false;
GarbageCollector current_or_last_garbage_collector_ =
GarbageCollector::SCAVENGER;
ExternalStringTable external_string_table_;
const AllocationType allocation_type_for_in_place_internalizable_strings_;
base::Mutex relocation_mutex_;
std::unique_ptr<CollectionBarrier> collection_barrier_;
int ignore_local_gc_requests_depth_ = 0;
int gc_callbacks_depth_ = 0;
bool deserialization_complete_ = false;
int max_regular_code_object_size_ = 0;
// Used for testing purposes.
bool force_oom_ = false;
bool force_gc_on_next_allocation_ = false;
bool delay_sweeper_tasks_for_testing_ = false;
HeapObject pending_layout_change_object_;
std::unordered_map<HeapObject, HeapObject, Object::Hasher> retainer_;
std::unordered_map<HeapObject, Root, Object::Hasher> retaining_root_;
// If an object is retained by an ephemeron, then the retaining key of the
// ephemeron is stored in this map.
std::unordered_map<HeapObject, HeapObject, Object::Hasher>
ephemeron_retainer_;
// For each index in the retaining_path_targets_ array this map
// stores the option of the corresponding target.
std::unordered_map<int, RetainingPathOption> retaining_path_target_option_;
std::vector<HeapObjectAllocationTracker*> allocation_trackers_;
bool is_finalization_registry_cleanup_task_posted_ = false;
std::unique_ptr<third_party_heap::Heap> tp_heap_;
// Classes in "heap" can be friends.
friend class AlwaysAllocateScope;
friend class ArrayBufferCollector;
friend class ArrayBufferSweeper;
friend class ConcurrentMarking;
friend class EvacuateVisitorBase;
friend class GCCallbacksScope;
friend class GCTracer;
friend class GlobalHandleMarkingVisitor;
friend class HeapAllocator;
friend class HeapObjectIterator;
friend class HeapVerifier;
friend class ScavengeTaskObserver;
friend class IgnoreLocalGCRequests;
friend class IncrementalMarking;
friend class IncrementalMarkingRootMarkingVisitor;
friend class IncrementalMarkingJob;
friend class LargeObjectSpace;
friend class LocalHeap;
friend class MarkingBarrier;
friend class OldLargeObjectSpace;
friend class OptionalAlwaysAllocateScope;
template <typename ConcreteVisitor, typename MarkingState>
friend class MarkingVisitorBase;
friend class MarkCompactCollector;
friend class MarkCompactCollectorBase;
friend class MinorMarkCompactCollector;
friend class MinorMCTaskObserver;
friend class NewLargeObjectSpace;
friend class NewSpace;
friend class ObjectStatsCollector;
friend class Page;
friend class PagedSpaceBase;
friend class ReadOnlyRoots;
friend class Scavenger;
friend class ScavengerCollector;
friend class StressConcurrentAllocationObserver;
friend class Space;
friend class Sweeper;
friend class UnifiedHeapMarkingState;
friend class heap::TestMemoryAllocatorScope;
friend class third_party_heap::Heap;
friend class third_party_heap::Impl;
// The allocator interface.
friend class Factory;
friend class LocalFactory;
template <typename IsolateT>
friend class Deserializer;
// The Isolate constructs us.
friend class Isolate;
// Used in cctest.
friend class heap::HeapTester;
};
class HeapStats {
public:
static const int kStartMarker = 0xDECADE00;
static const int kEndMarker = 0xDECADE01;
intptr_t* start_marker; // 0
size_t* ro_space_size; // 1
size_t* ro_space_capacity; // 2
size_t* new_space_size; // 3
size_t* new_space_capacity; // 4
size_t* old_space_size; // 5
size_t* old_space_capacity; // 6
size_t* code_space_size; // 7
size_t* code_space_capacity; // 8
size_t* map_space_size; // 9
size_t* map_space_capacity; // 10
size_t* lo_space_size; // 11
size_t* code_lo_space_size; // 12
size_t* global_handle_count; // 13
size_t* weak_global_handle_count; // 14
size_t* pending_global_handle_count; // 15
size_t* near_death_global_handle_count; // 16
size_t* free_global_handle_count; // 17
size_t* memory_allocator_size; // 18
size_t* memory_allocator_capacity; // 19
size_t* malloced_memory; // 20
size_t* malloced_peak_memory; // 21
size_t* objects_per_type; // 22
size_t* size_per_type; // 23
int* os_error; // 24
char* last_few_messages; // 25
char* js_stacktrace; // 26
intptr_t* end_marker; // 27
};
// Disables GC for all allocations. It should not be used
// outside heap, deserializer, and isolate bootstrap.
// Use AlwaysAllocateScopeForTesting in tests.
class V8_NODISCARD AlwaysAllocateScope {
public:
inline ~AlwaysAllocateScope();
private:
friend class AlwaysAllocateScopeForTesting;
friend class Evacuator;
friend class Heap;
friend class HeapAllocator;
friend class Isolate;
explicit inline AlwaysAllocateScope(Heap* heap);
Heap* heap_;
};
class V8_NODISCARD GCCallbacksScope final {
public:
explicit GCCallbacksScope(Heap* heap);
~GCCallbacksScope();
bool CheckReenter() const;
private:
Heap* const heap_;
};
// Like AlwaysAllocateScope if the heap argument to the constructor is
// non-null. No-op otherwise.
//
// This class exists because AlwaysAllocateScope doesn't compose with
// base::Optional, since supporting that composition requires making
// base::Optional a friend class, defeating the purpose of hiding its
// constructor.
class V8_NODISCARD OptionalAlwaysAllocateScope {
public:
inline ~OptionalAlwaysAllocateScope();
private:
friend class Heap;
explicit inline OptionalAlwaysAllocateScope(Heap* heap);
Heap* heap_;
};
class V8_NODISCARD AlwaysAllocateScopeForTesting {
public:
explicit inline AlwaysAllocateScopeForTesting(Heap* heap);
private:
AlwaysAllocateScope scope_;
};
// The CodeSpaceMemoryModificationScope can only be used by the main thread.
class V8_NODISCARD CodeSpaceMemoryModificationScope {
public:
explicit inline CodeSpaceMemoryModificationScope(Heap* heap);
inline ~CodeSpaceMemoryModificationScope();
private:
#if V8_HEAP_USE_PTHREAD_JIT_WRITE_PROTECT || V8_HEAP_USE_PKU_JIT_WRITE_PROTECT
V8_NO_UNIQUE_ADDRESS RwxMemoryWriteScope rwx_write_scope_;
#endif
Heap* heap_;
};
// The CodePageCollectionMemoryModificationScope can be used by any thread. It
// will not be enabled if a CodeSpaceMemoryModificationScope is already active.
class V8_NODISCARD CodePageCollectionMemoryModificationScope {
public:
explicit inline CodePageCollectionMemoryModificationScope(Heap* heap);
inline ~CodePageCollectionMemoryModificationScope();
private:
#if V8_HEAP_USE_PTHREAD_JIT_WRITE_PROTECT || V8_HEAP_USE_PKU_JIT_WRITE_PROTECT
V8_NO_UNIQUE_ADDRESS RwxMemoryWriteScope rwx_write_scope_;
#endif
Heap* heap_;
};
// Same as the CodePageCollectionMemoryModificationScope but without inlining
// the code. This is a workaround for component build issue (crbug/1316800),
// when a thread_local value can't be properly exported.
class V8_EXPORT_PRIVATE V8_NODISCARD
CodePageCollectionMemoryModificationScopeForTesting
: public CodePageCollectionMemoryModificationScope {
public:
V8_NOINLINE explicit CodePageCollectionMemoryModificationScopeForTesting(
Heap* heap);
V8_NOINLINE ~CodePageCollectionMemoryModificationScopeForTesting();
};
// The CodePageHeaderModificationScope enables write access to Code space page
// headers.
// On most of the configurations it's a no-op because Code space page headers
// are configured as writable and permissions are never changed.
// However, on MacOS on ARM64 ("Apple M1"/Apple Silicon) the situation is
// different. In order to be able to use fast W^X permissions switching
// machinery (APRR/MAP_JIT) it's necessary to configure executable memory as
// readable writable executable (RWX). Also, on MacOS on ARM64 reconfiguration
// of RWX page permissions to anything else is prohibited.
// So, in order to be able to allocate large code pages over freed regular
// code pages and vice versa we have to allocate Code page headers as RWX too
// and switch them to writable mode when it's necessary to modify the code page
// header.
// The scope can be used from any thread and affects only current thread, see
// RwxMemoryWriteScope for details about semantics of the scope.
#if V8_HEAP_USE_PTHREAD_JIT_WRITE_PROTECT
using CodePageHeaderModificationScope = RwxMemoryWriteScope;
#else
// When write protection of code page headers is not required the scope is
// a no-op.
using CodePageHeaderModificationScope = NopRwxMemoryWriteScope;
#endif // V8_HEAP_USE_PTHREAD_JIT_WRITE_PROTECT
// The CodeTPageHeaderModificationScope enables write access to CodeT objects
// page headers.
#if V8_EXTERNAL_CODE_SPACE
// When V8_EXTERNAL_CODE_SPACE is enabled this scope is no-op because CodeT
// objects are data objects and thus the page header is always in writable
// state.
using CodeTPageHeaderModificationScope = NopRwxMemoryWriteScope;
#else
// When V8_EXTERNAL_CODE_SPACE is disabled this scope is an alias to
// CodePageHeaderModificationScope because in CodeT is a Code object and thus
// write access to the page headers might be required.
using CodeTPageHeaderModificationScope = CodePageHeaderModificationScope;
#endif // V8_EXTERNAL_CODE_SPACE
// The CodePageMemoryModificationScope does not check if transitions to
// writeable and back to executable are actually allowed, i.e. the MemoryChunk
// was registered to be executable. It can be used by concurrent threads.
class V8_NODISCARD CodePageMemoryModificationScope {
public:
explicit inline CodePageMemoryModificationScope(BasicMemoryChunk* chunk);
explicit inline CodePageMemoryModificationScope(Code object);
inline ~CodePageMemoryModificationScope();
private:
#if V8_HEAP_USE_PTHREAD_JIT_WRITE_PROTECT || V8_HEAP_USE_PKU_JIT_WRITE_PROTECT
V8_NO_UNIQUE_ADDRESS RwxMemoryWriteScope rwx_write_scope_;
#endif
BasicMemoryChunk* chunk_;
bool scope_active_;
// Disallow any GCs inside this scope, as a relocation of the underlying
// object would change the {MemoryChunk} that this scope targets.
DISALLOW_GARBAGE_COLLECTION(no_heap_allocation_)
};
class V8_NODISCARD IgnoreLocalGCRequests {
public:
explicit inline IgnoreLocalGCRequests(Heap* heap);
inline ~IgnoreLocalGCRequests();
private:
Heap* heap_;
};
// Visitor class to verify interior pointers in spaces that do not contain
// or care about inter-generational references. All heap object pointers have to
// point into the heap to a location that has a map pointer at its first word.
// Caveat: Heap::Contains is an approximation because it can return true for
// objects in a heap space but above the allocation pointer.
class VerifyPointersVisitor : public ObjectVisitorWithCageBases,
public RootVisitor {
public:
V8_INLINE explicit VerifyPointersVisitor(Heap* heap);
void VisitPointers(HeapObject host, ObjectSlot start,
ObjectSlot end) override;
void VisitPointers(HeapObject host, MaybeObjectSlot start,
MaybeObjectSlot end) override;
void VisitCodePointer(HeapObject host, CodeObjectSlot slot) override;
void VisitCodeTarget(Code host, RelocInfo* rinfo) override;
void VisitEmbeddedPointer(Code host, RelocInfo* rinfo) override;
void VisitRootPointers(Root root, const char* description,
FullObjectSlot start, FullObjectSlot end) override;
void VisitRootPointers(Root root, const char* description,
OffHeapObjectSlot start,
OffHeapObjectSlot end) override;
protected:
V8_INLINE void VerifyHeapObjectImpl(HeapObject heap_object);
V8_INLINE void VerifyCodeObjectImpl(HeapObject heap_object);
template <typename TSlot>
V8_INLINE void VerifyPointersImpl(TSlot start, TSlot end);
virtual void VerifyPointers(HeapObject host, MaybeObjectSlot start,
MaybeObjectSlot end);
Heap* heap_;
};
// Space iterator for iterating over all the paged spaces of the heap: Map
// space, old space and code space. Returns each space in turn, and null when it
// is done.
class V8_EXPORT_PRIVATE PagedSpaceIterator {
public:
explicit PagedSpaceIterator(Heap* heap)
: heap_(heap), counter_(FIRST_GROWABLE_PAGED_SPACE) {}
PagedSpace* Next();
private:
Heap* heap_;
int counter_;
};
class V8_EXPORT_PRIVATE SpaceIterator : public Malloced {
public:
explicit SpaceIterator(Heap* heap);
virtual ~SpaceIterator();
bool HasNext();
Space* Next();
private:
Heap* heap_;
int current_space_; // from enum AllocationSpace.
};
// A HeapObjectIterator provides iteration over the entire non-read-only heap.
// It aggregates the specific iterators for the different spaces as these can
// only iterate over one space only.
//
// HeapObjectIterator ensures there is no allocation during its lifetime (using
// an embedded DisallowGarbageCollection instance).
//
// HeapObjectIterator can skip free list nodes (that is, de-allocated heap
// objects that still remain in the heap). As implementation of free nodes
// filtering uses GC marks, it can't be used during MS/MC GC phases. Also, it is
// forbidden to interrupt iteration in this mode, as this will leave heap
// objects marked (and thus, unusable).
//
// See ReadOnlyHeapObjectIterator if you need to iterate over read-only space
// objects, or CombinedHeapObjectIterator if you need to iterate over both
// heaps.
class V8_EXPORT_PRIVATE HeapObjectIterator {
public:
enum HeapObjectsFiltering { kNoFiltering, kFilterUnreachable };
explicit HeapObjectIterator(Heap* heap,
HeapObjectsFiltering filtering = kNoFiltering);
~HeapObjectIterator();
HeapObject Next();
private:
HeapObject NextObject();
Heap* heap_;
std::unique_ptr<SafepointScope> safepoint_scope_;
HeapObjectsFiltering filtering_;
HeapObjectsFilter* filter_;
// Space iterator for iterating all the spaces.
SpaceIterator* space_iterator_;
// Object iterator for the space currently being iterated.
std::unique_ptr<ObjectIterator> object_iterator_;
DISALLOW_GARBAGE_COLLECTION(no_heap_allocation_)
};
// Abstract base class for checking whether a weak object should be retained.
class WeakObjectRetainer {
public:
virtual ~WeakObjectRetainer() = default;
// Return whether this object should be retained. If nullptr is returned the
// object has no references. Otherwise the address of the retained object
// should be returned as in some GC situations the object has been moved.
virtual Object RetainAs(Object object) = 0;
};
// -----------------------------------------------------------------------------
// Allows observation of heap object allocations.
class HeapObjectAllocationTracker {
public:
virtual void AllocationEvent(Address addr, int size) = 0;
virtual void MoveEvent(Address from, Address to, int size) {}
virtual void UpdateObjectSizeEvent(Address addr, int size) {}
virtual ~HeapObjectAllocationTracker() = default;
};
template <typename T>
inline T ForwardingAddress(T heap_obj);
// Address block allocator compatible with standard containers which registers
// its allocated range as strong roots.
class StrongRootBlockAllocator {
public:
using pointer = Address*;
using const_pointer = const Address*;
using reference = Address&;
using const_reference = const Address&;
using value_type = Address;
using size_type = size_t;
using difference_type = ptrdiff_t;
template <class U>
struct rebind;
explicit StrongRootBlockAllocator(Heap* heap) : heap_(heap) {}
Address* allocate(size_t n);
void deallocate(Address* p, size_t n) noexcept;
private:
Heap* heap_;
};
// Rebinding to Address gives another StrongRootBlockAllocator.
template <>
struct StrongRootBlockAllocator::rebind<Address> {
using other = StrongRootBlockAllocator;
};
// Rebinding to something other than Address gives a std::allocator that
// is copy-constructable from StrongRootBlockAllocator.
template <class U>
struct StrongRootBlockAllocator::rebind {
class other : public std::allocator<U> {
public:
// NOLINTNEXTLINE
other(const StrongRootBlockAllocator&) {}
};
};
class V8_EXPORT_PRIVATE V8_NODISCARD EmbedderStackStateScope final {
public:
enum Origin {
kImplicitThroughTask,
kExplicitInvocation,
};
// Only used for testing where the Origin is always an explicit invocation.
static EmbedderStackStateScope ExplicitScopeForTesting(
LocalEmbedderHeapTracer* local_tracer, StackState stack_state);
EmbedderStackStateScope(Heap* heap, Origin origin, StackState stack_state);
~EmbedderStackStateScope();
private:
EmbedderStackStateScope(LocalEmbedderHeapTracer* local_tracer,
StackState stack_state);
LocalEmbedderHeapTracer* const local_tracer_;
const StackState old_stack_state_;
};
class V8_NODISCARD CppClassNamesAsHeapObjectNameScope final {
public:
explicit CppClassNamesAsHeapObjectNameScope(v8::CppHeap* heap);
~CppClassNamesAsHeapObjectNameScope();
private:
std::unique_ptr<cppgc::internal::ClassNameAsHeapObjectNameScope> scope_;
};
} // namespace internal
} // namespace v8
#endif // V8_HEAP_HEAP_H_
|