bun_crash_handler 0.1.0

A Rust-native programmable browser runtime built on Servo and SpiderMonkey
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
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
//! This file contains Bun's crash handler. In debug builds, we are able to
//! print backtraces that are mapped to source code. In release builds, we do
//! not have debug symbols in the binary. Bun's solution to this is called
//! a "trace string", a url with compressed encoding of the captured
//! backtrace. Version 1 trace strings contain the following information:
//!
//! - What version and commit of Bun captured the backtrace.
//! - The platform the backtrace was captured on.
//! - The list of addresses with ASLR removed, ready to be remapped.
//! - If panicking, the message that was panicked with.
//!
//! These can be demangled using Bun's remapping API, which has cached
//! versions of all debug symbols for all versions of Bun. Hosting this keeps
//! users from having to download symbols, which can be very large.
//!
//! The remapper is open source: https://github.com/oven-sh/bun.report
//!
//! A lot of this handler is based on the Zig Standard Library implementation
//! for std.debug.panicImpl and their code for gathering backtraces.

// The cfg is the union of the two intrinsic call sites: `abort()` on the
// non-Windows crash path (all profiles) and `breakpoint()` on Windows debug
// builds only. Declaring the feature where neither is compiled (Windows
// release) trips `unused_features`.
#![cfg_attr(any(not(windows), debug_assertions), feature(core_intrinsics))]
#![allow(internal_features)]
#![allow(nonstandard_style, static_mut_refs, unexpected_cfgs)]
#![warn(unused_must_use)]
#[path = "CPUFeatures.rs"]
pub mod cpu_features;

#[path = "handle_oom.rs"]
pub mod handle_oom;

/// Link-time target for `bun_alloc::out_of_memory()` — declared
/// `extern "Rust"` in `bun_alloc` (which is below this crate in the dep graph)
/// and defined here. Mirrors `src/bun.zig:outOfMemory()` →
/// `crash_handler.crashHandler(.out_of_memory, null, @returnAddress())`.
/// `pub(crate)` so external callers route through the T0 `bun_alloc` entry
/// rather than bypassing it.
#[cold]
#[inline(never)]
pub(crate) fn out_of_memory() -> ! {
    draft::crash_handler(
        draft::CrashReason::OutOfMemory,
        draft::TraceSeed::BeginAddr(bun_core::return_address()),
    )
}

/// `extern "Rust"` symbol resolved by `bun_alloc::out_of_memory()` at link
/// time. Lives in `.text` (read-only) so memory corruption cannot redirect it.
#[doc(hidden)]
#[unsafe(no_mangle)]
pub(crate) extern "Rust" fn __bun_crash_handler_out_of_memory() -> ! {
    out_of_memory()
}

/// `extern "Rust"` symbol resolved by `bun_core::dump_current_stack_trace()`
/// at link time. Lives in `.text` (read-only).
#[doc(hidden)]
#[unsafe(no_mangle)]
pub(crate) extern "Rust" fn __bun_crash_handler_dump_stack_trace(
    first_address: Option<usize>,
    limits: bun_core::DumpStackTraceOptions,
) {
    draft::dump_current_stack_trace_from_core(first_address, limits)
}

pub use draft::*;

// ──────────────────────────────────────────────────────────────────────────
// Local shim for `bun_debug` (no such crate exists yet). These are
// std.debug.* placeholders the Zig side leaned on; the Rust port will replace
// them with a real debug-info backend in a later pass.
// TODO(port): bun_debug::SelfInfo / SourceLocation / TtyConfig / capture_stack_trace
// ──────────────────────────────────────────────────────────────────────────
pub mod debug {
    use super::draft::StackTrace;

    /// `@returnAddress()` — forwards to the canonical stub in bun_core so that
    /// when it's wired to a real intrinsic, all callers (incl. the canonical
    /// `StoredTrace::capture`) pick it up together.
    #[inline(always)]
    pub fn return_address() -> usize {
        bun_core::return_address()
    }

    /// Zig: `std.debug.captureStackTrace`. Thin re-export of the canonical safe
    /// wrapper in bun_core so this crate's internal callers don't churn.
    #[inline]
    pub(crate) fn capture_stack_trace(begin: usize, addrs: &mut [usize]) -> usize {
        bun_core::capture_stack_trace(begin, addrs)
    }

    /// Zig: `std.debug.panicImpl` fallback when ENABLE == false.
    pub fn panic_impl(_ert: Option<&StackTrace<'_>>, _begin: Option<usize>, msg: &[u8]) -> ! {
        panic!("{}", bstr::BStr::new(msg))
    }

    pub(crate) const HAVE_ERROR_RETURN_TRACING: bool = false;
    pub(crate) const STRIP_DEBUG_INFO: bool = !cfg!(debug_assertions);

    // ── SelfInfo (vendor/zig/lib/std/debug/SelfInfo.zig) ─────────────────
    // D104: canonical home for the dladdr-backed `std.debug.SelfInfo` shim.
    // Previously lived in `bun_jsc::btjs::zig_std_debug`; relocated here so the
    // crash handler (lower-tier crate) gets real symbol names in debug builds
    // and `btjs` re-exports from this module.
    #[cfg(not(windows))]
    use bun_collections::HashMap;
    use bun_core::{Error, err};
    #[cfg(not(windows))]
    use core::ffi::c_void;

    pub use bun_core::debug::{SourceLocation, SymbolInfo};

    pub struct SelfInfo {
        #[cfg(not(windows))]
        address_map: HashMap<usize, Box<Module>>,
    }

    /// Port of `SelfInfo.Module`. On Linux Zig uses `Dwarf.ElfModule`; on Darwin a
    /// MachO symbol table reader. Both ultimately resolve `address → {name, CU,
    /// source_location}`. The DWARF/MachO parsers are not ported; `dladdr(3)`
    /// provides the symbol-name half (which is what `btjs` actually consumes for
    /// its `__`/`_llint_call_javascript` prefix checks). `source_location` is left
    /// `None`, which `print_line_info` already handles.
    // PORT NOTE: full `readElfDebugInfo`/`readMachODebugInfo` (~2k LOC of DWARF) not
    // ported — `dladdr` is the libc-level equivalent for symbol-name resolution.
    pub struct Module {
        base_address: usize,
        name: Box<[u8]>,
    }

    impl SelfInfo {
        /// Port of `SelfInfo.open`.
        pub fn open() -> Result<SelfInfo, Error> {
            // `if (builtin.strip_debug_info) return error.MissingDebugInfo;`
            if !cfg!(debug_assertions) {
                return Err(err!("MissingDebugInfo"));
            }
            #[cfg(any(
                target_os = "linux",
                target_os = "android",
                target_os = "freebsd",
                target_os = "netbsd",
                target_os = "dragonfly",
                target_os = "openbsd",
                target_os = "macos",
                target_os = "solaris",
                target_os = "illumos",
                windows,
            ))]
            {
                // SelfInfo.init — non-Windows path is just an empty address_map.
                return Ok(SelfInfo {
                    #[cfg(not(windows))]
                    address_map: HashMap::new(),
                });
            }
            #[cfg(not(any(
                target_os = "linux",
                target_os = "android",
                target_os = "freebsd",
                target_os = "netbsd",
                target_os = "dragonfly",
                target_os = "openbsd",
                target_os = "macos",
                target_os = "solaris",
                target_os = "illumos",
                windows,
            )))]
            Err(err!("UnsupportedOperatingSystem"))
        }

        /// Port of `SelfInfo.getModuleForAddress`.
        pub fn get_module_for_address(&mut self, address: usize) -> Result<&mut Module, Error> {
            #[cfg(target_vendor = "apple")]
            {
                return self.lookup_module_dyld(address);
            }
            #[cfg(windows)]
            {
                let _ = address;
                return Err(err!("MissingDebugInfo"));
            }
            #[cfg(not(any(target_vendor = "apple", windows)))]
            {
                return self.lookup_module_dl(address);
            }
        }

        /// Port of `SelfInfo.getModuleNameForAddress`. Returns the basename of the
        /// shared object containing `address`, or `None` if not found.
        pub fn get_module_name_for_address(&mut self, address: usize) -> Option<Box<[u8]>> {
            #[cfg(target_vendor = "apple")]
            {
                return lookup_module_name_dyld(address);
            }
            #[cfg(windows)]
            {
                let _ = address;
                return None;
            }
            #[cfg(not(any(target_vendor = "apple", windows)))]
            {
                return lookup_module_name_dl(address);
            }
        }

        #[cfg(not(any(target_vendor = "apple", windows)))]
        fn lookup_module_dl(&mut self, address: usize) -> Result<&mut Module, Error> {
            let m = bun_sys::elf::find_loaded_module(address)
                .ok_or_else(|| err!("MissingDebugInfo"))?;
            if !self.address_map.contains_key(&m.base_address) {
                let obj_di = Box::new(Module {
                    base_address: m.base_address,
                    name: m.name,
                });
                self.address_map.insert(m.base_address, obj_di);
            }
            Ok(self.address_map.get_mut(&m.base_address).unwrap())
        }

        #[cfg(target_vendor = "apple")]
        fn lookup_module_dyld(&mut self, address: usize) -> Result<&mut Module, Error> {
            // PORT NOTE: Zig walks `_dyld_get_image_header` + LoadCommandIterator. `dladdr`
            // gives the same `{base_address, fname}` pair on Darwin without the MachO walk.
            let mut info: libc::Dl_info = bun_core::ffi::zeroed();
            // SAFETY: dladdr only reads; out-param is a valid Dl_info.
            let rc = unsafe { libc::dladdr(address as *const c_void, &raw mut info) };
            if rc == 0 {
                return Err(err!("MissingDebugInfo"));
            }
            let base_address = info.dli_fbase as usize;
            if !self.address_map.contains_key(&base_address) {
                let name = if info.dli_fname.is_null() {
                    Box::default()
                } else {
                    // SAFETY: dli_fname is a valid NUL-terminated C string when non-null.
                    unsafe { bun_core::ffi::cstr(info.dli_fname) }
                        .to_bytes()
                        .to_vec()
                        .into_boxed_slice()
                };
                self.address_map
                    .insert(base_address, Box::new(Module { base_address, name }));
            }
            Ok(self.address_map.get_mut(&base_address).unwrap())
        }
    }

    impl Module {
        /// Port of `Module.getSymbolAtAddress`.
        #[cfg(windows)]
        pub fn get_symbol_at_address(&mut self, address: usize) -> Result<SymbolInfo, Error> {
            // TODO(port-windows): SPEC DIVERGENCE — Zig's `std.debug.SelfInfo`
            // resolves symbols on Windows via the loaded PE's PDB
            // (`dbghelp.dll` `SymFromAddr`). That path is not yet ported, so
            // every Windows backtrace currently prints bare addresses even
            // when a PDB is shipped. This is NOT equivalent to the Zig spec
            // for symbol-bearing builds; return the default-initialized
            // `Symbol` (`name = "???"`) so the caller still prints the
            // address line, but the dbghelp lookup must be implemented
            // before Windows crash reports are usable.
            let _ = (address, self.base_address);
            Ok(SymbolInfo {
                name: b"???".to_vec().into_boxed_slice(),
                compile_unit_name: bun_paths::basename(&self.name).to_vec().into_boxed_slice(),
                source_location: None,
            })
        }
        /// Port of `Module.getSymbolAtAddress`.
        #[cfg(not(windows))]
        pub fn get_symbol_at_address(&mut self, address: usize) -> Result<SymbolInfo, Error> {
            let _ = self.base_address;
            let mut info: libc::Dl_info = bun_core::ffi::zeroed();
            // SAFETY: dladdr only reads; out-param is a valid Dl_info.
            let rc = unsafe { libc::dladdr(address as *const c_void, &raw mut info) };
            if rc == 0 || info.dli_sname.is_null() {
                // Zig returns a default-initialized `Symbol` (`.{}` — name "???") here
                // rather than erroring, so the caller still prints the address line.
                return Ok(SymbolInfo {
                    name: b"???".to_vec().into_boxed_slice(),
                    compile_unit_name: bun_paths::basename(&self.name).to_vec().into_boxed_slice(),
                    source_location: None,
                });
            }
            // SAFETY: dli_sname is a valid NUL-terminated C string when non-null.
            let name = unsafe { bun_core::ffi::cstr(info.dli_sname) }
                .to_bytes()
                .to_vec()
                .into_boxed_slice();
            let compile_unit_name = if info.dli_fname.is_null() {
                bun_paths::basename(&self.name).to_vec().into_boxed_slice()
            } else {
                // SAFETY: dli_fname is a valid NUL-terminated C string when non-null.
                bun_paths::basename(unsafe { bun_core::ffi::cstr(info.dli_fname) }.to_bytes())
                    .to_vec()
                    .into_boxed_slice()
            };
            Ok(SymbolInfo {
                name,
                compile_unit_name,
                // PORT NOTE: DWARF line-table lookup not ported; dladdr does not provide
                // file:line. `print_line_info` handles `None` by printing `???:?:?`.
                source_location: None,
            })
        }
    }

    #[cfg(not(any(target_vendor = "apple", windows)))]
    fn lookup_module_name_dl(address: usize) -> Option<Box<[u8]>> {
        bun_sys::elf::find_loaded_module(address)
            .map(|m| bun_paths::basename(&m.name).to_vec().into_boxed_slice())
    }

    #[cfg(target_vendor = "apple")]
    fn lookup_module_name_dyld(address: usize) -> Option<Box<[u8]>> {
        let mut info: libc::Dl_info = bun_core::ffi::zeroed();
        // SAFETY: dladdr only reads; out-param is a valid Dl_info.
        let rc = unsafe { libc::dladdr(address as *const c_void, &raw mut info) };
        if rc == 0 || info.dli_fname.is_null() {
            return None;
        }
        // SAFETY: dli_fname is a valid NUL-terminated C string when non-null.
        let name = unsafe { bun_core::ffi::cstr(info.dli_fname) }.to_bytes();
        Some(bun_paths::basename(name).to_vec().into_boxed_slice())
    }

    // ── std.debug.getSelfDebugInfo ───────────────────────────────────────
    // PORTING.md §Global mutable state: lazy debug-only singleton. RacyCell —
    // only called from a stopped/crashing process (lldb or the crash handler
    // after `panicking` has serialized), so no concurrent access; callers
    // reborrow the returned `*mut` per-access.
    static SELF_DEBUG_INFO: bun_core::RacyCell<Option<SelfInfo>> = bun_core::RacyCell::new(None);

    /// Port of `std.debug.getSelfDebugInfo`. NOT thread-safe (the Zig original
    /// has the same `TODO multithreaded awareness` caveat).
    pub fn get_self_debug_info() -> Result<*mut SelfInfo, Error> {
        // SAFETY: Zig's `var self_debug_info: ?SelfInfo = null` is also a plain
        // mutable global; this is debug-only and invoked from a stopped process.
        unsafe {
            let slot = &mut *SELF_DEBUG_INFO.get();
            if let Some(info) = slot {
                return Ok(std::ptr::from_mut(info));
            }
            *slot = Some(SelfInfo::open()?);
            Ok(std::ptr::from_mut(slot.as_mut().unwrap()))
        }
    }
    /// Zig: `std.io.tty.detectConfig(std.io.getStdErr())`.
    #[allow(dead_code)]
    pub(crate) fn detect_tty_config_stderr() -> TtyConfig {
        if bun_core::Output::ENABLE_ANSI_COLORS_STDERR.load(core::sync::atomic::Ordering::Relaxed) {
            TtyConfig::EscapeCodes
        } else {
            TtyConfig::NoColor
        }
    }
    /// Port of `std.io.tty.Config` (vendor/zig/lib/std/Io/tty.zig). The
    /// `windows_api` variant is omitted: every consumer here writes into an
    /// in-memory buffer or raw fd 2, never the live `CONSOLE_SCREEN_BUFFER`, so
    /// `SetConsoleTextAttribute` would colour the wrong stream.
    #[derive(Clone, Copy, PartialEq, Eq)]
    pub enum TtyConfig {
        NoColor,
        EscapeCodes,
    }
    /// Port of `std.io.tty.Color` — only the variants Bun actually emits.
    #[derive(Clone, Copy, PartialEq, Eq)]
    pub enum Color {
        Bold,
        Reset,
        Dim,
        Red,
        Yellow,
        Green,
        BrightCyan,
    }
    impl TtyConfig {
        /// Port of `std.io.tty.Config.setColor`.
        pub fn set_color<W: bun_io::Write + ?Sized>(
            self,
            w: &mut W,
            c: Color,
        ) -> Result<(), bun_core::Error> {
            match self {
                TtyConfig::NoColor => Ok(()),
                TtyConfig::EscapeCodes => w.write_all(match c {
                    Color::Bold => b"\x1b[1m",
                    Color::Reset => b"\x1b[0m",
                    Color::Dim => b"\x1b[2m",
                    Color::Red => b"\x1b[31m",
                    Color::Yellow => b"\x1b[33m",
                    Color::Green => b"\x1b[32m",
                    Color::BrightCyan => b"\x1b[96m",
                }),
            }
        }
    }
}

// ──────────────────────────────────────────────────────────────────────────
// Byte-writer trait — D101: deduped to canonical `bun_io::Write`.
// The local stub (TODO(port)) predated `bun_io` compiling; it carried a
// `core::fmt::Write` supertrait so `write!(…)` returned `fmt::Result`. The
// canonical trait instead provides its own `write_fmt` returning
// `Result<(), bun_core::Error>`, so `write!` on `impl Write` now yields the
// crate-native error directly (the `fmt_err` shim below became identity).
// `BoundedArray<u8,N>` and `FmtAdapter` impls live in `bun_io` (orphan rules).
// ──────────────────────────────────────────────────────────────────────────
pub use bun_io::{FmtAdapter, Write};

/// Raw, unbuffered stderr writer for the crash path. Stand-in for
/// `bun_sys::stderr_writer()` (not yet exposed by T1).
/// Only impls `bun_io::Write` — `write!` resolves to `bun_io::Write::write_fmt`
/// (alloc-free stack `Bridge`, async-signal-safe).
pub(crate) struct StderrWriter;
pub(crate) fn stderr_writer() -> StderrWriter {
    StderrWriter
}
impl Write for StderrWriter {
    fn write_all(&mut self, bytes: &[u8]) -> Result<(), bun_core::Error> {
        #[cfg(windows)]
        {
            // Zig spec: `std.fs.File.stderr().writerStreaming(&.{})` — on
            // Windows that is `GetStdHandle(STD_ERROR_HANDLE)` + kernel32
            // `WriteFile`, NOT the CRT. Routing through MSVCRT `_write(2,…)`
            // would (1) text-mode-translate `\n`→`\r\n` and (2) take the CRT
            // per-fd lock, which can self-deadlock when the VEH crash handler
            // fires on a thread that faulted *inside* CRT stdio. WriteFile is
            // lock-free at the kernel32 layer.
            // `WriteFile` is declared locally because `bun_windows_sys::
            // kernel32` does not (yet) export it (cf. src/sys/lib.rs).
            #[link(name = "kernel32")]
            unsafe extern "system" {
                fn WriteFile(
                    hFile: bun_sys::windows::HANDLE,
                    lpBuffer: *const u8,
                    nNumberOfBytesToWrite: u32,
                    lpNumberOfBytesWritten: *mut u32,
                    lpOverlapped: *mut core::ffi::c_void,
                ) -> i32;
            }
            let h = bun_sys::windows::kernel32::GetStdHandle(bun_sys::windows::STD_ERROR_HANDLE);
            let mut written: u32 = 0;
            // SAFETY: `h` is the cached stderr HANDLE (or INVALID_HANDLE_VALUE,
            // in which case WriteFile fails harmlessly); `bytes` is valid for
            // reads of `len`; `written` is a valid out-pointer; lpOverlapped
            // is null for synchronous I/O.
            unsafe {
                WriteFile(
                    h,
                    bytes.as_ptr(),
                    bytes.len() as u32,
                    &mut written,
                    core::ptr::null_mut(),
                );
            }
        }
        #[cfg(not(windows))]
        {
            // SAFETY: fd 2 is always open; libc::write is async-signal-safe.
            unsafe {
                libc::write(2, bytes.as_ptr().cast(), bytes.len() as _);
            }
        }
        Ok(())
    }
}

// ──────────────────────────────────────────────────────────────────────────
mod draft {

    use core::cell::Cell;
    #[cfg(not(windows))]
    use core::ffi::c_int;
    #[cfg(windows)]
    use core::ffi::c_long;
    use core::ffi::{c_char, c_void};
    use core::fmt;
    // D101: `core::fmt::Write` intentionally NOT in scope here — `bun_io::Write`
    // (via `super::Write`) supplies `write_fmt` for `BoundedArray<u8,N>`; importing
    // both makes `write!` ambiguous (E0034).
    use core::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering};

    use bun_base64::VLQ;
    use bun_collections::BoundedArray;
    use bun_core::strings;
    use bun_core::{Environment, Global, Output, env_var, fmt as bun_fmt};

    use super::{FmtAdapter, Write, debug, stderr_writer};

    /// D101: now identity. Pre-dedup `Write` had a `core::fmt::Write` supertrait so
    /// `write!` returned `fmt::Result` and needed remapping. With canonical
    /// `bun_io::Write::write_fmt` the error type is already `bun_core::Error`; this
    /// stays as a no-op so the ~22 `.map_err(fmt_err)?` sites don't churn.
    #[inline(always)]
    fn fmt_err(e: bun_core::Error) -> bun_core::Error {
        e
    }

    /// Zig: `Output.enable_ansi_colors_stderr` — runtime flag, exposed in Rust as an
    /// `AtomicBool` static. Re-exported here so call sites read like the Zig.
    use bun_core::output::enable_ansi_colors_stderr;

    /// Zig: `std.posix.abort()`. On POSIX this is `libc::abort()` (async-signal-safe).
    /// On Windows, Zig's `std.posix.abort()` is *not* MSVCRT `abort()` — it is
    /// `if (Debug) @breakpoint(); kernel32.ExitProcess(3);`. UCRT `abort()` would
    /// raise SIGABRT, may print `R6010 - abort() has been called` to stderr, and
    /// can pop a Watson/WER dialog — none of which the Zig spec does.
    #[inline(always)]
    fn abort() -> ! {
        #[cfg(windows)]
        {
            #[cfg(debug_assertions)]
            core::intrinsics::breakpoint();
            bun_sys::windows::kernel32::ExitProcess(3)
        }
        #[cfg(not(windows))]
        // SAFETY: libc::abort has no preconditions; never returns.
        unsafe {
            libc::abort()
        }
    }
    use super::cpu_features::CPUFeatures;
    use super::debug::{Color, SelfInfo, SourceLocation, TtyConfig};

    /// Zig: `bun.fmt.fmtArgv` — print an argv vector as a shell-ish line.
    /// crash_handler.zig:1024 calls this when the addr2line spawn fails.
    #[cfg(any(windows, target_os = "linux", target_os = "android"))]
    fn fmt_argv<W: super::Write>(w: &mut W, argv: &[Vec<u8>]) -> Result<(), bun_core::Error> {
        for (i, a) in argv.iter().enumerate() {
            if i > 0 {
                w.write_byte(b' ')?;
            }
            // argv came from this process so it's UTF-8 by construction; raw bytes
            // are fine for the stderr crash-path sink either way.
            w.write_all(a)?;
        }
        Ok(())
    }

    // TODO(port): `Cli` arrives from move-in (MOVE_DOWN bun_runtime::cli::Cli → crash_handler).
    // Only the two bits the crash handler needs — main-thread check and the
    // one-byte command tag for the trace URL — land here as plain globals that
    // `bun_runtime` populates at startup.
    pub mod cli_state {
        use core::sync::atomic::{AtomicU8, AtomicU64, Ordering};

        static MAIN_THREAD_ID: AtomicU64 = AtomicU64::new(0);
        /// 0 = unset → encoded as `_` in the trace string.
        static CMD_CHAR: AtomicU8 = AtomicU8::new(0);

        pub fn set_main_thread_id(id: u64) {
            MAIN_THREAD_ID.store(id, Ordering::Relaxed);
        }

        pub fn is_main_thread() -> bool {
            MAIN_THREAD_ID.load(Ordering::Relaxed) == bun_threading::current_thread_id()
        }
        pub(crate) fn cmd_char() -> Option<u8> {
            match CMD_CHAR.load(Ordering::Relaxed) {
                0 => None,
                c => Some(c),
            }
        }
    }

    // std.builtin.StackTrace lives in bun_core (T0); the debug-info types are local
    // shims (see `super::debug`) until a real bun_debug crate exists.
    pub use bun_core::StackTrace;

    /// Set this to false if you want to disable all uses of this panic handler.
    /// This is useful for testing as a crash in here will not 'panicked during a panic'.
    pub(crate) const ENABLE: bool = true;

    /// Overridable with BUN_CRASH_REPORT_URL environment variable.
    const DEFAULT_REPORT_BASE_URL: &str = "https://bun.report";

    /// Only print the `Bun has crashed` message once. Once this is true, control
    /// flow is not returned to the main application.
    static HAS_PRINTED_MESSAGE: AtomicBool = AtomicBool::new(false);

    /// Non-zero whenever the program triggered a panic.
    /// The counter is incremented/decremented atomically.
    /// PORT NOTE: shared with bun_core::PANICKING so T0 callers see the same state.
    use bun_core::PANICKING;
    // D131: dedup — these read the shared `PANICKING` atomic and were byte-identical
    // to the bun_core (T0) copies. Re-export so `bun_crash_handler::{is_panicking,
    // sleep_forever_if_another_thread_is_crashing}` keeps resolving for any
    // out-of-tree callers. `dump_current_stack_trace` is intentionally NOT deduped:
    // the bun_core version is an `extern "Rust"` dispatch shim, this crate's is the
    // real impl (linked via `__bun_crash_handler_dump_stack_trace`).
    pub use bun_core::{is_panicking, sleep_forever_if_another_thread_is_crashing};

    // Locked to avoid interleaving panic messages from multiple threads.
    // TODO: I don't think it's safe to lock/unlock a mutex inside a signal handler.
    // PORTING.md §Concurrency: `bun_threading::Guarded<()>` for a bare critical section.
    static PANIC_MUTEX: bun_threading::Guarded<()> = bun_threading::Guarded::new(());

    thread_local! {
        /// Counts how many times the panic handler is invoked by this thread.
        /// This is used to catch and handle panics triggered by the panic handler.
        static PANIC_STAGE: Cell<usize> = const { Cell::new(0) };

        static INSIDE_NATIVE_PLUGIN: Cell<Option<*const c_char>> = const { Cell::new(None) };
        static UNSUPPORTED_UV_FUNCTION: Cell<Option<*const c_char>> = const { Cell::new(None) };

        /// This can be set by various parts of the codebase to indicate a broader
        /// action being taken. It is printed when a crash happens, which can help
        /// narrow down what the bug is. Example: "Crashed while parsing /path/to/file.js"
        ///
        /// Some of these are enabled in release builds, which may encourage users to
        /// attach the affected files to crash report. Others, which may have low crash
        /// rate or only crash due to assertion failures, are debug-only. See `Action`.
        pub static CURRENT_ACTION: Cell<Option<Action>> = const { Cell::new(None) };
    }

    // PORTING.md §Concurrency: `bun_threading::Guarded<Vec<..>>` instead of bare Mutex + global Vec.
    // Stores a boxed type-erased closure (not a bare fn pointer) so that
    // `append_pre_crash_handler` can monomorphize a wrapper that actually invokes the
    // caller's typed handler — mirroring Zig's `comptime handler` trampoline.
    struct CrashHandlerEntry(*mut c_void, Box<dyn Fn(*mut c_void) + Send>);
    // SAFETY: only accessed under the mutex; the opaque ptr is never dereferenced
    // except by the registered callback on the crash thread.
    unsafe impl Send for CrashHandlerEntry {}
    static BEFORE_CRASH_HANDLERS: bun_threading::Guarded<Vec<CrashHandlerEntry>> =
        bun_threading::Guarded::new(Vec::new());

    /// Prevents crash reports from being uploaded to any server. Reports will still be printed and
    /// abort the process. Overrides BUN_CRASH_REPORT_URL, BUN_ENABLE_CRASH_REPORTING, and all other
    /// things that affect crash reporting. See suppressReporting() for intended usage.
    static SUPPRESS_REPORTING: AtomicBool = AtomicBool::new(false);

    /// This structure and formatter must be kept in sync with `bun.report`'s decoder implementation.
    #[derive(Clone, Copy)]
    pub enum CrashReason {
        /// From @panic()
        Panic(&'static [u8]),
        // TODO(port): lifetime — Zig holds a borrowed []const u8; using &'static here as a placeholder.
        /// "reached unreachable code"
        Unreachable,

        SegmentationFault(usize),
        IllegalInstruction(usize),

        /// Posix-only
        BusError(usize),
        /// Posix-only
        FloatingPointError(usize),
        /// Windows-only
        DatatypeMisalignment,
        /// Windows-only
        StackOverflow,

        /// Either `main` returned an error, or somewhere else in the code a trace string is printed.
        ZigError(bun_core::Error),

        OutOfMemory,
    }

    impl fmt::Display for CrashReason {
        fn fmt(&self, writer: &mut fmt::Formatter<'_>) -> fmt::Result {
            match self {
                CrashReason::Panic(message) => write!(writer, "{}", bstr::BStr::new(message)),
                CrashReason::Unreachable => writer.write_str("reached unreachable code"),
                CrashReason::SegmentationFault(addr) => {
                    write!(writer, "Segmentation fault at address 0x{:X}", addr)
                }
                CrashReason::IllegalInstruction(addr) => {
                    write!(writer, "Illegal instruction at address 0x{:X}", addr)
                }
                CrashReason::BusError(addr) => write!(writer, "Bus error at address 0x{:X}", addr),
                CrashReason::FloatingPointError(addr) => {
                    write!(writer, "Floating point error at address 0x{:X}", addr)
                }
                CrashReason::DatatypeMisalignment => writer.write_str("Unaligned memory access"),
                CrashReason::StackOverflow => writer.write_str("Stack overflow"),
                CrashReason::ZigError(err) => {
                    write!(writer, "error.{}", bstr::BStr::new(err.name()))
                }
                CrashReason::OutOfMemory => writer.write_str("Bun ran out of memory"),
            }
        }
    }

    /// bun.bundle_v2.LinkerContext.generateCompileResultForJSChunk
    ///
    /// The bundler types (`LinkerContext` / `Chunk` / `PartRange`) live in a
    /// higher-tier crate; `chunk`/`part_range` stay erased and are reinterpreted by
    /// the `Linker` impl in `bun_bundler::LinkerContext`.
    #[cfg(feature = "show_crash_trace")]
    #[derive(Clone, Copy)]
    pub struct BundleGenerateChunk {
        pub ctx: BundleGenerateChunkCtx,
        /// SAFETY: erased `&bun_bundler::Chunk`
        pub chunk: *const (),
        /// SAFETY: erased `&bun_bundler::PartRange`
        pub part_range: *const (),
    }

    #[cfg(feature = "show_crash_trace")]
    bun_dispatch::link_interface! {
        pub BundleGenerateChunkCtx[Linker] {
            fn fmt(chunk: *const (), part_range: *const (), writer: &mut core::fmt::Formatter<'_>) -> core::fmt::Result;
        }
    }

    #[cfg(feature = "show_crash_trace")]
    #[derive(Clone, Copy)]
    pub(crate) struct ResolverAction {
        pub source_dir: &'static [u8],
        pub import_path: &'static [u8],
        pub kind: bun_ast::ImportKind,
    }

    #[derive(Clone, Copy)]
    pub enum Action {
        Parse(&'static [u8]),
        Visit(&'static [u8]),
        Print(&'static [u8]),
        // TODO(port): lifetime — these slices borrow caller-owned paths; &'static is a placeholder.
        #[cfg(feature = "show_crash_trace")]
        BundleGenerateChunk(BundleGenerateChunk),
        #[cfg(not(feature = "show_crash_trace"))]
        BundleGenerateChunk(()),

        #[cfg(feature = "show_crash_trace")]
        Resolver(ResolverAction),
        #[cfg(not(feature = "show_crash_trace"))]
        Resolver(()),

        Dlopen(&'static [u8]),
    }

    impl fmt::Display for Action {
        fn fmt(&self, writer: &mut fmt::Formatter<'_>) -> fmt::Result {
            match self {
                Action::Parse(path) => write!(writer, "parsing {}", bstr::BStr::new(path)),
                Action::Visit(path) => write!(writer, "visiting {}", bstr::BStr::new(path)),
                Action::Print(path) => write!(writer, "printing {}", bstr::BStr::new(path)),
                #[cfg(feature = "show_crash_trace")]
                Action::BundleGenerateChunk(data) => {
                    data.ctx.fmt(data.chunk, data.part_range, writer)
                }
                #[cfg(not(feature = "show_crash_trace"))]
                Action::BundleGenerateChunk(()) => Ok(()),
                #[cfg(feature = "show_crash_trace")]
                Action::Resolver(res) => {
                    write!(
                        writer,
                        "resolving {} from {} ({})",
                        bstr::BStr::new(res.import_path),
                        bstr::BStr::new(res.source_dir),
                        bstr::BStr::new(res.kind.label()),
                    )
                }
                #[cfg(not(feature = "show_crash_trace"))]
                Action::Resolver(()) => Ok(()),
                Action::Dlopen(path) => {
                    write!(writer, "loading native module: {}", bstr::BStr::new(path))
                }
            }
        }
    }

    /// Snapshot the thread-local `CURRENT_ACTION` for save/restore around a scoped
    /// operation (e.g. `js_printer::print_with_writer_and_platform`).
    #[inline]
    pub fn current_action() -> Option<Action> {
        CURRENT_ACTION.with(|c| c.get())
    }

    /// Set (or clear) the thread-local `CURRENT_ACTION`. Paired with
    /// [`current_action`] for scoped restore via `scopeguard`.
    #[inline]
    pub(crate) fn set_current_action(action: Option<Action>) {
        CURRENT_ACTION.with(|c| c.set(action));
    }

    /// RAII guard returned by [`scoped_action`] / [`set_current_action_resolver`].
    /// Restores the previous `CURRENT_ACTION` on drop (Zig: `defer current_action = old`).
    pub struct ActionGuard(Option<Action>);
    impl Drop for ActionGuard {
        #[inline]
        fn drop(&mut self) {
            set_current_action(self.0);
        }
    }

    /// Scoped `CURRENT_ACTION = action`. Snapshots the previous value, installs
    /// `action`, and returns an [`ActionGuard`] that restores the previous value
    /// on drop. Zig: `const old = current_action; defer current_action = old;
    /// current_action = ...;`.
    #[inline]
    #[must_use]
    pub fn scoped_action(action: Action) -> ActionGuard {
        let prev = current_action();
        set_current_action(Some(action));
        ActionGuard(prev)
    }

    /// Scoped `CURRENT_ACTION = .resolver{...}`. Zig (resolver.zig:672-679) sets
    /// this only under `Environment.show_crash_trace` because module resolution is
    /// extremely hot and has a low crash rate; the cfg-gate here mirrors that.
    ///
    /// `source_dir`/`import_path` are caller-interned (DirnameStore / source text)
    /// and outlive the guard; the `&'static` lifetime erasure matches the existing
    /// `Action::Parse`/`Visit`/`Print` slice fields (see TODO(port) above).
    #[inline]
    pub fn set_current_action_resolver(
        source_dir: &[u8],
        import_path: &[u8],
        kind: bun_ast::ImportKind,
    ) -> ActionGuard {
        let prev = current_action();
        #[cfg(feature = "show_crash_trace")]
        {
            // SAFETY: caller-interned slices outlive the guard; see fn docs.
            let source_dir: &'static [u8] = unsafe { &*(source_dir as *const [u8]) };
            let import_path: &'static [u8] = unsafe { &*(import_path as *const [u8]) };
            set_current_action(Some(Action::Resolver(ResolverAction {
                source_dir,
                import_path,
                kind,
            })));
        }
        #[cfg(not(feature = "show_crash_trace"))]
        {
            let _ = (source_dir, import_path, kind);
            set_current_action(Some(Action::Resolver(())));
        }
        ActionGuard(prev)
    }

    /// Where the crash trace is seeded from. Each call site has exactly one.
    #[derive(Clone, Copy)]
    pub enum TraceSeed<'a> {
        /// Signal/exception handler saved the fault register context: walk frame
        /// pointers from `fp` (POSIX) / RtlCapture and trim by `pc` (Windows). `pc`
        /// becomes frame 0.
        Fault { pc: usize, fp: usize },
        /// A trace was already captured upstream (Zig error return traces).
        ErrorReturn(&'a StackTrace<'a>),
        /// Walk the current stack and trim the capture machinery above this PC.
        BeginAddr(usize),
        /// Walk the current stack with no trim (the handler's own `return_address()`
        /// is used as a best-effort trim point).
        None,
    }

    /// This function is invoked when a crash happens. A crash is classified in `CrashReason`.
    #[cold]
    pub fn crash_handler(reason: CrashReason, seed: TraceSeed<'_>) -> ! {
        if cfg!(debug_assertions) {
            Output::disable_scoped_debug_writer();
        }

        let mut trace_str_buf = BoundedArray::<u8, 1024>::default();

        match PANIC_STAGE.with(|s| s.get()) {
            0 => {
                bun_core::maybe_handle_panic_during_process_reload();

                PANIC_STAGE.with(|s| s.set(1));
                let _ = PANICKING.fetch_add(1, Ordering::SeqCst);

                if let Some(handlers) = BEFORE_CRASH_HANDLERS.try_lock() {
                    for CrashHandlerEntry(ptr, cb) in handlers.iter() {
                        cb(*ptr);
                    }
                }

                {
                    let _panic_guard = PANIC_MUTEX.lock();

                    // Use an raw unbuffered writer to stderr to avoid losing information on
                    // panic in a panic. There is also a possibility that `Output` related code
                    // is not configured correctly, so that would also mask the message.
                    //
                    // Output.errorWriter() is not used here because it may not be configured
                    // if the program crashes immediately at startup.
                    // TODO(port): std.fs.File.stderr().writerStreaming — local raw StderrWriter (bun_sys
                    //             FileWriter only impls std::io::Write, not the local byte-Write trait)
                    let writer = &mut stderr_writer();

                    // The format of the panic trace is slightly different in debug
                    // builds. Mainly, we demangle the backtrace immediately instead
                    // of using a trace string.
                    //
                    // To make the release-mode behavior easier to demo, debug mode
                    // checks for this CLI flag.
                    let debug_trace = Environment::SHOW_CRASH_TRACE
                        && 'check_flag: {
                            for arg in bun_core::argv() {
                                if arg == &b"--debug-crash-handler-use-trace-string"[..] {
                                    break 'check_flag false;
                                }
                            }
                            // Act like release build when explicitly enabling reporting
                            if is_reporting_enabled() {
                                break 'check_flag false;
                            }
                            true
                        };

                    // SAFETY: single-threaded mutation under panic_mutex
                    if !HAS_PRINTED_MESSAGE.load(Ordering::Relaxed) {
                        Output::flush();
                        Output::source::stdio::restore();

                        if writer
                            .write_all(
                                concat!(
                                    "============================================================",
                                    "\n"
                                )
                                .as_bytes(),
                            )
                            .is_err()
                        {
                            abort();
                        }
                        if print_metadata(writer).is_err() {
                            abort();
                        }

                        if let Some(name) = INSIDE_NATIVE_PLUGIN.with(|c| c.get()) {
                            // SAFETY: name was set from a valid NUL-terminated C string
                            let native_plugin_name =
                                unsafe { bun_core::ffi::cstr(name) }.to_bytes();
                            let fmt = "\nBun has encountered a crash while running the <red><d>\"{s}\"<r> native plugin.\n\nThis indicates either a bug in the native plugin or in Bun.\n";
                            if write!(
                                writer,
                                "{}",
                                Output::pretty_fmt_args(
                                    fmt,
                                    true,
                                    format_args!("{}", bstr::BStr::new(native_plugin_name))
                                )
                            )
                            .is_err()
                            {
                                abort();
                            }
                        } else if UNSUPPORTED_UV_FUNCTION.with(|c| c.get()).is_some() {
                            // TODO(port): bun_analytics::Features::unsupported_uv_function — using
                            // the threadlocal as a stand-in for the global counter check.
                            let name: &[u8] = UNSUPPORTED_UV_FUNCTION
                                .with(|c| c.get())
                                .map(|p| {
                                    // SAFETY: p was set from a valid NUL-terminated C string via CrashHandler__unsupportedUVFunction
                                    unsafe { bun_core::ffi::cstr(p) }.to_bytes()
                                })
                                .unwrap_or(b"<unknown>");
                            let fmt = "Bun encountered a crash when running a NAPI module that tried to call\nthe <red>{s}<r> libuv function.\n\nBun is actively working on supporting all libuv functions for POSIX\nsystems, please see this issue to track our progress:\n\n<cyan>https://github.com/oven-sh/bun/issues/18546<r>\n\n";
                            if write!(
                                writer,
                                "{}",
                                Output::pretty_fmt_args(
                                    fmt,
                                    true,
                                    format_args!("{}", bstr::BStr::new(name))
                                )
                            )
                            .is_err()
                            {
                                abort();
                            }
                            // SAFETY: single-threaded mutation under panic_mutex
                            HAS_PRINTED_MESSAGE.store(true, Ordering::Relaxed);
                        }
                    } else {
                        if enable_ansi_colors_stderr() {
                            if writer
                                .write_all(&Output::pretty_fmt::<true>("<red>"))
                                .is_err()
                            {
                                abort();
                            }
                        }
                        if writer.write_all(b"oh no").is_err() {
                            abort();
                        }
                        if enable_ansi_colors_stderr() {
                            if writer
                                .write_all(&Output::pretty_fmt::<true>(
                                    "<r><d>: multiple threads are crashing<r>\n",
                                ))
                                .is_err()
                            {
                                abort();
                            }
                        } else {
                            if writer
                                .write_all(&Output::pretty_fmt::<true>(
                                    ": multiple threads are crashing\n",
                                ))
                                .is_err()
                            {
                                abort();
                            }
                        }
                    }

                    if !matches!(reason, CrashReason::OutOfMemory) || debug_trace {
                        if enable_ansi_colors_stderr() {
                            if writer
                                .write_all(&Output::pretty_fmt::<true>("<red>"))
                                .is_err()
                            {
                                abort();
                            }
                        }

                        if writer.write_all(b"panic").is_err() {
                            abort();
                        }

                        if enable_ansi_colors_stderr() {
                            if writer
                                .write_all(&Output::pretty_fmt::<true>("<r><d>"))
                                .is_err()
                            {
                                abort();
                            }
                        }

                        if cli_state::is_main_thread() {
                            if writer.write_all(b"(main thread)").is_err() {
                                abort();
                            }
                        } else {
                            #[cfg(windows)]
                            {
                                // TODO(port): bun_sys::windows::GetThreadDescription / PWSTR / HRESULT_CODE
                                {
                                    let mut name: bun_sys::windows::PWSTR = core::ptr::null_mut();
                                    // SAFETY: GetCurrentThread/GetThreadDescription are valid Win32 calls
                                    let result = unsafe {
                                        bun_sys::windows::GetThreadDescription(
                                            bun_sys::windows::GetCurrentThread(),
                                            &mut name,
                                        )
                                    };
                                    // SAFETY: `name` is the PWSTR out-param written by GetThreadDescription; deref is guarded by the S_OK check via `&&` short-circuit
                                    if bun_sys::windows::HRESULT_CODE(result)
                                        == bun_sys::windows::S_OK
                                        && unsafe { *name } != 0
                                    {
                                        // SAFETY: `name` is a valid NUL-terminated wide string
                                        // (PWSTR out-param from GetThreadDescription).
                                        let span = unsafe { bun_core::ffi::wstr_units(name) };
                                        if write!(writer, "({})", bun_fmt::utf16(span)).is_err() {
                                            abort();
                                        }
                                        // NOTE: `GetThreadDescription` heap-allocates `name` and the
                                        // caller is meant to `LocalFree` it. The Zig spec leaks it
                                        // identically (crash_handler.zig:316-322) — this runs on a
                                        // `noreturn` crash path immediately before `ExitProcess(3)`,
                                        // so the leak is intentional.
                                    } else {
                                        if write!(
                                            writer,
                                            "(thread {})",
                                            bun_sys::windows::kernel32::GetCurrentThreadId()
                                        )
                                        .is_err()
                                        {
                                            abort();
                                        }
                                    }
                                }
                            }
                            #[cfg(any(
                                target_os = "macos",
                                target_os = "linux",
                                target_os = "android",
                                target_os = "freebsd"
                            ))]
                            { /* no-op */ }
                            // TODO(port): wasm @compileError("TODO")
                        }

                        if writer.write_all(b": ").is_err() {
                            abort();
                        }
                        if enable_ansi_colors_stderr() {
                            if writer
                                .write_all(&Output::pretty_fmt::<true>("<r>"))
                                .is_err()
                            {
                                abort();
                            }
                        }
                        if writeln!(writer, "{}", reason).is_err() {
                            abort();
                        }
                    }

                    if let Some(action) = CURRENT_ACTION.with(|c| c.get()) {
                        if writeln!(writer, "Crashed while {}", action).is_err() {
                            abort();
                        }
                    }

                    let mut addr_buf: [usize; 20] = [0; 20];
                    let trace_buf: StackTrace;

                    let trace: &StackTrace = 'blk: {
                        let idx: usize = match seed {
                            TraceSeed::ErrorReturn(ert) => break 'blk ert,
                            // For an actual fault the signal/exception handler hands
                            // us the saved register context. Seeding the walk from
                            // the fault `pc`/`fp` is the only reliable way to recover
                            // the faulting stack: the POSIX handler runs on an
                            // `SA_ONSTACK` altstack, so its own frame chain is
                            // disjoint from the faulting thread's, and release builds
                            // strip the unwind tables a CFI-based capture would need.
                            TraceSeed::Fault { pc, fp } => {
                                bun_core::debug::capture_from_context(pc, fp, &mut addr_buf)
                            }
                            TraceSeed::BeginAddr(addr) => {
                                debug::capture_stack_trace(addr, &mut addr_buf)
                            }
                            TraceSeed::None => {
                                debug::capture_stack_trace(debug::return_address(), &mut addr_buf)
                            }
                        };
                        trace_buf = StackTrace {
                            index: idx,
                            instruction_addresses: &addr_buf,
                        };
                        break 'blk &trace_buf;
                    };

                    if debug_trace {
                        // SAFETY: single-threaded mutation under panic_mutex
                        HAS_PRINTED_MESSAGE.store(true, Ordering::Relaxed);

                        dump_stack_trace(trace, WriteStackTraceLimits::default());

                        if write!(
                            trace_str_buf.writer(),
                            "{}",
                            TraceString {
                                trace,
                                reason,
                                action: TraceStringAction::ViewTrace,
                            }
                        )
                        .is_err()
                        {
                            abort();
                        }
                    } else {
                        // SAFETY: single-threaded read under panic_mutex
                        if !HAS_PRINTED_MESSAGE.load(Ordering::Relaxed) {
                            // SAFETY: single-threaded mutation under panic_mutex
                            HAS_PRINTED_MESSAGE.store(true, Ordering::Relaxed);
                            if writer.write_all(b"oh no").is_err() {
                                abort();
                            }
                            if enable_ansi_colors_stderr() {
                                if writer
                                    .write_all(&Output::pretty_fmt::<true>("<r><d>:<r> "))
                                    .is_err()
                                {
                                    abort();
                                }
                            } else {
                                if writer.write_all(&Output::pretty_fmt::<true>(": ")).is_err() {
                                    abort();
                                }
                            }
                            if let Some(name) = INSIDE_NATIVE_PLUGIN.with(|c| c.get()) {
                                // SAFETY: name was set from a valid NUL-terminated C string
                                let native_plugin_name =
                                    unsafe { bun_core::ffi::cstr(name) }.to_bytes();
                                if write!(writer, "{}", Output::pretty_fmt_args(
                                "Bun has encountered a crash while running the <red><d>\"{s}\"<r> native plugin.\n\nTo send a redacted crash report to Bun's team,\nplease file a GitHub issue using the link below:\n\n",
                                true,
                                format_args!("{}", bstr::BStr::new(native_plugin_name)),
                            )).is_err() { abort(); }
                            } else if UNSUPPORTED_UV_FUNCTION.with(|c| c.get()).is_some() {
                                // TODO(port): bun_analytics::Features::unsupported_uv_function
                                let name: &[u8] = UNSUPPORTED_UV_FUNCTION
                                    .with(|c| c.get())
                                    .map(|p| {
                                        // SAFETY: p was set from a valid NUL-terminated C string via CrashHandler__unsupportedUVFunction
                                        unsafe { bun_core::ffi::cstr(p) }.to_bytes()
                                    })
                                    .unwrap_or(b"<unknown>");
                                let fmt = "Bun encountered a crash when running a NAPI module that tried to call\nthe <red>{s}<r> libuv function.\n\nBun is actively working on supporting all libuv functions for POSIX\nsystems, please see this issue to track our progress:\n\n<cyan>https://github.com/oven-sh/bun/issues/18546<r>\n\n";
                                if write!(
                                    writer,
                                    "{}",
                                    Output::pretty_fmt_args(
                                        fmt,
                                        true,
                                        format_args!("{}", bstr::BStr::new(name))
                                    )
                                )
                                .is_err()
                                {
                                    abort();
                                }
                            } else if matches!(reason, CrashReason::OutOfMemory) {
                                if writer.write_all(
                                b"Bun has run out of memory.\n\nTo send a redacted crash report to Bun's team,\nplease file a GitHub issue using the link below:\n\n",
                            ).is_err() { abort(); }
                            } else {
                                if writer.write_all(
                                b"Bun has crashed. This indicates a bug in Bun, not your code.\n\nTo send a redacted crash report to Bun's team,\nplease file a GitHub issue using the link below:\n\n",
                            ).is_err() { abort(); }
                            }
                        }

                        if enable_ansi_colors_stderr() {
                            if writer
                                .write_all(&Output::pretty_fmt::<true>("<cyan>"))
                                .is_err()
                            {
                                abort();
                            }
                        }

                        if writer.write_all(b" ").is_err() {
                            abort();
                        }

                        if write!(
                            trace_str_buf.writer(),
                            "{}",
                            TraceString {
                                trace,
                                reason,
                                action: TraceStringAction::OpenIssue,
                            }
                        )
                        .is_err()
                        {
                            abort();
                        }

                        if writer.write_all(trace_str_buf.const_slice()).is_err() {
                            abort();
                        }

                        if writer.write_all(b"\n").is_err() {
                            abort();
                        }
                    }

                    if enable_ansi_colors_stderr() {
                        if writer
                            .write_all(&Output::pretty_fmt::<true>("<r>\n"))
                            .is_err()
                        {
                            abort();
                        }
                    } else {
                        if writer.write_all(b"\n").is_err() {
                            abort();
                        }
                    }
                }

                // Be aware that this function only lets one thread return from it.
                // This is important so that we do not try to run the following reload logic twice.
                wait_for_other_thread_to_finish_panicking();

                report(trace_str_buf.const_slice());

                // At this point, the crash handler has performed it's job. Reset the segfault handler
                // so that a crash will actually crash. We need this because we want the process to
                // exit with a signal, and allow tools to be able to gather core dumps.
                //
                // This is done so late (in comparison to the Zig Standard Library's panic handler)
                // because if multiple threads segfault (more often the case on Windows), we don't
                // want another thread to interrupt the crashing of the first one.
                reset_segfault_handler();

                if bun_core::auto_reload_on_crash()
                // Do not reload if the panic arose FROM the reload function.
                && !bun_core::is_process_reload_in_progress_on_another_thread()
                {
                    // attempt to prevent a double panic
                    bun_core::set_auto_reload_on_crash(false);

                    // TODO(port): pretty_fmt! color tags — runtime rewrite via pretty_fmt_args
                    Output::pretty_errorln(format_args!(
                        "<d>--- Bun is auto-restarting due to crash <d>[time: <b>{}<r><d>] ---<r>",
                        bun_core::time::milli_timestamp().max(0),
                    ));
                    Output::flush();

                    // TODO(port): comptime assert void == @TypeOf(bun.reloadProcess(...))
                    bun_core::reload_process(false, true);
                }
            }
            t @ (1 | 2) => {
                if t == 1 {
                    PANIC_STAGE.with(|s| s.set(2));

                    reset_segfault_handler();
                    Output::flush();
                }
                PANIC_STAGE.with(|s| s.set(3));

                // A panic happened while trying to print a previous panic message,
                // we're still holding the mutex but that's fine as we're going to
                // call abort()
                let stderr = &mut stderr_writer();
                if write!(stderr, "\npanic: {}\n", reason).is_err() {
                    abort();
                }
                if writeln!(stderr, "panicked during a panic. Aborting.").is_err() {
                    abort();
                }
            }
            3 => {
                // Panicked while printing "Panicked during a panic."
                PANIC_STAGE.with(|s| s.set(4));
            }
            _ => {
                // Panicked or otherwise looped into the panic handler while trying to exit.
                abort();
            }
        }

        crash();
    }

    /// This is called when `main` returns a Zig error.
    /// We don't want to treat it as a crash under certain error codes.
    pub fn handle_root_error(err: bun_core::Error, error_return_trace: Option<&StackTrace>) -> ! {
        use bun_core::{err_generic, pretty_error};

        /// Zig: `std.posix.getrlimit(.NOFILE)`. bun_sys::posix has no rlimit yet —
        /// thin libc wrapper (POD out-param, never fails on supported targets).
        #[cfg(unix)]
        fn getrlimit_nofile() -> Option<libc::rlimit> {
            // SAFETY: zeroed rlimit is valid POD; getrlimit only writes to it.
            let mut lim: libc::rlimit = bun_core::ffi::zeroed();
            // SAFETY: &mut lim is a valid out-pointer.
            if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &raw mut lim) } == 0 {
                Some(lim)
            } else {
                None
            }
        }

        let mut show_trace = Environment::SHOW_CRASH_TRACE;

        // Match against interned error consts (see PORTING.md §Idiom map: catch |e| switch (e))
        if err == bun_core::err!("OutOfMemory") {
            super::out_of_memory();
        } else if err == bun_core::err!("InvalidArgument")
            || err == bun_core::err!("Invalid Bunfig")
            || err == bun_core::err!("InstallFailed")
        {
            if !show_trace {
                Global::exit(1);
            }
        } else if err == bun_core::err!("SyntaxError") {
            Output::err("SyntaxError", "An error occurred while parsing code", ());
        } else if err == bun_core::err!("CurrentWorkingDirectoryUnlinked") {
            err_generic!(
                "The current working directory was deleted, so that command didn't work. Please cd into a different directory and try again.",
            );
        } else if err == bun_core::err!("SystemFdQuotaExceeded") {
            #[cfg(unix)]
            {
                let limit = getrlimit_nofile().map(|l| l.rlim_cur);
                #[cfg(target_os = "macos")]
                {
                    pretty_error!(
                        "<r><red>error<r>: Your computer ran out of file descriptors <d>(<red>SystemFdQuotaExceeded<r><d>)<r>\n\n<d>Current limit: {}<r>\n\nTo fix this, try running:\n\n  <cyan>sudo launchctl limit maxfiles 2147483646<r>\n  <cyan>ulimit -n 2147483646<r>\n\nThat will only work until you reboot.\n",
                        bun_fmt::nullable_fallback(limit, b"<unknown>"),
                    );
                }
                #[cfg(target_os = "freebsd")]
                {
                    pretty_error!(
                        "\n<r><red>error<r>: Your computer ran out of file descriptors <d>(<red>SystemFdQuotaExceeded<r><d>)<r>\n\n<d>Current limit: {}<r>\n\nTo fix this, try running:\n\n  <cyan>sudo sysctl kern.maxfiles=2147483646 kern.maxfilesperproc=2147483646<r>\n  <cyan>ulimit -n 2147483646<r>\n\nTo persist across reboots, add to /etc/sysctl.conf and edit /etc/login.conf.\n",
                        bun_fmt::nullable_fallback(limit, b"<unknown>"),
                    );
                }
                #[cfg(not(any(target_os = "macos", target_os = "freebsd")))]
                {
                    pretty_error!(
                        "\n<r><red>error<r>: Your computer ran out of file descriptors <d>(<red>SystemFdQuotaExceeded<r><d>)<r>\n\n<d>Current limit: {}<r>\n\nTo fix this, try running:\n\n  <cyan>sudo echo -e \"\\nfs.file-max=2147483646\\n\" >> /etc/sysctl.conf<r>\n  <cyan>sudo sysctl -p<r>\n  <cyan>ulimit -n 2147483646<r>\n",
                        bun_fmt::nullable_fallback(limit, b"<unknown>"),
                    );

                    if let Some(user) = env_var::USER::get() {
                        if !user.is_empty() {
                            let user = bstr::BStr::new(user);
                            pretty_error!(
                                "\nIf that still doesn't work, you may need to add these lines to /etc/security/limits.conf:\n\n <cyan>{} soft nofile 2147483646<r>\n <cyan>{} hard nofile 2147483646<r>\n",
                                user,
                                user,
                            );
                        }
                    }
                }
            }
            #[cfg(not(unix))]
            {
                pretty_error!(
                    "<r><red>error<r>: Your computer ran out of file descriptors <d>(<red>SystemFdQuotaExceeded<r><d>)<r>",
                );
            }
        } else if err == bun_core::err!("ProcessFdQuotaExceeded") {
            #[cfg(unix)]
            {
                let limit = getrlimit_nofile().map(|l| l.rlim_cur);
                #[cfg(target_os = "macos")]
                {
                    pretty_error!(
                        "\n<r><red>error<r>: bun ran out of file descriptors <d>(<red>ProcessFdQuotaExceeded<r><d>)<r>\n\n<d>Current limit: {}<r>\n\nTo fix this, try running:\n\n  <cyan>ulimit -n 2147483646<r>\n\nYou may also need to run:\n\n  <cyan>sudo launchctl limit maxfiles 2147483646<r>\n",
                        bun_fmt::nullable_fallback(limit, b"<unknown>"),
                    );
                }
                #[cfg(target_os = "freebsd")]
                {
                    pretty_error!(
                        "\n<r><red>error<r>: bun ran out of file descriptors <d>(<red>ProcessFdQuotaExceeded<r><d>)<r>\n\n<d>Current limit: {}<r>\n\nTo fix this, try running:\n\n  <cyan>ulimit -n 2147483646<r>\n  <cyan>sudo sysctl kern.maxfilesperproc=2147483646<r>\n",
                        bun_fmt::nullable_fallback(limit, b"<unknown>"),
                    );
                }
                #[cfg(not(any(target_os = "macos", target_os = "freebsd")))]
                {
                    pretty_error!(
                        "\n<r><red>error<r>: bun ran out of file descriptors <d>(<red>ProcessFdQuotaExceeded<r><d>)<r>\n\n<d>Current limit: {}<r>\n\nTo fix this, try running:\n\n  <cyan>ulimit -n 2147483646<r>\n\nThat will only work for the current shell. To fix this for the entire system, run:\n\n  <cyan>sudo echo -e \"\\nfs.file-max=2147483646\\n\" >> /etc/sysctl.conf<r>\n  <cyan>sudo sysctl -p<r>\n",
                        bun_fmt::nullable_fallback(limit, b"<unknown>"),
                    );

                    if let Some(user) = env_var::USER::get() {
                        if !user.is_empty() {
                            let user = bstr::BStr::new(user);
                            pretty_error!(
                                "\nIf that still doesn't work, you may need to add these lines to /etc/security/limits.conf:\n\n <cyan>{} soft nofile 2147483646<r>\n <cyan>{} hard nofile 2147483646<r>\n",
                                user,
                                user,
                            );
                        }
                    }
                }
            }
            #[cfg(not(unix))]
            {
                bun_core::pretty_errorln!(
                    "<r><red>error<r>: bun ran out of file descriptors <d>(<red>ProcessFdQuotaExceeded<r><d>)<r>",
                );
            }
        } else if err == bun_core::err!("NotOpenForReading") || err == bun_core::err!("Unexpected")
        {
            // The usage of `unreachable` in Zig's std.posix may cause the file descriptor problem to show up as other errors
            #[cfg(unix)]
            {
                // SAFETY: zeroed rlimit is valid POD (integers).
                let limit = getrlimit_nofile().unwrap_or(bun_core::ffi::zeroed());

                if limit.rlim_cur > 0 && limit.rlim_cur < (8192 * 2) {
                    pretty_error!(
                        "\n<r><red>error<r>: An unknown error occurred, possibly due to low max file descriptors <d>(<red>Unexpected<r><d>)<r>\n\n<d>Current limit: {}<r>\n\nTo fix this, try running:\n\n  <cyan>ulimit -n 2147483646<r>\n",
                        limit.rlim_cur,
                    );

                    #[cfg(any(target_os = "linux", target_os = "android"))]
                    {
                        if let Some(user) = env_var::USER::get() {
                            if !user.is_empty() {
                                let user = bstr::BStr::new(user);
                                pretty_error!(
                                    "\nIf that still doesn't work, you may need to add these lines to /etc/security/limits.conf:\n\n <cyan>{} soft nofile 2147483646<r>\n <cyan>{} hard nofile 2147483646<r>\n",
                                    user,
                                    user,
                                );
                            }
                        }
                    }
                    #[cfg(target_os = "macos")]
                    {
                        pretty_error!(
                            "\nIf that still doesn't work, you may need to run:\n\n  <cyan>sudo launchctl limit maxfiles 2147483646<r>\n",
                        );
                    }
                } else {
                    err_generic!(
                        "An unknown error occurred <d>(<red>{}<r><d>)<r>",
                        bstr::BStr::new(err.name()),
                    );
                    show_trace = true;
                }
            }
            #[cfg(not(unix))]
            {
                err_generic!(
                    "An unknown error occurred <d>(<red>{}<r><d>)<r>",
                    bstr::BStr::new(err.name()),
                );
                show_trace = true;
            }
        } else if err == bun_core::err!("ENOENT") || err == bun_core::err!("FileNotFound") {
            Output::err(
                "ENOENT",
                "Bun could not find a file, and the code that produces this error is missing a better error.",
                (),
            );
        } else if err == bun_core::err!("MissingPackageJSON") {
            err_generic!("Bun could not find a package.json file to install from");
            Output::note("Run \"bun init\" to initialize a project");
        } else {
            // PORT NOTE: Zig picked the format string at comptime; the macros need
            // `:literal`, so branch on the const and call separately.
            if Environment::SHOW_CRASH_TRACE {
                err_generic!(
                    "'main' returned <red>error.{}<r>",
                    bstr::BStr::new(err.name())
                );
            } else {
                err_generic!(
                    "An internal error occurred (<red>{}<r>)",
                    bstr::BStr::new(err.name())
                );
            }
            show_trace = true;
        }

        if show_trace {
            VERBOSE_ERROR_TRACE.store(show_trace, Ordering::Relaxed);
            handle_error_return_trace_extra::<true>(err, error_return_trace);
        }

        Global::exit(1);
    }

    #[cold]
    pub fn panic_impl(
        msg: &[u8],
        error_return_trace: Option<&StackTrace>,
        begin_addr: Option<usize>,
    ) -> ! {
        crash_handler(
            if msg == b"reached unreachable code" {
                CrashReason::Unreachable
            } else {
                // TODO(port): lifetime — Zig borrows msg; erased to &'static for the noreturn path.
                // SAFETY: process is about to abort; the borrow is never invalidated.
                CrashReason::Panic(unsafe { bun_collections::detach_lifetime(msg) })
            },
            match error_return_trace {
                Some(ert) if ert.index > 0 => TraceSeed::ErrorReturn(ert),
                _ => TraceSeed::BeginAddr(begin_addr.unwrap_or_else(debug::return_address)),
            },
        );
    }

    pub(crate) fn report_base_url() -> &'static [u8] {
        // PORTING.md §Concurrency: OnceLock for lazy global init (was a raw mutable global Option).
        static BASE_URL: std::sync::OnceLock<&'static [u8]> = std::sync::OnceLock::new();
        *BASE_URL.get_or_init(|| {
            if let Some(url) = env_var::BUN_CRASH_REPORT_URL::get() {
                return strings::without_trailing_slash(url);
            }
            DEFAULT_REPORT_BASE_URL.as_bytes()
        })
    }

    const ARCH_DISPLAY_STRING: &str = if cfg!(target_arch = "aarch64") {
        if cfg!(target_os = "macos") {
            "Silicon"
        } else {
            "arm64"
        }
    } else {
        "x64"
    };

    // TODO(port): std.fmt.comptimePrint — use const_format::formatcp!
    const METADATA_VERSION_LINE: &str = const_format::formatcp!(
        "Bun {}v{} {} {}{}\n",
        if cfg!(debug_assertions) {
            "Debug "
        } else if Environment::IS_CANARY {
            "Canary "
        } else {
            ""
        },
        bun_core::package_json_version_with_sha,
        bun_core::os_display,
        ARCH_DISPLAY_STRING,
        if Environment::BASELINE {
            " (baseline)"
        } else {
            ""
        },
    );

    /// Extract `(pc, fp)` from the `ucontext_t` the kernel hands the signal
    /// handler. Seeds the frame-pointer walk from the faulting frame. Returns
    /// `None` on arch/OS combos we don't have register offsets for (the caller
    /// then falls back to a current-stack capture).
    #[cfg(unix)]
    fn fault_context_from_ucontext(ctx: *mut c_void) -> Option<(usize, usize)> {
        debug_assert!(!ctx.is_null());
        let uc = ctx.cast::<libc::ucontext_t>().cast_const();
        #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
        // SAFETY: the kernel passes a valid ucontext_t as the handler's 3rd arg.
        unsafe {
            let mc = &(*uc).uc_mcontext;
            let pc = mc.gregs[libc::REG_RIP as usize] as usize;
            let fp = mc.gregs[libc::REG_RBP as usize] as usize;
            Some((pc, fp))
        }
        #[cfg(all(target_os = "linux", target_arch = "aarch64"))]
        // SAFETY: the kernel passes a valid ucontext_t as the handler's 3rd arg.
        unsafe {
            let mc = &(*uc).uc_mcontext;
            Some((mc.pc as usize, mc.regs[29] as usize))
        }
        #[cfg(all(target_os = "macos", target_arch = "x86_64"))]
        // SAFETY: the kernel passes a valid ucontext_t as the handler's 3rd arg.
        unsafe {
            let mc = (*uc).uc_mcontext;
            if mc.is_null() {
                return None;
            }
            Some(((*mc).__ss.__rip as usize, (*mc).__ss.__rbp as usize))
        }
        #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
        // SAFETY: the kernel passes a valid ucontext_t as the handler's 3rd arg.
        unsafe {
            let mc = (*uc).uc_mcontext;
            if mc.is_null() {
                return None;
            }
            Some(((*mc).__ss.__pc as usize, (*mc).__ss.__fp as usize))
        }
        #[cfg(not(any(
            all(target_os = "linux", target_arch = "x86_64"),
            all(target_os = "linux", target_arch = "aarch64"),
            all(target_os = "macos", target_arch = "x86_64"),
            all(target_os = "macos", target_arch = "aarch64"),
        )))]
        {
            let _ = uc;
            None
        }
    }

    #[cfg(unix)]
    extern "C" fn handle_segfault_posix(sig: c_int, info: *mut libc::siginfo_t, ctx: *mut c_void) {
        // SAFETY: kernel provides a valid siginfo_t; `si_addr` reads the per-platform
        // sigfault address field (Zig: `info.fields.sigfault.addr` / `info.addr`).
        let addr: usize = unsafe { (*info).si_addr() as usize };

        crash_handler(
            match sig {
                libc::SIGSEGV => CrashReason::SegmentationFault(addr),
                libc::SIGILL => CrashReason::IllegalInstruction(addr),
                libc::SIGBUS => CrashReason::BusError(addr),
                libc::SIGFPE => CrashReason::FloatingPointError(addr),
                // we do not register this handler for other signals
                _ => unreachable!(),
            },
            match fault_context_from_ucontext(ctx) {
                Some((pc, fp)) => TraceSeed::Fault { pc, fp },
                None => TraceSeed::None,
            },
        );
    }

    #[cfg(unix)]
    static DID_REGISTER_SIGALTSTACK: AtomicBool = AtomicBool::new(false);
    /// 512K alternate signal stack. The kernel writes here during signal delivery;
    /// Rust never reads/writes the bytes, so `RacyCell` only needs to provide a
    /// stable `*mut u8` for `sigaltstack(2)`.
    #[cfg(unix)]
    static SIGALTSTACK: bun_core::RacyCell<[u8; 512 * 1024]> =
        bun_core::RacyCell::new([0; 512 * 1024]);

    #[cfg(unix)]
    fn update_posix_segfault_handler(
        mut act: Option<&mut libc::sigaction>,
    ) -> Result<(), bun_core::Error> {
        if let Some(act_) = act.as_deref_mut() {
            // SAFETY: single global; only mutated during signal-handler setup
            if !DID_REGISTER_SIGALTSTACK.load(Ordering::Relaxed) {
                let stack = libc::stack_t {
                    ss_flags: 0,
                    ss_size: 512 * 1024,
                    // SAFETY: SIGALTSTACK is a process-lifetime static byte buffer; the kernel only writes to it during signal delivery (no Rust aliasing)
                    ss_sp: SIGALTSTACK.get().cast(),
                };

                // SAFETY: stack points to a valid static buffer
                if unsafe { libc::sigaltstack(&raw const stack, core::ptr::null_mut()) } == 0 {
                    act_.sa_flags |= libc::SA_ONSTACK;
                    // SAFETY: single global; only mutated during signal-handler setup
                    DID_REGISTER_SIGALTSTACK.store(true, Ordering::Relaxed);
                }
            }
        }

        let act_ptr: *const libc::sigaction = act
            .map(|a| std::ptr::from_ref(a))
            .unwrap_or(core::ptr::null());
        // SAFETY: valid sigaction pointer or null; null oldact is permitted.
        unsafe {
            libc::sigaction(libc::SIGSEGV, act_ptr, core::ptr::null_mut());
            libc::sigaction(libc::SIGILL, act_ptr, core::ptr::null_mut());
            libc::sigaction(libc::SIGBUS, act_ptr, core::ptr::null_mut());
            libc::sigaction(libc::SIGFPE, act_ptr, core::ptr::null_mut());
        }
        Ok(())
    }

    // Windows VEH handle storage lives at T0 (`bun_core::WINDOWS_SEGFAULT_HANDLE`,
    // `AtomicPtr<c_void>`) so `bun_core::raise_ignoring_panic_handler` can remove
    // it before re-raising without an upward dep. Single source of truth — this
    // crate reads/writes/swaps that same atomic; no local mirror (a second copy
    // would go stale after T0's swap-to-null and trip the `debug_assert!(rc != 0)`
    // in `reset_segfault_handler` on a double-remove).

    #[cfg(unix)]
    pub fn reset_on_posix() {
        if Environment::ENABLE_ASAN {
            return;
        }
        // Zig: std.posix.Sigaction{ .handler = .{ .sigaction = handleSegfaultPosix }, ... }.
        // SAFETY: zeroed sigaction is valid POD; we overwrite the fields we need.
        let mut act: libc::sigaction = bun_core::ffi::zeroed();
        act.sa_sigaction = handle_segfault_posix as *const () as usize;
        act.sa_flags = libc::SA_SIGINFO | libc::SA_RESTART | libc::SA_RESETHAND;
        // SAFETY: sa_mask is a valid out-pointer.
        unsafe {
            libc::sigemptyset(&raw mut act.sa_mask);
        }
        let _ = update_posix_segfault_handler(Some(&mut act));
    }

    pub fn init() {
        if !ENABLE {
            return;
        }
        #[cfg(windows)]
        {
            // SAFETY: AddVectoredExceptionHandler is a valid Win32 call
            unsafe {
                // SAFETY: ABI-identical `extern "system" fn(*mut _) -> i32` —
                // `*mut EXCEPTION_POINTERS` vs the type-erased `*mut c_void` in
                // the kernel32 binding, `c_long` == `i32` on Win64.
                let handle = bun_sys::windows::kernel32::AddVectoredExceptionHandler(
                    0,
                    bun_ptr::cast_fn_ptr::<
                        extern "system" fn(*mut bun_sys::windows::EXCEPTION_POINTERS) -> c_long,
                        unsafe extern "system" fn(*mut core::ffi::c_void) -> i32,
                    >(handle_segfault_windows),
                );
                // Publish to T0 storage (single source of truth — see note above
                // `reset_on_posix`). `HANDLE` is `*mut c_void`; cast is identity.
                bun_core::WINDOWS_SEGFAULT_HANDLE
                    .store(handle as *mut core::ffi::c_void, Ordering::Relaxed);
            }
        }
        #[cfg(any(
            target_os = "macos",
            target_os = "linux",
            target_os = "android",
            target_os = "freebsd"
        ))]
        {
            reset_on_posix();
        }
        // TODO(port): wasm @compileError("TODO")

        install_hooks();
    }

    /// One-shot state registration into lower-tier crates. Storage moved down:
    /// `bun_core::CRASH_HANDLER_INSTALLED` is a plain `AtomicBool`; T0's
    /// `raise_ignoring_panic_handler` does the SIG_DFL reset itself with libc.
    pub(crate) fn install_hooks() {
        bun_core::CRASH_HANDLER_INSTALLED.store(true, Ordering::Relaxed);
        // T0 `bun_alloc::out_of_memory()` and `bun_core::dump_current_stack_trace()`
        // reach this crate via link-time `extern "Rust"` symbols
        // (`__bun_crash_handler_out_of_memory` / `__bun_crash_handler_dump_stack_trace`)
        // — no runtime registration needed.
        //
        // Route Rust `panic!()` through the trace-string + report path. Zig wires
        // `pub const panic = bun.crash_handler.panic` at the root so every
        // `@panic()` reports; the Rust port's bare `panic!` was printing the std
        // default hook + unwinding with no trace string and no upload.
        std::panic::set_hook(Box::new(rust_panic_hook));
    }

    /// `std::panic` hook: emit the same trace-string + auto-report as the fatal
    /// `crash_handler()` path, then **abort** (matches Zig's `noreturn` panic).
    /// With `panic = "abort"` no unwind starts after this hook returns, so there
    /// are no `catch_unwind` boundaries to reach.
    #[cold]
    #[inline(never)]
    fn rust_panic_hook(info: &std::panic::PanicHookInfo<'_>) {
        // Re-entry guard: if the hook itself panics (formatter, write, …), the
        // recursive entry sees stage>0, prints a one-liner, and returns so the
        // inner unwind tears the process down rather than looping.
        let stage = PANIC_STAGE.with(|s| s.get());
        if stage != 0 {
            PANIC_STAGE.with(|s| s.set(stage + 1));
            let stderr = &mut stderr_writer();
            let _ = write!(
                stderr,
                "\npanic: {info}\npanicked during a panic. Aborting.\n"
            );
            return;
        }
        PANIC_STAGE.with(|s| s.set(1));

        // Just the panic message — no `(file:line:col)` suffix. The call site is
        // captured in the backtrace and symbolized there (matching Zig, which
        // never appended a location to the message). With `-Zlocation-detail=none`
        // in release the location would be `<redacted>:0:0` anyway.
        let mut msg_buf = BoundedArray::<u8, 1024>::default();
        {
            let payload = info.payload();
            let msg: &str = if let Some(s) = payload.downcast_ref::<&'static str>() {
                s
            } else if let Some(s) = payload.downcast_ref::<std::string::String>() {
                s.as_str()
            } else {
                "<non-string panic payload>"
            };
            let _ = write!(msg_buf.writer(), "{msg}");
        }
        // SAFETY: `CrashReason::Panic` stores `&'static [u8]` (it was designed for
        // the `-> !` path). `msg_buf` outlives every read of `reason` below — the
        // borrow is fully consumed by the `Display`/`TraceString` writes inside
        // this frame and never escapes.
        let reason =
            CrashReason::Panic(unsafe { bun_collections::detach_lifetime(msg_buf.const_slice()) });

        let mut trace_str_buf = BoundedArray::<u8, 1024>::default();
        {
            let _panic_guard = PANIC_MUTEX.lock();
            let writer = &mut stderr_writer();

            let debug_trace = Environment::SHOW_CRASH_TRACE
                && 'check_flag: {
                    for arg in bun_core::argv() {
                        if arg == &b"--debug-crash-handler-use-trace-string"[..] {
                            break 'check_flag false;
                        }
                    }
                    if is_reporting_enabled() {
                        break 'check_flag false;
                    }
                    true
                };

            Output::flush();
            let _ =
                writer.write_all(b"============================================================\n");
            let _ = print_metadata(writer);

            if enable_ansi_colors_stderr() {
                let _ = writer.write_all(&Output::pretty_fmt::<true>("<red>"));
            }
            let _ = writer.write_all(b"panic");
            if enable_ansi_colors_stderr() {
                let _ = writer.write_all(&Output::pretty_fmt::<true>("<r>"));
            }
            let _ = writeln!(writer, ": {}", reason);

            if let Some(action) = CURRENT_ACTION.with(|c| c.get()) {
                let _ = writeln!(writer, "Crashed while {}", action);
            }

            let mut addr_buf: [usize; 20] = [0; 20];
            let idx = debug::capture_stack_trace(debug::return_address(), &mut addr_buf);
            let trace = StackTrace {
                index: idx,
                instruction_addresses: &addr_buf,
            };

            if debug_trace {
                dump_stack_trace(&trace, WriteStackTraceLimits::default());
                let _ = write!(
                    trace_str_buf.writer(),
                    "{}",
                    TraceString {
                        trace: &trace,
                        reason,
                        action: TraceStringAction::ViewTrace,
                    }
                );
            } else {
                let _ = writer.write_all(b"oh no");
                if enable_ansi_colors_stderr() {
                    let _ = writer.write_all(&Output::pretty_fmt::<true>("<r><d>:<r> "));
                } else {
                    let _ = writer.write_all(b": ");
                }
                let _ = writer.write_all(
                    b"Bun has crashed. This indicates a bug in Bun, not your code.\n\n\
                  To send a redacted crash report to Bun's team,\n\
                  please file a GitHub issue using the link below:\n\n ",
                );
                if enable_ansi_colors_stderr() {
                    let _ = writer.write_all(&Output::pretty_fmt::<true>("<cyan>"));
                }
                let _ = write!(
                    trace_str_buf.writer(),
                    "{}",
                    TraceString {
                        trace: &trace,
                        reason,
                        action: TraceStringAction::OpenIssue,
                    }
                );
                let _ = writer.write_all(trace_str_buf.const_slice());
                let _ = writer.write_all(b"\n");
            }
            if enable_ansi_colors_stderr() {
                let _ = writer.write_all(&Output::pretty_fmt::<true>("<r>\n"));
            } else {
                let _ = writer.write_all(b"\n");
            }
        }

        report(trace_str_buf.const_slice());

        // A Rust `panic!` is a bug. The process must not continue — with
        // `panic = "abort"` no unwind starts, so `catch_unwind` boundaries are
        // unreachable for Rust panics. This matches Zig's
        // `pub const panic = bun.crash_handler.panic` (which is `noreturn`).
        crash();
    }

    /// Adapter for non-fatal `bun_core::dump_current_stack_trace` callers
    /// (fd.rs EBADF debug-warn, ref_count leak reports). Zig routes these through
    /// `dumpStackTrace` which on Linux debug spawns `llvm-symbolizer` — but the
    /// Rust debug binary's .debug_info is large enough that the symbolizer parse
    /// alone costs ~5s, which is unacceptable on a hot non-fatal path
    /// (`closeSync(EBADF)` was timing out fs.test.ts at the 5s budget). For these
    /// advisory dumps we honour `frame_count` and use WTF's dladdr-based printer
    /// (sub-ms, function names only). The full `dump_stack_trace` (with
    /// llvm-symbolizer source lines) is kept for actual crash/panic paths, which
    /// call it directly.
    pub(crate) fn dump_current_stack_trace_from_core(
        first_address: Option<usize>,
        limits: bun_core::DumpStackTraceOptions,
    ) {
        Output::flush();
        let mut addrs: [usize; 32] = [0; 32];
        let n = debug::capture_stack_trace(
            first_address.unwrap_or_else(debug::return_address),
            &mut addrs,
        );
        let n = n.min(limits.frame_count);
        if !Environment::SHOW_CRASH_TRACE {
            // debug symbols aren't available, lets print a tracestring
            let stderr = &mut stderr_writer();
            let stack = StackTrace {
                index: n,
                instruction_addresses: &addrs,
            };
            let _ = writeln!(
                stderr,
                "View Debug Trace: {}",
                TraceString {
                    action: TraceStringAction::ViewTrace,
                    reason: CrashReason::ZigError(bun_core::err!("DumpStackTrace")),
                    trace: &stack,
                }
            );
            return;
        }
        // SAFETY: `addrs[..n]` is a valid slice of captured return addresses.
        unsafe {
            WTF__DumpStackTrace(addrs.as_ptr(), n);
        }
    }

    pub(crate) fn reset_segfault_handler() {
        if !ENABLE {
            return;
        }
        if Environment::ENABLE_ASAN {
            return;
        }

        #[cfg(windows)]
        {
            // Swap-to-null so a concurrent/reentrant reset (or T0's
            // `raise_ignoring_panic_handler`) can't double-remove the same handle.
            let handle =
                bun_core::WINDOWS_SEGFAULT_HANDLE.swap(core::ptr::null_mut(), Ordering::Relaxed);
            if !handle.is_null() {
                // SAFETY: handle was returned by AddVectoredExceptionHandler and
                // not yet removed (atomically claimed via the swap above).
                let rc =
                    unsafe { bun_sys::windows::kernel32::RemoveVectoredExceptionHandler(handle) };
                debug_assert!(rc != 0);
            }
            return;
        }

        #[cfg(unix)]
        {
            // SAFETY: zeroed sigaction is valid POD; handler = SIG_DFL (= 0), flags = 0.
            let mut act: libc::sigaction = bun_core::ffi::zeroed();
            act.sa_sigaction = libc::SIG_DFL;
            // SAFETY: sa_mask is a valid out-pointer.
            unsafe {
                libc::sigemptyset(&raw mut act.sa_mask);
            }
            // To avoid a double-panic, do nothing if an error happens here.
            let _ = update_posix_segfault_handler(Some(&mut act));
        }
    }

    #[cfg(windows)]
    pub(crate) extern "system" fn handle_segfault_windows(
        info: *mut bun_sys::windows::EXCEPTION_POINTERS,
    ) -> c_long {
        // SAFETY: kernel provides a valid EXCEPTION_POINTERS
        let info = unsafe { &*info };
        let reason = match unsafe { (*info.ExceptionRecord).ExceptionCode } {
            bun_sys::windows::EXCEPTION_DATATYPE_MISALIGNMENT => CrashReason::DatatypeMisalignment,
            bun_sys::windows::EXCEPTION_ACCESS_VIOLATION => {
                CrashReason::SegmentationFault(unsafe {
                    (*info.ExceptionRecord).ExceptionInformation[1]
                })
            }
            bun_sys::windows::EXCEPTION_ILLEGAL_INSTRUCTION => {
                // `ExceptionAddress` is the faulting RIP for `STATUS_ILLEGAL_
                // INSTRUCTION` (winnt.h); avoids depending on the arch-specific
                // `CONTEXT` layout (Zig reached `ContextRecord.Rip` directly).
                CrashReason::IllegalInstruction(
                    unsafe { (*info.ExceptionRecord).ExceptionAddress } as usize
                )
            }
            bun_sys::windows::EXCEPTION_STACK_OVERFLOW => CrashReason::StackOverflow,

            // exception used for thread naming
            // https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2017/debugger/how-to-set-a-thread-name-in-native-code?view=vs-2017#set-a-thread-name-by-throwing-an-exception
            // related commit
            // https://github.com/go-delve/delve/pull/1384
            bun_sys::windows::MS_VC_EXCEPTION => {
                return bun_sys::windows::EXCEPTION_CONTINUE_EXECUTION;
            }

            _ => return bun_sys::windows::EXCEPTION_CONTINUE_SEARCH,
        };
        // SAFETY: kernel provides a valid EXCEPTION_RECORD; ExceptionAddress is
        // the faulting instruction.
        let pc = unsafe { (*info.ExceptionRecord).ExceptionAddress } as usize;
        // Windows: capture_from_context uses RtlCaptureStackBackTrace and trims
        // by `pc`; the frame-pointer slot is unused.
        crash_handler(reason, TraceSeed::Fault { pc, fp: 0 });
    }

    #[cfg(all(target_os = "linux", target_env = "gnu"))]
    unsafe extern "C" {
        fn gnu_get_libc_version() -> *const c_char;
    }

    // Only populated after JSC::VM::tryCreate. C++ writes this as a plain
    // `size_t`; `AtomicUsize` has the same size/alignment as `usize` so the
    // symbol layout is unchanged, and the Rust side reads it race-free.
    #[unsafe(no_mangle)]
    pub(crate) static Bun__reported_memory_size: AtomicUsize = AtomicUsize::new(0);

    pub fn print_metadata(writer: &mut impl Write) -> Result<(), bun_core::Error> {
        #[cfg(debug_assertions)]
        {
            if Output::is_ai_agent() {
                return Ok(());
            }
        }

        if enable_ansi_colors_stderr() {
            writer.write_all(&Output::pretty_fmt::<true>("<r><d>"))?;
        }

        #[cfg(target_arch = "x86_64")]
        let is_ancient_cpu: bool;

        writer.write_all(METADATA_VERSION_LINE.as_bytes())?;
        {
            let cpu_features = CPUFeatures::get();

            // TODO(port): bun_analytics::GenerateHeader::GeneratePlatform
            {
                #[cfg(any(
                    all(target_os = "linux", target_env = "gnu"),
                    target_os = "freebsd",
                    target_os = "macos"
                ))]
                let platform = bun_analytics::GenerateHeader::generate_platform::for_os();
                #[cfg(all(target_os = "linux", target_env = "gnu"))]
                {
                    // SAFETY: gnu_get_libc_version returns a static NUL-terminated string or null
                    let version = unsafe { gnu_get_libc_version() };
                    let version_bytes: &[u8] = if version.is_null() {
                        b""
                    } else {
                        // SAFETY: non-null branch — gnu_get_libc_version returned a valid C string.
                        unsafe { bun_core::ffi::cstr(version) }.to_bytes()
                    };
                    let kernel_version =
                        bun_analytics::GenerateHeader::generate_platform::kernel_version();
                    if platform.os == bun_analytics::schema::analytics::OperatingSystem::Wsl {
                        writeln!(
                            writer,
                            "WSL Kernel v{}.{}.{} | glibc v{}",
                            kernel_version.major,
                            kernel_version.minor,
                            kernel_version.patch,
                            bstr::BStr::new(version_bytes)
                        )
                        .map_err(fmt_err)?;
                    } else {
                        writeln!(
                            writer,
                            "Linux Kernel v{}.{}.{} | glibc v{}",
                            kernel_version.major,
                            kernel_version.minor,
                            kernel_version.patch,
                            bstr::BStr::new(version_bytes)
                        )
                        .map_err(fmt_err)?;
                    }
                }
                #[cfg(all(target_os = "linux", target_env = "musl"))]
                {
                    let kernel_version =
                        bun_analytics::GenerateHeader::generate_platform::kernel_version();
                    write!(
                        writer,
                        "Linux Kernel v{}.{}.{} | musl\n",
                        kernel_version.major, kernel_version.minor, kernel_version.patch
                    )
                    .map_err(fmt_err)?;
                }
                #[cfg(target_os = "android")]
                {
                    let kernel_version =
                        bun_analytics::GenerateHeader::generate_platform::kernel_version();
                    write!(
                        writer,
                        "Android Kernel v{}.{}.{} | bionic\n",
                        kernel_version.major, kernel_version.minor, kernel_version.patch
                    )
                    .map_err(fmt_err)?;
                }
                #[cfg(target_os = "freebsd")]
                {
                    write!(
                        writer,
                        "FreeBSD Kernel v{}\n",
                        bstr::BStr::new(platform.version)
                    )
                    .map_err(fmt_err)?;
                }
                #[cfg(target_os = "macos")]
                {
                    writeln!(writer, "macOS v{}", bstr::BStr::new(platform.version))
                        .map_err(fmt_err)?;
                }
                #[cfg(windows)]
                {
                    // TODO(port): std.zig.system.windows.detectRuntimeVersion()
                    write!(
                        writer,
                        "Windows v{}\n",
                        bun_sys::windows::detect_runtime_version()
                    )
                    .map_err(fmt_err)?;
                }
            } // end  — bun_analytics platform block

            #[cfg(target_arch = "x86_64")]
            {
                is_ancient_cpu = !cpu_features.has_any_avx();
            }

            if !cpu_features.is_empty() {
                writeln!(writer, "CPU: {}", cpu_features).map_err(fmt_err)?;
            }

            write!(writer, "Args: ").map_err(fmt_err)?;
            let mut arg_chars_left: usize = if cfg!(debug_assertions) { 4096 } else { 196 };
            for (i, arg) in bun_core::argv().iter().enumerate() {
                if i != 0 {
                    writer.write_all(b" ")?;
                }
                write!(
                    writer,
                    "{}",
                    bun_fmt::QuotedFormatter {
                        text: &arg[0..arg.len().min(arg_chars_left)]
                    }
                )
                .map_err(fmt_err)?;
                arg_chars_left = arg_chars_left.saturating_sub(arg.len());
                if arg_chars_left == 0 {
                    writer.write_all(b"...")?;
                    break;
                }
            }
        }

        // TODO(port): bun_analytics::Features::formatter
        {
            write!(writer, "\n{}", bun_analytics::features::formatter()).map_err(fmt_err)?;
        }
        writer.write_all(b"\n")?;

        if bun_core::USE_MIMALLOC {
            let mut elapsed_msecs: usize = 0;
            let mut user_msecs: usize = 0;
            let mut system_msecs: usize = 0;
            let mut current_rss: usize = 0;
            let mut peak_rss: usize = 0;
            let mut current_commit: usize = 0;
            let mut peak_commit: usize = 0;
            let mut page_faults: usize = 0;
            // SAFETY: all out-pointers are valid
            unsafe {
                bun_alloc::mimalloc::mi_process_info(
                    &raw mut elapsed_msecs,
                    &raw mut user_msecs,
                    &raw mut system_msecs,
                    &raw mut current_rss,
                    &raw mut peak_rss,
                    &raw mut current_commit,
                    &raw mut peak_commit,
                    &raw mut page_faults,
                );
            }
            writeln!(
                writer,
                "Elapsed: {}ms | User: {}ms | Sys: {}ms",
                elapsed_msecs, user_msecs, system_msecs
            )
            .map_err(fmt_err)?;

            // TODO(port): {B:<3.2} byte-size formatting — bun_fmt::bytes() doesn't take width/prec yet
            write!(
                writer,
                "RSS: {} | Peak: {} | Commit: {} | Faults: {}",
                bun_fmt::bytes(current_rss),
                bun_fmt::bytes(peak_rss),
                bun_fmt::bytes(current_commit),
                page_faults,
            )
            .map_err(fmt_err)?;

            // SAFETY: read-only access to exported global
            let reported = Bun__reported_memory_size.load(Ordering::Relaxed);
            if reported > 0 {
                write!(writer, " | Machine: {}", bun_fmt::bytes(reported)).map_err(fmt_err)?;
            }

            writer.write_all(b"\n")?;
        }

        if enable_ansi_colors_stderr() {
            writer.write_all(&Output::pretty_fmt::<true>("<r>"))?;
        }
        writer.write_all(b"\n")?;

        #[cfg(target_arch = "x86_64")]
        {
            if is_ancient_cpu {
                writer.write_all(
                    b"CPU lacks AVX support. Please consider upgrading to a newer CPU.\n",
                )?;
            }
        }
        Ok(())
    }

    fn wait_for_other_thread_to_finish_panicking() {
        if PANICKING.fetch_sub(1, Ordering::SeqCst) != 1 {
            // Another thread is panicking, wait for the last one to finish
            // and call abort()
            // TODO(port): builtin.single_threaded → unreachable

            // Sleep forever without hammering the CPU
            let futex = AtomicU32::new(0);
            loop {
                bun_threading::Futex::wait_forever(&futex, 0);
            }
        }
    }

    /// Each platform is encoded as a single character. It is placed right after the
    /// slash after the version, so someone just reading the trace string can tell
    /// what platform it came from. L, M, and W are for Linux, macOS, and Windows,
    /// with capital letters indicating aarch64, lowercase indicating x86_64.
    ///
    /// eg: 'https://bun.report/1.1.3/we04c...
    ///                               ^ this tells you it is windows x86_64
    ///
    /// Baseline gets a weirder encoding of a mix of b and e.
    struct Platform;

    impl Platform {
        // TODO(port): Zig builds this via @tagName(os) ++ "_" ++ @tagName(arch) ++ baseline.
        // Rust cannot concat ident names at const time without a proc-macro; spell out the cfg matrix.
        const CURRENT: u8 = {
            // Android folds into the Linux variants — Zig's `@tagName(Environment.os)`
            // (crash_handler.zig:1153) yields `"linux"` for Android because Zig keeps
            // it under `os.tag == .linux`. bun.report decodes the same single-char
            // codes; introducing new ones would break older decoders.
            #[cfg(all(
                any(target_os = "linux", target_os = "android"),
                target_arch = "x86_64",
                not(feature = "baseline")
            ))]
            {
                b'l'
            }
            #[cfg(all(
                any(target_os = "linux", target_os = "android"),
                target_arch = "x86_64",
                feature = "baseline"
            ))]
            {
                b'B'
            }
            #[cfg(all(
                any(target_os = "linux", target_os = "android"),
                target_arch = "aarch64"
            ))]
            {
                b'L'
            }
            #[cfg(all(target_os = "macos", target_arch = "x86_64", not(feature = "baseline")))]
            {
                b'm'
            }
            #[cfg(all(target_os = "macos", target_arch = "x86_64", feature = "baseline"))]
            {
                b'b'
            }
            #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
            {
                b'M'
            }
            #[cfg(all(windows, target_arch = "x86_64", not(feature = "baseline")))]
            {
                b'w'
            }
            #[cfg(all(windows, target_arch = "x86_64", feature = "baseline"))]
            {
                b'e'
            }
            #[cfg(all(windows, target_arch = "aarch64"))]
            {
                b'W'
            }
            #[cfg(all(
                target_os = "freebsd",
                target_arch = "x86_64",
                not(feature = "baseline")
            ))]
            {
                b'f'
            }
            #[cfg(all(target_os = "freebsd", target_arch = "x86_64", feature = "baseline"))]
            {
                b'g'
            }
            #[cfg(all(target_os = "freebsd", target_arch = "aarch64"))]
            {
                b'F'
            }
        };
    }

    /// Note to the decoder on how to process this string. This ensures backwards
    /// compatibility with older versions of the tracestring.
    ///
    /// '1' - original. uses 7 char hash with VLQ encoded stack-frames
    /// '2' - same as '1' but this build is known to be a canary build
    const VERSION_CHAR: &str = if Environment::IS_CANARY { "2" } else { "1" };

    // Zig: `if (git_sha.len > 0) git_sha[0..7] else "unknown"` — the v1/v2 trace-string
    // format encodes exactly 7 hex chars. `Environment::GIT_SHA_SHORT` is 9 chars and would
    // shift every following VLQ byte, making bun.report unable to decode the URL.
    const GIT_SHA: &str = {
        const fn sha7(s: &'static str) -> &'static str {
            let (head, _) = s.as_bytes().split_at(7);
            // SAFETY: GIT_SHA is ASCII hex; the first 7 bytes are a valid UTF-8
            // prefix. `split_at` const-panics if the input is shorter than 7.
            unsafe { core::str::from_utf8_unchecked(head) }
        }
        if !Environment::GIT_SHA.is_empty() {
            sha7(Environment::GIT_SHA)
        } else {
            "unknown"
        }
    };

    struct StackLine {
        address: i32,
        // None -> from bun.exe
        object: Option<Box<[u8]>>,
        // TODO(port): Zig stores a borrowed slice into caller's `name_bytes`; using Box<[u8]> here
        // since the only caller writes into a stack buffer and the value is consumed immediately.
    }

    impl StackLine {
        /// `None` implies the trace is not known.
        pub(crate) fn from_address(addr: usize, name_bytes: &mut [u8]) -> Option<StackLine> {
            #[cfg(windows)]
            {
                let module = bun_sys::windows::get_module_handle_from_address(addr)?;

                let base_address = module as usize;

                let mut temp: [u16; 512] = [0; 512];
                let name = bun_sys::windows::get_module_name_w(module, &mut temp)?;

                let image_path = bun_sys::windows::exe_path_w();

                return Some(StackLine {
                    // To remap this, `pdb-addr2line --exe bun.pdb 0x123456`
                    // Zig: `@intCast(addr - base_address)` — unchecked in ReleaseFast.
                    // Use a wrapping cast so an oversize/underflowed module offset
                    // produces a junk frame instead of panicking *inside* the crash
                    // handler (which would escalate to a double-panic and lose the
                    // entire report).
                    address: addr.wrapping_sub(base_address) as i32,

                    object: if name != image_path.as_slice() {
                        // GetModuleFileNameW output never has a trailing separator
                        // or bare drive prefix, so the std.fs.path.basenameWindows
                        // stripping is a no-op on this domain.
                        let basename = bun_paths::basename_windows(name);
                        Some(Box::<[u8]>::from(
                            &*strings::convert_utf16_to_utf8_in_buffer(name_bytes, basename),
                        ))
                    } else {
                        None
                    },
                });
            }
            #[cfg(target_os = "macos")]
            {
                // This code is slightly modified from std.debug.DebugInfo.lookupModuleNameDyld
                // https://github.com/ziglang/zig/blob/215de3ee67f75e2405c177b262cb5c1cd8c8e343/lib/std/debug.zig#L1783
                let address = if addr == 0 { 0 } else { addr - 1 };

                let image_count = bun_sys::c::_dyld_image_count();

                let mut i: u32 = 0;
                while i < image_count {
                    let header = bun_sys::c::_dyld_get_image_header(i);
                    if header.is_null() {
                        i += 1;
                        continue;
                    }
                    let base_address = header as usize;
                    if address < base_address {
                        i += 1;
                        continue;
                    }
                    // This 'slide' is the ASLR offset. Subtract from `address` to get a stable address
                    let vmaddr_slide = bun_sys::c::_dyld_get_image_vmaddr_slide(i) as usize;

                    // SAFETY: header points to a valid mach_header_64
                    let header_ref = unsafe { &*header };
                    // SAFETY: load commands follow the mach header in memory; the
                    // dyld-mapped image stays live for the process lifetime, so the
                    // iterator's no-realloc/no-free contract is trivially upheld.
                    let mut it =
                        bun_sys::macho::LoadCommandIterator::new(header_ref.ncmds, unsafe {
                            core::slice::from_raw_parts(
                                header
                                    .cast::<u8>()
                                    .add(core::mem::size_of::<bun_sys::macho::mach_header_64>()),
                                header_ref.sizeofcmds as usize,
                            )
                        });

                    while let Some(cmd) = it.next() {
                        match cmd.cmd() {
                            bun_sys::macho::LC_SEGMENT_64 => {
                                let segment_cmd =
                                    cmd.cast::<bun_sys::macho::segment_command_64>().unwrap();
                                if segment_cmd.seg_name() != b"__TEXT" {
                                    continue;
                                }

                                let original_address = address - vmaddr_slide;
                                let seg_start = segment_cmd.vmaddr as usize;
                                let seg_end = seg_start + segment_cmd.vmsize as usize;
                                if original_address >= seg_start && original_address < seg_end {
                                    // Subtract ASLR value for stable address
                                    let stable_address: usize = address - vmaddr_slide;

                                    if i == 0 {
                                        let image_relative_address = stable_address - seg_start;
                                        if image_relative_address > i32::MAX as usize {
                                            return None;
                                        }

                                        // To remap this, you have to add the offset (which is going to be 0x100000000),
                                        // and then you can run it through `llvm-symbolizer --obj bun-with-symbols 0x123456`
                                        // The reason we are subtracting this known offset is mostly just so that we can
                                        // fit it within a signed 32-bit integer. The VLQs will be shorter too.
                                        return Some(StackLine {
                                            object: None,
                                            address: i32::try_from(image_relative_address)
                                                .expect("int cast"),
                                        });
                                    } else {
                                        // these libraries are not interesting, mark as unknown
                                        return None;
                                    }
                                }
                            }
                            _ => {}
                        }
                    }
                    i += 1;
                }

                let _ = name_bytes;
                return None;
            }
            #[cfg(not(any(windows, target_os = "macos")))]
            {
                // This code is slightly modified from std.debug.DebugInfo.lookupModuleDl
                // https://github.com/ziglang/zig/blob/215de3ee67f75e2405c177b262cb5c1cd8c8e343/lib/std/debug.zig#L2024
                let _ = name_bytes;
                let address = addr.saturating_sub(1);
                let m = bun_sys::elf::find_loaded_module(address)?;
                return Some(StackLine {
                    address: i32::try_from(address - m.base_address).expect("int cast"),
                    object: None,
                });
            }
        }

        pub(crate) fn write_encoded(
            self_: Option<&StackLine>,
            writer: &mut impl Write,
        ) -> Result<(), bun_core::Error> {
            let Some(known) = self_ else {
                writer.write_all(b"_")?;
                return Ok(());
            };

            if let Some(object) = &known.object {
                writer.write_all(VLQ::encode(1).slice())?;
                writer.write_all(
                    VLQ::encode(i32::try_from(object.len()).expect("int cast")).slice(),
                )?;
                writer.write_all(object)?;
            }

            writer.write_all(VLQ::encode(known.address).slice())?;
            Ok(())
        }
    }

    impl fmt::Display for StackLine {
        fn fmt(&self, writer: &mut fmt::Formatter<'_>) -> fmt::Result {
            let addr_display: u64 = if cfg!(target_os = "macos") {
                self.address as u64 + 0x100000000
            } else {
                self.address as u64
            };
            write!(
                writer,
                "0x{:x}{}{}",
                addr_display,
                if self.object.is_some() { " @ " } else { "" },
                self.object
                    .as_deref()
                    .map(bstr::BStr::new)
                    .unwrap_or_default(),
            )
        }
    }

    struct TraceString<'a> {
        trace: &'a StackTrace<'a>,
        reason: CrashReason,
        action: TraceStringAction,
    }

    #[derive(Clone, Copy, PartialEq, Eq)]
    enum TraceStringAction {
        /// Open a pre-filled GitHub issue with the expanded trace
        OpenIssue,
        /// View the trace with nothing else
        ViewTrace,
    }

    impl<'a> fmt::Display for TraceString<'a> {
        fn fmt(&self, writer: &mut fmt::Formatter<'_>) -> fmt::Result {
            // encode_trace_string takes a byte writer; bridge fmt::Formatter via adapter
            let _ = encode_trace_string(self, &mut FmtAdapter::new(writer));
            Ok(())
        }
    }

    fn encode_trace_string(
        opts: &TraceString<'_>,
        writer: &mut impl Write,
    ) -> Result<(), bun_core::Error> {
        writer.write_all(report_base_url())?;
        writer.write_all(b"/")?;
        writer.write_all(Environment::VERSION_STRING.as_bytes())?;
        writer.write_all(b"/")?;
        writer.write_all(&[Platform::CURRENT])?;
        writer.write_byte(cli_state::cmd_char().unwrap_or(b'_'))?;

        writer.write_all(VERSION_CHAR.as_bytes())?;
        writer.write_all(GIT_SHA.as_bytes())?;

        let packed_features: u64 = bun_analytics::packed_features().bits();
        write_u64_as_two_vlqs(writer, packed_features as usize)?;

        let mut name_bytes: [u8; 1024] = [0; 1024];

        for &addr in &opts.trace.instruction_addresses[0..opts.trace.index] {
            let line = StackLine::from_address(addr, &mut name_bytes);
            StackLine::write_encoded(line.as_ref(), writer)?;
        }

        writer.write_all(VLQ::ZERO.slice())?;

        // The following switch must be kept in sync with `bun.report`'s decoder implementation.
        match opts.reason {
            CrashReason::Panic(message) => {
                writer.write_byte(b'0')?;

                let mut compressed_bytes: [u8; 2048] = [0; 2048];
                let mut len: bun_zlib::uLong = compressed_bytes.len() as bun_zlib::uLong;
                let ret = {
                    bun_zlib::compress2(
                        compressed_bytes.as_mut_ptr(),
                        &raw mut len,
                        message.as_ptr(),
                        u32::try_from(message.len()).expect("int cast") as bun_zlib::uLong,
                        9,
                    )
                };
                // Match on the raw zlib return code so this stays ABI-correct
                // regardless of whether the platform `compress2` binding returns
                // `c_int` (posix) or the `ReturnCode` enum (win32).
                let compressed = match ret as i32 {
                    r if r == bun_zlib::ReturnCode::Ok as i32 => {
                        &compressed_bytes[0..usize::try_from(len).expect("int cast")]
                    }
                    // Insufficient memory.
                    r if r == bun_zlib::ReturnCode::MemError as i32 => {
                        return Err(bun_core::err!("OutOfMemory"));
                    }
                    // The buffer dest was not large enough to hold the compressed data.
                    r if r == bun_zlib::ReturnCode::BufError as i32 => {
                        return Err(bun_core::err!("NoSpaceLeft"));
                    }
                    // The level was not Z_DEFAULT_LEVEL, or was not between 0 and 9.
                    // This is technically possible but impossible because we pass 9.
                    _ => return Err(bun_core::err!("Unexpected")),
                };

                let mut b64_bytes: [u8; 2048] = [0; 2048];
                if bun_base64::encode_len(compressed) > b64_bytes.len() {
                    return Err(bun_core::err!("NoSpaceLeft"));
                }
                let b64_len = bun_base64::encode(&mut b64_bytes, compressed);

                writer.write_all(strings::trim_right(&b64_bytes[0..b64_len], b"="))?;
            }

            CrashReason::Unreachable => writer.write_byte(b'1')?,

            CrashReason::SegmentationFault(addr) => {
                writer.write_byte(b'2')?;
                write_u64_as_two_vlqs(writer, addr)?;
            }
            CrashReason::IllegalInstruction(addr) => {
                writer.write_byte(b'3')?;
                write_u64_as_two_vlqs(writer, addr)?;
            }
            CrashReason::BusError(addr) => {
                writer.write_byte(b'4')?;
                write_u64_as_two_vlqs(writer, addr)?;
            }
            CrashReason::FloatingPointError(addr) => {
                writer.write_byte(b'5')?;
                write_u64_as_two_vlqs(writer, addr)?;
            }

            CrashReason::DatatypeMisalignment => writer.write_byte(b'6')?,
            CrashReason::StackOverflow => writer.write_byte(b'7')?,

            CrashReason::ZigError(err) => {
                writer.write_byte(b'8')?;
                writer.write_all(err.name().as_bytes())?;
            }

            CrashReason::OutOfMemory => writer.write_byte(b'9')?,
        }

        if opts.action == TraceStringAction::ViewTrace {
            writer.write_all(b"/view")?;
        }
        Ok(())
    }

    pub fn write_u64_as_two_vlqs(
        writer: &mut impl Write,
        addr: usize,
    ) -> Result<(), bun_core::Error> {
        // @bitCast(@as(u32, ...)) → reinterpret u32 as i32
        let first = VLQ::encode((((addr as u64) & 0xFFFFFFFF00000000) >> 32) as u32 as i32);
        let second = VLQ::encode(((addr as u64) & 0xFFFFFFFF) as u32 as i32);
        writer.write_all(first.slice())?;
        writer.write_all(second.slice())?;
        Ok(())
    }

    fn is_reporting_enabled() -> bool {
        if SUPPRESS_REPORTING.load(Ordering::Relaxed) {
            return false;
        }

        // If trying to test the crash handler backend, implicitly enable reporting
        if let Some(value) = env_var::BUN_CRASH_REPORT_URL::get() {
            return !value.is_empty();
        }

        // Environment variable to specifically enable or disable reporting
        if let Some(enable_crash_reporting) = env_var::BUN_ENABLE_CRASH_REPORTING::get() {
            return enable_crash_reporting;
        }

        // Debug builds shouldn't report to the default url by default
        if cfg!(debug_assertions) {
            return false;
        }

        if Environment::ENABLE_ASAN {
            return false;
        }

        // Honor DO_NOT_TRACK
        // TODO(port): bun_analytics::is_enabled
        if env_var::DO_NOT_TRACK::get() == Some(true) {
            return false;
        }

        if Environment::IS_CANARY {
            return true;
        }

        // Change in v1.1.10: enable crash reporter auto upload on macOS and Windows.
        if cfg!(target_os = "macos") || cfg!(windows) {
            return true;
        }

        false
    }

    /// Bun automatically reports crashes on Windows and macOS
    ///
    /// These URLs contain no source code or personally-identifiable
    /// information (PII). The stackframes point to Bun's open-source native code
    /// (not user code), and are safe to share publicly and with the Bun team.
    fn report(url: &[u8]) {
        if !is_reporting_enabled() {
            return;
        }
        #[cfg(windows)]
        {
            // TODO(port): bun_sys::windows::PROCESS_INFORMATION / STARTUPINFOW / CreateProcessW
            // TODO(port): bun_core::w! / strings::convert_utf8_to_utf16_in_buffer
            use bun_sys::windows;
            let mut process: windows::PROCESS_INFORMATION = bun_core::ffi::zeroed();
            let mut startup_info = windows::STARTUPINFOW {
                cb: core::mem::size_of::<windows::STARTUPINFOW>() as u32,
                lpReserved: core::ptr::null_mut(),
                lpDesktop: core::ptr::null_mut(),
                lpTitle: core::ptr::null_mut(),
                dwX: 0,
                dwY: 0,
                dwXSize: 0,
                dwYSize: 0,
                dwXCountChars: 0,
                dwYCountChars: 0,
                dwFillAttribute: 0,
                dwFlags: 0,
                wShowWindow: 0,
                cbReserved2: 0,
                lpReserved2: core::ptr::null_mut(),
                hStdInput: core::ptr::null_mut(),
                hStdOutput: core::ptr::null_mut(),
                hStdError: core::ptr::null_mut(),
                // .hStdInput = bun.FD.stdin().native(),
                // .hStdOutput = bun.FD.stdout().native(),
                // .hStdError = bun.FD.stderr().native(),
            };
            let mut cmd_line = BoundedArray::<u16, 4096>::default();
            cmd_line.append_slice_assume_capacity(bun_core::w!(
                "powershell -ExecutionPolicy Bypass -Command \"try{Invoke-RestMethod -Uri '"
            ));
            // PERF(port): was assume_capacity
            {
                // `unused_capacity_slice` is `&mut [MaybeUninit<u16>]`;
                // `from_raw_parts_mut::<u16>` over that storage would assert the
                // bytes are already initialized (library-UB even though
                // `convert_utf8_to_utf16_in_buffer` only writes). Zero-fill the
                // spare slots first so the `&mut [u16]` we hand to simdutf is over
                // initialized memory. Cold crash-reporter path — the extra memset
                // is irrelevant.
                let spare = cmd_line.unused_capacity_slice();
                for slot in spare.iter_mut() {
                    slot.write(0);
                }
                let cap = spare.len();
                // SAFETY: every `MaybeUninit<u16>` in `spare` was just written
                // above; `dst..dst+cap` is now `cap` initialized `u16`s inside one
                // allocation.
                let init = unsafe {
                    core::slice::from_raw_parts_mut(spare.as_mut_ptr().cast::<u16>(), cap)
                };
                let encoded_len = strings::convert_utf8_to_utf16_in_buffer(init, url).len();
                let _ = cmd_line.resize(cmd_line.len() + encoded_len);
            }
            if cmd_line
                .append_slice(bun_core::w!("/ack'|out-null}catch{}\""))
                .is_err()
            {
                return;
            }
            if cmd_line.append(0).is_err() {
                return;
            }
            // SAFETY: we just wrote a NUL terminator at len-1
            let end = cmd_line.len() - 1;
            let cmd_line_slice = &mut cmd_line.slice()[0..end];
            // TODO(port): need [:0] sentinel slice — pass raw pointer
            // SAFETY: all pointer args are either null or point to stack-local buffers/structs valid for the duration of the call; cmd_line is NUL-terminated above
            let spawn_result = unsafe {
                windows::kernel32::CreateProcessW(
                    core::ptr::null(),
                    cmd_line_slice.as_mut_ptr(),
                    core::ptr::null_mut(),
                    core::ptr::null_mut(),
                    1, // true
                    0,
                    core::ptr::null_mut(),
                    core::ptr::null(),
                    &mut startup_info,
                    &mut process,
                )
            };

            // we don't care what happens with the process
            // NOTE: on success `CreateProcessW` returns two open kernel handles in
            // `process.hProcess` / `process.hThread` that the caller is meant to
            // `CloseHandle`. The Zig spec leaks them identically (crash_handler.zig:
            // 1545-1546 `_ = spawn_result;`); `report()` runs immediately before
            // `crash()` → `ExitProcess(3)`, so the kernel reclaims them anyway.
            let _ = spawn_result;
            let _ = url;
        }
        #[cfg(any(
            target_os = "macos",
            target_os = "linux",
            target_os = "android",
            target_os = "freebsd"
        ))]
        {
            let mut buf = bun_core::PathBuffer::default();
            let mut buf2 = bun_core::PathBuffer::default();
            let Some(path_env) = env_var::PATH::get() else {
                return;
            };
            let Ok(cwd) = bun_core::getcwd(&mut buf2) else {
                return;
            };
            // PORT NOTE: reshaped for borrowck — capture cwd bytes by value (it
            // borrows buf2, not buf, so no actual overlap; copy len for clarity).
            let cwd_bytes = cwd.as_bytes();
            let Some(curl) = bun_which::which(&mut buf, path_env, cwd_bytes, b"curl") else {
                return;
            };
            let mut cmd_line = BoundedArray::<u8, 4096>::default();
            if cmd_line.append_slice(url).is_err() {
                return;
            }
            if cmd_line.append_slice(b"/ack").is_err() {
                return;
            }
            if cmd_line.append(0).is_err() {
                return;
            }

            let argv: [*const c_char; 4] = [
                curl.as_ptr(),
                c"-fsSL".as_ptr(),
                cmd_line.const_slice().as_ptr().cast(),
                core::ptr::null(),
            ];
            // SAFETY: fork is async-signal-safe; we're already in the crash path
            let result = unsafe { libc::fork() };
            match result {
                // child
                0 => {
                    for i in 0..2 {
                        // SAFETY: closing stdin/stdout in child
                        unsafe {
                            libc::close(i);
                        }
                    }
                    // SAFETY: argv is NUL-terminated array of NUL-terminated strings; environ is the
                    // process environment block
                    unsafe {
                        libc::execve(argv[0], argv.as_ptr(), bun_core::c_environ());
                    }
                    // SAFETY: _exit is async-signal-safe in the forked child
                    unsafe {
                        libc::_exit(0);
                    }
                }
                // success and failure cases: ignore the result
                _ => {}
            }
        }
        // TODO(port): wasm @compileError("Not implemented")
        #[cfg(not(unix))]
        let _ = url;
    }

    /// Crash. Make sure segfault handlers are off so that this doesnt trigger the crash handler.
    /// This causes a segfault on posix systems to try to get a core dump.
    fn crash() -> ! {
        #[cfg(not(windows))]
        {
            // Install default handler so that the tkill below will terminate.
            // Zig: std.posix.Sigaction{ .handler = SIG.DFL, .mask = sigemptyset(), .flags = 0 }.
            // bun_sys::posix has no Sigaction yet — use libc directly (async-signal-safe).
            // SAFETY: all-zero is a valid sigaction (handler = SIG_DFL = 0, flags = 0).
            let mut sigact: libc::sigaction = bun_core::ffi::zeroed();
            sigact.sa_sigaction = libc::SIG_DFL;
            // SAFETY: sa_mask is a valid out-pointer into a zeroed struct.
            unsafe {
                libc::sigemptyset(&raw mut sigact.sa_mask);
            }
            for sig in [
                libc::SIGSEGV,
                libc::SIGILL,
                libc::SIGBUS,
                libc::SIGABRT,
                libc::SIGFPE,
                libc::SIGHUP,
                libc::SIGTERM,
            ] {
                // SAFETY: &sigact is a valid sigaction; null oldact is permitted.
                unsafe {
                    libc::sigaction(sig, &raw const sigact, core::ptr::null_mut());
                }
            }
            // Zig: `@trap()` — emits ud2 (x86_64 → SIGILL) / brk (aarch64 → SIGTRAP).
            // `core::intrinsics::abort()` lowers to the same trap instruction, preserving
            // the Zig exit signal. Do NOT use `libc::abort()` here — that raises SIGABRT
            // (exit 134), which is the *Windows* path's behaviour.
            core::intrinsics::abort();
        }
        #[cfg(windows)]
        {
            // Node.js exits with code 134 (128 + SIGABRT) instead. We use abort() as it
            // includes a breakpoint which makes crashes easier to debug.
            //
            // Zig spec (crash_handler.zig:1592): the `.windows` arm is literally
            // `std.posix.abort();` — i.e. our same-module `abort()` helper, which on
            // Windows is `@breakpoint()` (Debug only) then `kernel32.ExitProcess(3)`.
            // Do NOT call MSVCRT `libc::abort()` here — that raises SIGABRT, may print
            // the CRT `abort() has been called` message, and can invoke WER.
            abort()
        }
    }

    pub static VERBOSE_ERROR_TRACE: AtomicBool = AtomicBool::new(false);

    #[cold]
    #[inline(never)]
    fn cold_handle_error_return_trace<const IS_ROOT: bool>(
        err_int_workaround_for_zig_ccall_bug: u16,
        trace: &StackTrace,
    ) {
        // TODO(port): std.meta.Int(.unsigned, @bitSizeOf(anyerror)) — bun_core::Error is errno-based
        let err = bun_core::Error::from_errno(err_int_workaround_for_zig_ccall_bug as i32);

        // The format of the panic trace is slightly different in debug
        // builds Mainly, we demangle the backtrace immediately instead
        // of using a trace string.
        //
        // To make the release-mode behavior easier to demo, debug mode
        // checks for this CLI flag.
        let is_debug = cfg!(debug_assertions)
            && 'check_flag: {
                for arg in Output::argv() {
                    if arg == b"--debug-crash-handler-use-trace-string" {
                        break 'check_flag false;
                    }
                }
                true
            };

        if is_debug {
            if IS_ROOT {
                // SAFETY: read-only access
                if VERBOSE_ERROR_TRACE.load(Ordering::Relaxed) {
                    Output::note("Release build will not have this trace by default:");
                }
            } else {
                bun_core::pretty_errorln!(
                    "<blue>note<r><d>:<r> caught error.{}:",
                    bstr::BStr::new(err.name())
                );
            }
            Output::flush();
            dump_stack_trace(trace, WriteStackTraceLimits::default());
        } else {
            let ts = TraceString {
                trace,
                reason: CrashReason::ZigError(err),
                action: TraceStringAction::ViewTrace,
            };
            if IS_ROOT {
                bun_core::pretty_errorln!(
                    "\nTo send a redacted crash report to Bun's team,\nplease file a GitHub issue using the link below:\n\n <cyan>{}<r>\n",
                    ts,
                );
            } else {
                bun_core::pretty_errorln!(
                    "<cyan>trace<r>: error.{}: <d>{}<r>",
                    bstr::BStr::new(err.name()),
                    ts,
                );
            }
        }
    }

    #[inline]
    fn handle_error_return_trace_extra<const IS_ROOT: bool>(
        err: bun_core::Error,
        maybe_trace: Option<&StackTrace>,
    ) {
        // TODO(port): builtin.have_error_return_tracing — Rust has no error-return tracing;
        // decide whether to keep this entire mechanism or strip it.
        if !debug::HAVE_ERROR_RETURN_TRACING {
            return;
        }
        // SAFETY: read-only access
        if !VERBOSE_ERROR_TRACE.load(Ordering::Relaxed) && !IS_ROOT {
            return;
        }

        if let Some(trace) = maybe_trace {
            cold_handle_error_return_trace::<IS_ROOT>(err.as_u16(), trace);
        }
    }

    /// In many places we catch errors, the trace for them is absorbed and only a
    /// single line (the error name) is printed. When this is set, we will print
    /// trace strings for those errors (or full stacks in debug builds).
    ///
    /// This can be enabled by passing `--verbose-error-trace` to the CLI.
    /// In release builds with error return tracing enabled, this is also exposed.
    /// You can test if this feature is available by checking `bun --help` for the flag.
    #[inline]
    pub fn handle_error_return_trace(err: bun_core::Error, maybe_trace: Option<&StackTrace>) {
        handle_error_return_trace_extra::<false>(err, maybe_trace);
    }

    unsafe extern "C" {
        fn WTF__DumpStackTrace(ptr: *const usize, count: usize);
    }

    /// Version of the standard library dumpStackTrace that has some fallbacks for
    /// cases where such logic fails to run.
    pub fn dump_stack_trace(trace: &StackTrace, limits: WriteStackTraceLimits) {
        Output::flush();
        let stderr = &mut stderr_writer();
        if !Environment::SHOW_CRASH_TRACE {
            // debug symbols aren't available, lets print a tracestring
            let _ = writeln!(
                stderr,
                "View Debug Trace: {}",
                TraceString {
                    action: TraceStringAction::ViewTrace,
                    reason: CrashReason::ZigError(bun_core::err!("DumpStackTrace")),
                    trace,
                }
            );
            return;
        }

        #[cfg(windows)]
        'attempt_dump: {
            // Windows has issues with opening the PDB file sometimes.
            let debug_info = match debug::get_self_debug_info() {
                // SAFETY: lazy debug-only singleton; sole `&mut` for the dump below.
                Ok(d) => unsafe { &mut *d },
                Err(err) => {
                    // Zig: `stderr.print(..) catch return;` — if stderr write fails
                    // (e.g. broken pipe), bail out entirely; don't fall through.
                    if write!(stderr, "Unable to dump stack trace: Unable to open debug info: {}\nFallback trace:\n", bstr::BStr::new(err.name())).is_err() { return; }
                    break 'attempt_dump;
                }
            };
            match write_stack_trace(
                trace,
                stderr,
                debug_info,
                debug::detect_tty_config_stderr(),
                &limits,
            ) {
                Ok(()) => return,
                Err(err) => {
                    if write!(
                        stderr,
                        "Unable to dump stack trace: {}\nFallback trace:\n",
                        bstr::BStr::new(err.name())
                    )
                    .is_err()
                    {
                        return;
                    }
                    break 'attempt_dump;
                }
            }
        }
        #[cfg(any(target_os = "linux", target_os = "android"))]
        {
            // In non-debug builds, use WTF's stack trace printer and return early
            if !cfg!(debug_assertions) {
                // SAFETY: trace.instruction_addresses is a valid slice of `index` entries
                unsafe {
                    WTF__DumpStackTrace(trace.instruction_addresses.as_ptr(), trace.index);
                }
                return;
            }
            // Otherwise fall through to llvm-symbolizer for debug builds
        }
        #[cfg(not(any(windows, target_os = "linux", target_os = "android")))]
        {
            // Assume debug symbol tooling is reliable.
            let debug_info = match debug::get_self_debug_info() {
                // SAFETY: lazy debug-only singleton; sole `&mut` for the dump below.
                Ok(d) => unsafe { &mut *d },
                Err(err) => {
                    let _ = writeln!(
                        stderr,
                        "Unable to dump stack trace: Unable to open debug info: {}",
                        bstr::BStr::new(err.name())
                    );
                    return;
                }
            };
            match write_stack_trace(
                trace,
                stderr,
                debug_info,
                debug::detect_tty_config_stderr(),
                &limits,
            ) {
                Ok(()) => return,
                Err(err) => {
                    let _ = write!(
                        stderr,
                        "Unable to dump stack trace: {}",
                        bstr::BStr::new(err.name())
                    );
                    return;
                }
            }
        }

        #[cfg(any(windows, target_os = "linux", target_os = "android"))]
        {
            let programs: &[&bun_core::ZStr] = if cfg!(windows) {
                &[bun_core::zstr!("pdb-addr2line")]
            } else {
                // if `llvm-symbolizer` doesn't work, also try `llvm-symbolizer-21`
                &[
                    bun_core::zstr!("llvm-symbolizer"),
                    bun_core::zstr!("llvm-symbolizer-21"),
                ]
            };
            for &program in programs {
                // PERF(port): was arena bulk-free + StackFallbackAllocator — using global allocator here.
                // Only stop once a symbolizer actually ran and exited 0. Any failure
                // (not found, spawn error, or non-zero exit) tries the next program and
                // ultimately falls through to the WTF fallback below — a found-but-broken
                // symbolizer must not leave the crash report with no trace at all.
                match spawn_symbolizer(program, trace) {
                    Ok(()) => return,
                    Err(_) => continue,
                }
            }
            let _ = limits;
            // INTENTIONAL DIVERGENCE from Zig spec (crash_handler.zig:1749-1760 falls
            // off the end of the `for (programs)` loop with no further fallback). On
            // Windows, `spawn_sync_inherit` is stubbed and `pdb-addr2line` is rarely
            // installed, so without this the user would get *only* "Fallback trace:"
            // and nothing else. Hand the raw addresses to WTF (always linked) so there
            // is at least some trace. Windows crash-trace snapshot tests must account
            // for this extra output.
            // SAFETY: trace.instruction_addresses is a valid slice of `index` entries
            unsafe {
                WTF__DumpStackTrace(trace.instruction_addresses.as_ptr(), trace.index);
            }
        }
    }

    #[cfg(any(windows, target_os = "linux", target_os = "android"))]
    fn spawn_symbolizer(
        program: &bun_core::ZStr,
        trace: &StackTrace,
    ) -> Result<(), bun_core::Error> {
        // TODO(port): narrow error set
        let mut argv: Vec<Vec<u8>> = Vec::new();
        argv.push(program.as_bytes().to_vec());
        argv.push(b"--exe".to_vec());
        argv.push({
            #[cfg(windows)]
            {
                // `to_utf8_alloc` is infallible (Vec<u8>); the Zig version returned
                // `![]u8` only for OOM, which Rust handles via abort.
                let image_path = strings::to_utf8_alloc(bun_sys::windows::exe_path_w());
                let mut s = image_path[0..image_path.len() - 3].to_vec();
                s.extend_from_slice(b"pdb");
                s
            }
            #[cfg(not(windows))]
            {
                bun_core::self_exe_path()?.as_bytes().to_vec()
            }
        });

        let mut name_bytes: [u8; 1024] = [0; 1024];
        for &addr in &trace.instruction_addresses[0..trace.index] {
            let Some(line) = StackLine::from_address(addr, &mut name_bytes) else {
                continue;
            };
            argv.push(format!("0x{:X}", line.address).into_bytes());
        }

        // PORTING.md: no std::process — routed through bun_core::spawn_sync_inherit (posix_spawn).
        let stderr = &mut stderr_writer();
        let result = bun_core::spawn_sync_inherit(&argv).inspect_err(|_err| {
        let _ = stderr.write_all(b"Failed to invoke command: ");
        let _ = fmt_argv(stderr, &argv);
        let _ = stderr.write_all(b"\n");
        if cfg!(windows) {
            let _ = stderr.write_all(b"(You can compile pdb-addr2line from https://github.com/oven-sh/bun.report, cd pdb-addr2line && cargo build)\n");
        }
    })?;

        if !result.is_ok() {
            let _ = stderr.write_all(b"Failed to invoke command: ");
            let _ = fmt_argv(stderr, &argv);
            let _ = stderr.write_all(b"\n");
            return Err(bun_core::err!("Unexpected"));
        }
        Ok(())
    }

    pub fn dump_current_stack_trace(first_address: Option<usize>, limits: WriteStackTraceLimits) {
        let mut addrs: [usize; 32] = [0; 32];
        let n = debug::capture_stack_trace(
            first_address.unwrap_or_else(debug::return_address),
            &mut addrs,
        );
        let stack = StackTrace {
            index: n,
            instruction_addresses: &addrs,
        };
        dump_stack_trace(&stack, limits);
    }

    /// If POSIX, and the existing soft limit for core dumps (ulimit -Sc) is nonzero, change it to zero.
    /// Used in places where we intentionally crash for testing purposes so that we don't clutter CI
    /// with core dumps.
    pub fn suppress_core_dumps_if_necessary() {
        #[cfg(unix)]
        {
            // Zig: std.posix.getrlimit / setrlimit. bun_sys::posix has no rlimit
            // surface yet — go straight to libc (already a dep, async-signal-safe).
            // SAFETY: all-zero rlimit is valid POD; getrlimit/setrlimit only read/write the struct.
            let mut existing_limit: libc::rlimit = bun_core::ffi::zeroed();
            // SAFETY: &mut existing_limit is a valid out-pointer.
            if unsafe { libc::getrlimit(libc::RLIMIT_CORE, &raw mut existing_limit) } != 0 {
                return;
            }
            if existing_limit.rlim_cur > 0 || existing_limit.rlim_cur == libc::RLIM_INFINITY {
                existing_limit.rlim_cur = 0;
                // SAFETY: &existing_limit is a valid in-pointer.
                unsafe {
                    libc::setrlimit(libc::RLIMIT_CORE, &raw const existing_limit);
                }
            }
        }
    }

    /// From now on, prevent crashes from being reported to bun.report or the URL overridden in
    /// BUN_CRASH_REPORT_URL. Should only be used for tests that are going to intentionally crash,
    /// so that they do not fail CI due to having a crash reported. And those cases should guard behind
    /// a feature flag and call right before the crash, in order to make sure that crashes other than
    /// the expected one are not suppressed.
    pub fn suppress_reporting() {
        suppress_core_dumps_if_necessary();
        SUPPRESS_REPORTING.store(true, Ordering::Relaxed);
    }

    // src/ptr/ref_count.rs:16). Re-export so `bun_crash_handler::StoredTrace` paths
    // keep compiling. NOTE: if `debug::return_address()` is ever wired to a real
    // `@returnAddress()` intrinsic, apply that improvement in bun_core's
    // `StoredTrace::capture()` instead — this crate no longer owns the type.
    pub use bun_core::StoredTrace;

    // TODO(port): move to *_jsc — `pub const js_bindings = @import("../runtime/api/crash_handler_jsc.zig").js_bindings;`
    // Per PORTING.md this *_jsc alias is deleted; the bindings live as an extension trait in bun_runtime.

    /// For large codebases such as bun.bake.DevServer, it may be helpful
    /// to dump a large amount of state to a file to aid debugging a crash.
    ///
    /// Pre-crash handlers are likely, but not guaranteed to call. Errors are ignored.
    pub fn append_pre_crash_handler<T: 'static>(
        ptr: *mut T,
        handler: fn(&mut T) -> Result<(), bun_core::Error>,
    ) -> Result<(), bun_alloc::AllocError> {
        // Zig monomorphizes a `wrap.onCrash` that casts the opaque ptr back to *T and calls
        // `handler`. Rust can't capture `handler` in a bare `fn` item, so box a closure that
        // performs the same cast+call. Errors are intentionally swallowed (best-effort dump).
        let on_crash = Box::new(move |opaque_ptr: *mut c_void| {
            // SAFETY: `opaque_ptr` is the `ptr.cast()` stored below; it was a valid *mut T
            // when registered and remove_pre_crash_handler() unregisters it before drop.
            let this = unsafe { bun_ptr::callback_ctx::<T>(opaque_ptr) };
            let _ = handler(this);
        });

        BEFORE_CRASH_HANDLERS
            .lock()
            .push(CrashHandlerEntry(ptr.cast(), on_crash));
        Ok(())
    }

    pub fn remove_pre_crash_handler(ptr: *mut c_void) {
        let mut list = BEFORE_CRASH_HANDLERS.lock();
        let index = 'find: {
            for (i, item) in list.iter().enumerate() {
                if item.0 == ptr {
                    break 'find i;
                }
            }
            return;
        };
        let _ = list.remove(index);
    }

    pub(crate) struct SourceAtAddress {
        pub source_location: Option<SourceLocation>,
        pub symbol_name: Box<[u8]>,
        pub compile_unit_name: Box<[u8]>,
        // TODO(port): Zig stores borrowed slices owned by debug_info; using Box<[u8]> here.
    }

    // PORT NOTE: Zig's `SourceAtAddress.deinit` only freed `source_location.file_name`;
    // `Option<SourceLocation>` owns it as `Box<[u8]>` so Drop handles it — no explicit deinit.

    // D130: deduped — canonical def lives in bun_core (T0). Re-export under the
    // Zig-spec name so internal use-sites and any downstream
    // `bun_crash_handler::WriteStackTraceLimits` importers keep compiling.
    pub use bun_core::DumpStackTraceOptions as WriteStackTraceLimits;

    /// Clone of `debug.writeStackTrace`, but can be configured to stop at either a
    /// frame count, or when hitting jsc LLInt Additionally, the printing function
    /// does not print the `^`, instead it highlights the word at the column. This
    /// Makes each frame take up two lines instead of three.
    pub fn write_stack_trace(
        stack_trace: &StackTrace,
        out_stream: &mut impl Write,
        debug_info: &mut SelfInfo,
        tty_config: TtyConfig,
        limits: &WriteStackTraceLimits,
    ) -> Result<(), bun_core::Error> {
        if debug::STRIP_DEBUG_INFO {
            return Err(bun_core::err!("MissingDebugInfo"));
        }
        let mut frame_index: usize = 0;
        let mut frames_left: usize = stack_trace
            .index
            .min(stack_trace.instruction_addresses.len());

        // PORT NOTE: Zig's `while (...) : ({ frames_left -= 1; frame_index = ... })` continue-expression
        // is inlined at every `continue` site and at end-of-loop below.
        while frames_left != 0 {
            if frame_index >= limits.frame_count {
                break;
            }
            let return_address = stack_trace.instruction_addresses[frame_index];
            let source = match get_source_at_address(debug_info, return_address - 1)? {
                Some(s) => s,
                None => {
                    let module_name = debug_info.get_module_name_for_address(return_address - 1);
                    print_line_info(
                        out_stream,
                        None,
                        return_address - 1,
                        b"???",
                        module_name.as_deref().unwrap_or(b"???"),
                        tty_config,
                    )?;
                    frames_left -= 1;
                    frame_index = (frame_index + 1) % stack_trace.instruction_addresses.len();
                    continue;
                }
            };

            let mut should_continue = false;
            if limits.skip_stdlib {
                if let Some(sl) = &source.source_location {
                    if strings::includes(&sl.file_name, b"lib/std") {
                        should_continue = true;
                    }
                }
            }
            for &pattern in limits.skip_file_patterns {
                if let Some(sl) = &source.source_location {
                    if strings::includes(&sl.file_name, pattern) {
                        should_continue = true;
                    }
                }
            }
            for &pattern in limits.skip_function_patterns {
                if strings::includes(&source.symbol_name, pattern) {
                    should_continue = true;
                }
            }
            if should_continue {
                frames_left -= 1;
                frame_index = (frame_index + 1) % stack_trace.instruction_addresses.len();
                continue;
            }
            if limits.stop_at_jsc_llint && strings::includes(&source.symbol_name, b"_llint_") {
                break;
            }

            print_line_info(
                out_stream,
                source.source_location.as_ref(),
                return_address - 1,
                &source.symbol_name,
                &source.compile_unit_name,
                tty_config,
            )?;

            frames_left -= 1;
            frame_index = (frame_index + 1) % stack_trace.instruction_addresses.len();
        }

        if stack_trace.index > stack_trace.instruction_addresses.len() {
            let dropped_frames = stack_trace.index - stack_trace.instruction_addresses.len();

            let _ = tty_config.set_color(out_stream, Color::Bold);
            writeln!(
                out_stream,
                "({} additional stack frames not recorded...)",
                dropped_frames
            )
            .map_err(fmt_err)?;
            let _ = tty_config.set_color(out_stream, Color::Reset);
        } else if frames_left != 0 {
            let _ = tty_config.set_color(out_stream, Color::Bold);
            writeln!(
                out_stream,
                "({} additional stack frames skipped...)",
                frames_left
            )
            .map_err(fmt_err)?;
            let _ = tty_config.set_color(out_stream, Color::Reset);
        }
        let _ = out_stream.write_all(b"\n");
        Ok(())
    }

    /// Clone of `debug.printSourceAtAddress` but it returns the metadata as well.
    pub(crate) fn get_source_at_address(
        debug_info: &mut SelfInfo,
        address: usize,
    ) -> Result<Option<SourceAtAddress>, bun_core::Error> {
        let module = match debug_info.get_module_for_address(address) {
            Ok(m) => m,
            Err(e)
                if e == bun_core::err!("MissingDebugInfo")
                    || e == bun_core::err!("InvalidDebugInfo") =>
            {
                return Ok(None);
            }
            Err(e) => return Err(e),
        };

        let symbol_info = match module.get_symbol_at_address(address) {
            Ok(s) => s,
            Err(e)
                if e == bun_core::err!("MissingDebugInfo")
                    || e == bun_core::err!("InvalidDebugInfo") =>
            {
                return Ok(None);
            }
            Err(e) => return Err(e),
        };

        Ok(Some(SourceAtAddress {
            source_location: symbol_info.source_location,
            symbol_name: symbol_info.name,
            compile_unit_name: symbol_info.compile_unit_name,
        }))
    }

    /// Clone of `debug.printLineInfo` as it is private.
    fn print_line_info(
        out_stream: &mut impl Write,
        source_location: Option<&SourceLocation>,
        address: usize,
        symbol_name: &[u8],
        compile_unit_name: &[u8],
        tty_config: TtyConfig,
    ) -> Result<(), bun_core::Error> {
        // Zig: `Environment.base_path ++ std.fs.path.sep_str` (comptime concat).
        // `Environment::BASE_PATH` is `&[u8]`, which `const_format::concatcp!` cannot
        // ingest. The constant is tiny and this path is debug-only — build it once
        // at runtime in a stack BoundedArray (no heap, async-signal-safe).
        let mut base_path_buf = BoundedArray::<u8, { bun_paths::MAX_PATH_BYTES }>::default();
        let _ = base_path_buf.append_slice(Environment::BASE_PATH);
        let _ = base_path_buf.append_slice(bun_paths::SEP_STR.as_bytes());
        let base_path: &[u8] = base_path_buf.const_slice();
        {
            if let Some(sl) = source_location {
                if sl.file_name.starts_with(base_path) {
                    tty_config.set_color(out_stream, Color::Dim)?;
                    out_stream.write_all(base_path)?;
                    tty_config.set_color(out_stream, Color::Reset)?;
                    tty_config.set_color(out_stream, Color::Bold)?;
                    write!(
                        out_stream,
                        "{}",
                        bstr::BStr::new(&sl.file_name[base_path.len()..])
                    )
                    .map_err(fmt_err)?;
                } else {
                    tty_config.set_color(out_stream, Color::Bold)?;
                    write!(out_stream, "{}", bstr::BStr::new(&sl.file_name)).map_err(fmt_err)?;
                }
                write!(out_stream, ":{}:{}", sl.line, sl.column).map_err(fmt_err)?;
            } else {
                tty_config.set_color(out_stream, Color::Bold)?;
                out_stream.write_all(b"???:?:?")?;
            }

            tty_config.set_color(out_stream, Color::Reset)?;
            out_stream.write_all(b": ")?;
            tty_config.set_color(out_stream, Color::Dim)?;
            write!(out_stream, "0x{:x} in", address).map_err(fmt_err)?;
            tty_config.set_color(out_stream, Color::Reset)?;
            tty_config.set_color(out_stream, Color::Yellow)?;
            write!(out_stream, " {}", bstr::BStr::new(symbol_name)).map_err(fmt_err)?;
            tty_config.set_color(out_stream, Color::Reset)?;
            tty_config.set_color(out_stream, Color::Dim)?;
            write!(out_stream, " ({})", bstr::BStr::new(compile_unit_name)).map_err(fmt_err)?;
            tty_config.set_color(out_stream, Color::Reset)?;
            out_stream.write_all(b"\n")?;

            // Show the matching source code line if possible
            if let Some(sl) = source_location {
                match print_line_from_file_any_os(out_stream, tty_config, sl) {
                    Ok(()) => {
                        if sl.column > 0 && tty_config == TtyConfig::NoColor {
                            // The caret already takes one char
                            let space_needed = (sl.column - 1) as usize;
                            out_stream.splat_byte_all(b' ', space_needed)?;
                            out_stream.write_all(b"^\n")?;
                        }
                    }
                    Err(e)
                        if e == bun_core::err!("EndOfFile")
                            || e == bun_core::err!("FileNotFound")
                            || e == bun_core::err!("BadPathName")
                            || e == bun_core::err!("AccessDenied") => {}
                    Err(e) => return Err(e),
                }
            }
        }
        Ok(())
    }

    /// Modified version of `debug.printLineFromFileAnyOs` that uses two passes.
    /// - Record the whole slice into a buffer
    /// - Locate the column, expand a highlight to one word.
    /// - Print the line, with the highlight.
    fn print_line_from_file_any_os(
        out_stream: &mut impl Write,
        tty_config: TtyConfig,
        source_location: &SourceLocation,
    ) -> Result<(), bun_core::Error> {
        // Need this to always block even in async I/O mode, because this could potentially
        // be called from e.g. the event loop code crashing.
        let f = bun_sys::File::openat(
            bun_sys::Fd::cwd(),
            &source_location.file_name,
            bun_sys::O::RDONLY,
            0,
        )
        .map_err(bun_core::Error::from)?;

        let mut line_buf: [u8; 4096] = [0; 4096];
        let mut fbs_len: usize = 0;
        'read_line: {
            let mut buf: [u8; 4096] = [0; 4096];
            let mut amt_read = f.read(&mut buf[..])?;
            let line_start: usize = 'seek: {
                let mut current_line_start: usize = 0;
                let mut next_line: usize = 1;
                while next_line != source_location.line as usize {
                    let slice = &buf[current_line_start..amt_read];
                    if let Some(pos) = bun_core::index_of_char(slice, b'\n') {
                        next_line += 1;
                        if pos == slice.len() - 1 {
                            amt_read = f.read(&mut buf[..])?;
                            current_line_start = 0;
                        } else {
                            current_line_start += pos + 1;
                        }
                    } else if amt_read < buf.len() {
                        return Err(bun_core::err!("EndOfFile"));
                    } else {
                        amt_read = f.read(&mut buf[..])?;
                        current_line_start = 0;
                    }
                }
                break 'seek current_line_start;
            };
            let slice = &mut buf[line_start..amt_read];
            if let Some(pos) = bun_core::index_of_char(slice, b'\n') {
                let line = &mut slice[0..pos];
                for b in line.iter_mut() {
                    if *b == b'\t' {
                        *b = b' ';
                    }
                }
                let n = line.len().min(line_buf.len() - fbs_len);
                line_buf[fbs_len..fbs_len + n].copy_from_slice(&line[..n]);
                fbs_len += n;
                break 'read_line;
            } else {
                // Line is the last inside the buffer, and requires another read to find delimiter. Alternatively the file ends.
                for b in slice.iter_mut() {
                    if *b == b'\t' {
                        *b = b' ';
                    }
                }
                let n = slice.len().min(line_buf.len() - fbs_len);
                line_buf[fbs_len..fbs_len + n].copy_from_slice(&slice[..n]);
                fbs_len += n;
                if n < slice.len() {
                    break 'read_line;
                }
                while amt_read == buf.len() {
                    amt_read = f.read(&mut buf[..])?;
                    if let Some(pos) = bun_core::index_of_char(&buf[0..amt_read], b'\n') {
                        let line = &mut buf[0..pos];
                        for b in line.iter_mut() {
                            if *b == b'\t' {
                                *b = b' ';
                            }
                        }
                        let n2 = line.len().min(line_buf.len() - fbs_len);
                        line_buf[fbs_len..fbs_len + n2].copy_from_slice(&line[..n2]);
                        fbs_len += n2;
                        break 'read_line;
                    } else {
                        let line = &mut buf[0..amt_read];
                        for b in line.iter_mut() {
                            if *b == b'\t' {
                                *b = b' ';
                            }
                        }
                        let n2 = line.len().min(line_buf.len() - fbs_len);
                        line_buf[fbs_len..fbs_len + n2].copy_from_slice(&line[..n2]);
                        fbs_len += n2;
                        if n2 < line.len() {
                            break 'read_line;
                        }
                    }
                }
                break 'read_line;
            }
            // unreachable in Zig (`return;` after the if/else above)
        }
        let line_without_newline = strings::trim_right(&line_buf[..fbs_len], b"\n");
        if source_location.column as usize > line_without_newline.len() {
            out_stream.write_all(line_without_newline)?;
            out_stream.write_byte(b'\n')?;
            return Ok(());
        }
        // expand the highlight to one word
        let mut left = (source_location.column as usize).saturating_sub(1);
        let mut right = left + 1;
        while left > 0 {
            match line_without_newline[left] {
                b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'_' | b' ' | b'\t' => break,
                _ => left -= 1,
            }
        }
        while left > 0 {
            match line_without_newline[left] {
                b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'_' => left -= 1,
                _ => break,
            }
        }
        while right < line_without_newline.len() {
            match line_without_newline[right - 1] {
                b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'_' => right += 1,
                _ => break,
            }
        }
        let before = &line_without_newline[0..left];
        let highlight = &line_without_newline[left..right];
        let mut after_before_comment = &line_without_newline[right..];
        let mut comment: &[u8] = b"";
        if let Some(pos) = bun_core::index_of(after_before_comment, b"//") {
            comment = &after_before_comment[pos..];
            after_before_comment = &after_before_comment[0..pos];
        }
        tty_config.set_color(out_stream, Color::Red)?;
        tty_config.set_color(out_stream, Color::Dim)?;
        out_stream.write_all(before)?;
        tty_config.set_color(out_stream, Color::Reset)?;
        tty_config.set_color(out_stream, Color::Red)?;
        out_stream.write_all(highlight)?;
        tty_config.set_color(out_stream, Color::Dim)?;
        out_stream.write_all(after_before_comment)?;
        if !comment.is_empty() {
            tty_config.set_color(out_stream, Color::Reset)?;
            tty_config.set_color(out_stream, Color::BrightCyan)?;
            out_stream.write_all(comment)?;
        }
        tty_config.set_color(out_stream, Color::Reset)?;
        out_stream.write_byte(b'\n')?;
        Ok(())
    }

    #[unsafe(no_mangle)]
    pub(crate) extern "C" fn CrashHandler__setInsideNativePlugin(name: *const c_char) {
        INSIDE_NATIVE_PLUGIN.with(|c| c.set(if name.is_null() { None } else { Some(name) }));
    }

    /// # Safety
    /// `name` must be a valid NUL-terminated C string.
    #[unsafe(no_mangle)]
    pub(crate) unsafe extern "C" fn CrashHandler__unsupportedUVFunction(name: *const c_char) {
        // TODO(port): bun_analytics::Features::increment_unsupported_uv_function
        UNSUPPORTED_UV_FUNCTION.with(|c| c.set(if name.is_null() { None } else { Some(name) }));
        if env_var::feature_flag::BUN_INTERNAL_SUPPRESS_CRASH_ON_UV_STUB::get() == Some(true) {
            suppress_reporting();
        }
        // SAFETY: name is non-null (Zig dereferences it unconditionally with `.?`)
        let name_bytes = unsafe { bun_core::ffi::cstr(name) }.to_bytes();
        // PORTING.md §Forbidden: no Box::leak. We're on the noreturn path, so a stack
        // buffer suffices — `panic_impl` erases to &'static for the abort path.
        let mut msg = BoundedArray::<u8, 256>::default();
        let _ = write!(
            msg.writer(),
            "unsupported uv function: {}",
            bstr::BStr::new(name_bytes)
        );
        panic_impl(msg.slice(), None, None);
    }

    /// # Safety
    /// `message_ptr` must be valid for reads of `message_len` bytes.
    #[unsafe(no_mangle)]
    pub(crate) unsafe extern "C" fn Bun__crashHandler(
        message_ptr: *const u8,
        message_len: usize,
    ) -> ! {
        // SAFETY: caller passes a valid (ptr, len) byte slice
        let msg = unsafe { core::slice::from_raw_parts(message_ptr, message_len) };
        crash_handler(
            // SAFETY: noreturn — see panic_impl note
            CrashReason::Panic(unsafe { bun_collections::detach_lifetime(msg) }),
            TraceSeed::BeginAddr(debug::return_address()),
        );
    }

    /// # Safety
    /// `action` must be null or a valid NUL-terminated C string that outlives the dlopen call.
    #[unsafe(no_mangle)]
    pub(crate) unsafe extern "C" fn CrashHandler__setDlOpenAction(action: *const c_char) {
        if !action.is_null() {
            debug_assert!(CURRENT_ACTION.with(|c| c.get()).is_none());
            // SAFETY: action is a valid NUL-terminated C string for the duration of the dlopen call
            let s = unsafe { bun_core::ffi::cstr(action) }.to_bytes();
            // SAFETY: noreturn-on-crash usage; the C string outlives the action via caller contract
            let s: &'static [u8] = unsafe { bun_collections::detach_lifetime(s) };
            CURRENT_ACTION.with(|c| c.set(Some(Action::Dlopen(s))));
        } else {
            debug_assert!(matches!(
                CURRENT_ACTION.with(|c| c.get()),
                Some(Action::Dlopen(_))
            ));
            CURRENT_ACTION.with(|c| c.set(None));
        }
    }

    pub fn fix_dead_code_elimination() {
        bun_core::keep_symbols!(CrashHandler__unsupportedUVFunction);
    }
    // In Zig: comptime { _ = &Bun__crashHandler; ... } — Rust links #[no_mangle] symbols unconditionally.
} // end mod draft

// ported from: src/crash_handler/crash_handler.zig