samply 0.13.1

A command line profiler for macOS and Linux.
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
use std::collections::{BTreeMap, HashMap, VecDeque};
use std::path::Path;

use debugid::DebugId;
use fxprof_processed_profile::{
    CategoryColor, CategoryHandle, CounterHandle, CpuDelta, Frame, FrameFlags, FrameInfo,
    LibraryHandle, LibraryInfo, Marker, MarkerFieldFlags, MarkerFieldFormat, MarkerHandle,
    MarkerLocations, MarkerTiming, ProcessHandle, Profile, SamplingInterval, StaticSchemaMarker,
    StaticSchemaMarkerField, StringHandle, ThreadHandle, Timestamp,
};
use shlex::Shlex;
use wholesym::PeCodeId;

use super::chrome::KeywordNames;
use super::winutils;
use crate::shared::context_switch::{
    ContextSwitchHandler, OffCpuSampleGroup, ThreadContextSwitchData,
};
use crate::shared::included_processes::IncludedProcesses;
use crate::shared::jit_category_manager::{JitCategoryManager, JsFrame};
use crate::shared::jit_function_add_marker::JitFunctionAddMarker;
use crate::shared::jit_function_recycler::JitFunctionRecycler;
use crate::shared::lib_mappings::{LibMappingAdd, LibMappingInfo, LibMappingOp, LibMappingOpQueue};
use crate::shared::per_cpu::Cpus;
use crate::shared::process_name::make_process_name;
use crate::shared::process_sample_data::{ProcessSampleData, UserTimingMarker};
use crate::shared::recording_props::ProfileCreationProps;
use crate::shared::recycling::{ProcessRecycler, ProcessRecyclingData, ThreadRecycler};
use crate::shared::synthetic_jit_library::SyntheticJitLibrary;
use crate::shared::timestamp_converter::TimestampConverter;
use crate::shared::types::{StackFrame, StackMode};
use crate::shared::unresolved_samples::{
    UnresolvedSamples, UnresolvedStackHandle, UnresolvedStacks,
};
use crate::windows::firefox::{
    PHASE_INSTANT, PHASE_INTERVAL, PHASE_INTERVAL_END, PHASE_INTERVAL_START,
};

/// An on- or off-cpu-sample for which the user stack is not known yet.
/// Consumed once the user stack arrives.
#[derive(Debug, Clone)]
pub struct SampleWithPendingStack {
    /// The timestamp of the SampleProf or CSwitch event
    pub timestamp: u64,
    /// Starts out as None. Once we encounter the kernel stack (if any), we put it here.
    pub kernel_stack: Option<Vec<StackFrame>>,
    pub off_cpu_sample_group: Option<OffCpuSampleGroup>,
    pub cpu_delta: CpuDelta,
    pub has_on_cpu_sample: bool,
    pub per_cpu_stuff: Option<(ThreadHandle, CpuDelta)>,
}

#[derive(Debug)]
pub struct MemoryUsage {
    pub counter: CounterHandle,
    #[allow(dead_code)]
    pub value: f64,
}

#[derive(Debug)]
pub struct PendingMarker {
    pub text: String,
    pub start: Timestamp,
}

pub struct Threads {
    threads: Vec<Thread>,
    threads_by_tid: HashMap<u32, usize>,
    threads_by_tid_and_start_time: BTreeMap<(u32, u64), usize>,
}

impl Threads {
    pub fn new() -> Self {
        Self {
            threads: Vec::new(),
            threads_by_tid: HashMap::new(),
            threads_by_tid_and_start_time: BTreeMap::new(),
        }
    }

    pub fn add(&mut self, tid: u32, start_timestamp_raw: u64, thread: Thread) {
        let index = self.threads.len();
        self.threads.push(thread);
        self.threads_by_tid.insert(tid, index);
        self.threads_by_tid_and_start_time
            .insert((tid, start_timestamp_raw), index);
    }

    pub fn notify_thread_created(&mut self, tid: u32, timestamp_raw: u64) {
        let Some(index) = self.threads_by_tid.remove(&tid) else {
            return;
        };
        self.threads[index].tid_reused_timestamp_raw = Some(timestamp_raw);
    }

    pub fn get_by_tid(&mut self, tid: u32) -> Option<&mut Thread> {
        let index = *self.threads_by_tid.get(&tid)?;
        Some(&mut self.threads[index])
    }

    fn get_index_by_tid_and_timestamp(&self, tid: u32, timestamp_raw: u64) -> Option<usize> {
        let lookup_key = (tid, timestamp_raw);
        let (found_key, last_entry_at_or_before_key) = self
            .threads_by_tid_and_start_time
            .range(..=lookup_key)
            .next_back()?;
        let (found_tid, found_start_timestamp) = *found_key;
        assert!(found_tid <= tid);
        if found_tid != tid {
            return None;
        }
        assert!(found_start_timestamp <= timestamp_raw);
        let index = *last_entry_at_or_before_key;
        let thread = &self.threads[index];
        if let Some(tid_reused_timestamp) = thread.tid_reused_timestamp_raw {
            if timestamp_raw >= tid_reused_timestamp {
                return None;
            }
        }
        Some(index)
    }

    pub fn has_thread_at_time(&self, tid: u32, timestamp_raw: u64) -> bool {
        self.get_index_by_tid_and_timestamp(tid, timestamp_raw)
            .is_some()
    }

    pub fn get_by_tid_and_timestamp(
        &mut self,
        tid: u32,
        timestamp_raw: u64,
    ) -> Option<&mut Thread> {
        let index = self.get_index_by_tid_and_timestamp(tid, timestamp_raw)?;
        Some(&mut self.threads[index])
    }
}

#[derive(Debug)]
pub struct Thread {
    pub name: Option<String>,
    #[allow(dead_code)]
    pub is_main_thread: bool,
    pub handle: ThreadHandle,
    pub label_frame: FrameInfo,
    pub samples_with_pending_stacks: VecDeque<SampleWithPendingStack>,
    pub context_switch_data: ThreadContextSwitchData,
    #[allow(dead_code)]
    pub thread_id: u32,
    pub tid_reused_timestamp_raw: Option<u64>,
    #[allow(dead_code)]
    pub process_id: u32,
    pub pending_markers: HashMap<String, PendingMarker>,
}

impl Thread {
    fn new(
        name: Option<String>,
        is_main_thread: bool,
        handle: ThreadHandle,
        label_frame: FrameInfo,
        pid: u32,
        tid: u32,
    ) -> Self {
        Thread {
            name,
            is_main_thread,
            handle,
            label_frame,
            samples_with_pending_stacks: VecDeque::new(),
            context_switch_data: Default::default(),
            pending_markers: HashMap::new(),
            thread_id: tid,
            tid_reused_timestamp_raw: None,
            process_id: pid,
        }
    }

    pub fn thread_label(&self) -> StringHandle {
        match self.label_frame.frame {
            Frame::Label(s) => s,
            _ => panic!(),
        }
    }
}

pub struct Processes {
    processes: Vec<Process>,
    processes_by_pid: HashMap<u32, usize>,
    processes_by_pid_and_start_time: BTreeMap<(u32, u64), usize>,
}

impl Processes {
    pub fn new() -> Self {
        Self {
            processes: Vec::new(),
            processes_by_pid: HashMap::new(),
            processes_by_pid_and_start_time: BTreeMap::new(),
        }
    }

    pub fn add(&mut self, pid: u32, start_timestamp_raw: u64, process: Process) {
        let index = self.processes.len();
        self.processes.push(process);
        self.processes_by_pid.insert(pid, index);
        self.processes_by_pid_and_start_time
            .insert((pid, start_timestamp_raw), index);
    }

    pub fn finish(self) -> Vec<ProcessSampleData> {
        self.processes
            .into_iter()
            .map(|process| {
                let jitdump_lib_mapping_op_queues = if !process.jit_lib_mapping_ops.is_empty() {
                    vec![process.jit_lib_mapping_ops]
                } else {
                    Vec::new()
                };

                ProcessSampleData::new(
                    process.unresolved_samples,
                    process.regular_lib_mapping_ops,
                    jitdump_lib_mapping_op_queues,
                    None,
                    Vec::new(),
                )
            })
            .collect()
    }

    pub fn has(&self, pid: u32) -> bool {
        self.processes_by_pid.contains_key(&pid)
    }

    pub fn notify_process_created(&mut self, pid: u32, timestamp_raw: u64) {
        let Some(index) = self.processes_by_pid.remove(&pid) else {
            return;
        };
        self.processes[index].pid_reused_timestamp_raw = Some(timestamp_raw);
    }

    pub fn get_by_pid(&mut self, pid: u32) -> Option<&mut Process> {
        let index = *self.processes_by_pid.get(&pid)?;
        Some(&mut self.processes[index])
    }

    fn get_index_by_pid_and_timestamp(&self, pid: u32, timestamp_raw: u64) -> Option<usize> {
        let lookup_key = (pid, timestamp_raw);
        let (found_key, last_entry_at_or_before_key) = self
            .processes_by_pid_and_start_time
            .range(..=lookup_key)
            .next_back()?;
        let (found_pid, found_start_timestamp) = *found_key;
        assert!(found_pid <= pid);
        if found_pid != pid {
            return None;
        }
        assert!(found_start_timestamp <= timestamp_raw);
        let index = *last_entry_at_or_before_key;
        let process = &self.processes[index];
        if let Some(pid_reused_timestamp) = process.pid_reused_timestamp_raw {
            if timestamp_raw >= pid_reused_timestamp {
                return None;
            }
        }
        Some(index)
    }

    pub fn has_process_at_time(&self, pid: u32, timestamp_raw: u64) -> bool {
        self.get_index_by_pid_and_timestamp(pid, timestamp_raw)
            .is_some()
    }

    pub fn get_by_pid_and_timestamp(
        &mut self,
        pid: u32,
        timestamp_raw: u64,
    ) -> Option<&mut Process> {
        let index = self.get_index_by_pid_and_timestamp(pid, timestamp_raw)?;
        Some(&mut self.processes[index])
    }
}

pub struct Process {
    pub name: String,
    pub handle: ProcessHandle,
    pub seen_main_thread_start: bool,
    pub unresolved_samples: UnresolvedSamples,
    pub regular_lib_mapping_ops: LibMappingOpQueue,
    pub jit_lib_mapping_ops: LibMappingOpQueue,
    pub main_thread_handle: ThreadHandle,
    pub main_thread_label_frame: FrameInfo,
    pub memory_usage: Option<MemoryUsage>,
    pub process_id: u32,
    pub pid_reused_timestamp_raw: Option<u64>,
    #[allow(dead_code)]
    pub parent_id: u32,
    pub thread_recycler: Option<ThreadRecycler>,
    pub jit_function_recycler: Option<JitFunctionRecycler>,
    pub js_sources: HashMap<u64, String>,
}

impl Process {
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        name: String,
        process_id: u32,
        parent_id: u32,
        handle: ProcessHandle,
        main_thread_handle: ThreadHandle,
        main_thread_label_frame: FrameInfo,
        thread_recycler: Option<ThreadRecycler>,
        jit_function_recycler: Option<JitFunctionRecycler>,
    ) -> Self {
        Self {
            name,
            handle,
            seen_main_thread_start: false,
            unresolved_samples: UnresolvedSamples::default(),
            regular_lib_mapping_ops: LibMappingOpQueue::default(),
            jit_lib_mapping_ops: LibMappingOpQueue::default(),
            main_thread_handle,
            main_thread_label_frame,
            memory_usage: None,
            process_id,
            pid_reused_timestamp_raw: None,
            parent_id,
            thread_recycler,
            jit_function_recycler,
            js_sources: HashMap::new(),
        }
    }

    pub fn take_recycling_data(&mut self) -> Option<ProcessRecyclingData> {
        let jit_function_recycler = self.jit_function_recycler.take()?;
        let thread_recycler = self.thread_recycler.take()?;

        Some(ProcessRecyclingData {
            process_handle: self.handle,
            main_thread_recycling_data: (
                self.main_thread_handle,
                self.main_thread_label_frame.clone(),
            ),
            thread_recycler,
            jit_function_recycler,
        })
    }

    #[allow(clippy::too_many_arguments)]
    pub fn add_jit_function(
        &mut self,
        timestamp_raw: u64,
        jit_lib: &mut SyntheticJitLibrary,
        name: String,
        start_avma: u64,
        size: u32,
        info: LibMappingInfo,
    ) {
        let relative_address = jit_lib.add_function(name, size);

        self.jit_lib_mapping_ops.push(
            timestamp_raw,
            LibMappingOp::Add(LibMappingAdd {
                start_avma,
                end_avma: start_avma + u64::from(size),
                relative_address_at_start: relative_address,
                info,
            }),
        );
    }

    pub fn get_memory_usage_counter(&mut self, profile: &mut Profile) -> CounterHandle {
        let process_handle = self.handle;
        let memory_usage = self.memory_usage.get_or_insert_with(|| {
            let counter = profile.add_counter(
                process_handle,
                "VM",
                "Memory",
                "Amount of VirtualAlloc allocated memory",
            );
            MemoryUsage {
                counter,
                value: 0.0,
            }
        });
        memory_usage.counter
    }
}

// Known profiler categories, lazy-created
#[derive(PartialEq, Eq, Hash, Copy, Clone, Debug)]
pub enum KnownCategory {
    Default,
    User,
    Kernel,
    System,
    D3DVideoSubmitDecoderBuffers,
    CoreClrR2r,
    CoreClrJit,
    CoreClrGc,
    Unknown,
}

struct KnownCategories(HashMap<KnownCategory, CategoryHandle>);

impl KnownCategories {
    pub fn new() -> Self {
        Self(HashMap::new())
    }

    #[rustfmt::skip]
    const CATEGORIES: &'static [(KnownCategory, &'static str, CategoryColor)] = &[
        (KnownCategory::User, "User", CategoryColor::Yellow),
        (KnownCategory::Kernel, "Kernel", CategoryColor::LightRed),
        (KnownCategory::System, "System Libraries", CategoryColor::Orange),
        (KnownCategory::D3DVideoSubmitDecoderBuffers, "D3D Video Submit Decoder Buffers", CategoryColor::Transparent),
        (KnownCategory::CoreClrR2r, "CoreCLR R2R", CategoryColor::Blue),
        (KnownCategory::CoreClrJit, "CoreCLR JIT", CategoryColor::Purple),
        (KnownCategory::CoreClrGc, "CoreCLR GC", CategoryColor::Red),
        (KnownCategory::Unknown, "Other", CategoryColor::DarkGray),
    ];

    pub fn get(&mut self, category: KnownCategory, profile: &mut Profile) -> CategoryHandle {
        let category = if category == KnownCategory::Default {
            KnownCategory::User
        } else {
            category
        };

        *self.0.entry(category).or_insert_with(|| {
            let (category_name, color) = Self::CATEGORIES
                .iter()
                .find(|(c, _, _)| *c == category)
                .map(|(_, name, color)| (*name, *color))
                .unwrap();
            profile.add_category(category_name, color)
        })
    }
}

#[derive(Debug, Clone, Copy)]
struct AddressClassifier {
    kernel_min: u64,
}

impl AddressClassifier {
    pub fn get_stack_mode(&self, address: u64) -> StackMode {
        if address >= self.kernel_min {
            StackMode::Kernel
        } else {
            StackMode::User
        }
    }
}

pub struct ProfileContext {
    profile: Profile,

    profile_creation_props: ProfileCreationProps,

    // state -- keep track of the processes etc we've seen as we're processing,
    // and their associated handles in the json profile
    processes: Processes,
    threads: Threads,
    thread_handles: BTreeMap<(u32, u64), ThreadHandle>,

    unresolved_stacks: UnresolvedStacks,

    /// Some() if a thread should be merged into a previously exited
    /// thread of the same name.
    process_recycler: Option<ProcessRecycler>,

    // some special threads
    gpu_thread_handle: Option<ThreadHandle>,

    // These are the processes + their descendants that we want to write into
    // the profile.json. If it's None, include everything.
    included_processes: Option<IncludedProcesses>,

    categories: KnownCategories,

    known_images: HashMap<(String, u32, u32), (LibraryHandle, KnownCategory)>,

    js_category_manager: JitCategoryManager,
    js_jit_lib: SyntheticJitLibrary,
    coreclr_jit_lib: SyntheticJitLibrary,

    context_switch_handler: ContextSwitchHandler,

    // cache of device mappings
    device_mappings: HashMap<String, String>, // map of \Device\HarddiskVolume4 -> C:\

    // the minimum address for kernel drivers, so that we can assign kernel_category to the frame
    kernel_min: u64,

    address_classifier: AddressClassifier,

    // architecture to record in the trace. will be the system architecture for now.
    // TODO no idea how to handle "I'm on aarch64 windows but I'm recording a win64 process".
    // I have no idea how stack traces work in that case anyway, so this is probably moot.
    arch: String,

    sample_count: usize,
    stack_sample_count: usize,
    event_count: usize,

    seen_header: bool,
    timestamp_converter: TimestampConverter,
    event_timestamps_are_qpc: bool,

    /// Only include main threads.
    main_thread_only: bool,

    // Time range from the timestamp origin
    time_range: Option<(Timestamp, Timestamp)>,

    cpus: Option<Cpus>,
}

impl ProfileContext {
    pub fn new(
        mut profile: Profile,
        arch: &str,
        included_processes: Option<IncludedProcesses>,
        profile_creation_props: ProfileCreationProps,
    ) -> Self {
        // On 64-bit systems, the kernel address space always has 0xF in the first 16 bits.
        // The actual kernel address space is much higher, but we just need this to disambiguate kernel and user
        // stacks.
        let kernel_min: u64 = if arch == "x86" {
            0x8000_0000
        } else {
            0xF000_0000_0000_0000
        };
        let address_classifier = AddressClassifier { kernel_min };
        let process_recycler = if profile_creation_props.reuse_threads {
            Some(ProcessRecycler::new())
        } else {
            None
        };
        let main_thread_only = profile_creation_props.main_thread_only;
        let time_range = profile_creation_props.time_range.map(|(start, end)| {
            (
                Timestamp::from_nanos_since_reference(start.as_nanos() as u64),
                Timestamp::from_nanos_since_reference(end.as_nanos() as u64),
            )
        });

        let mut categories = KnownCategories::new();
        let mut js_category_manager = JitCategoryManager::new();
        let default_js_jit_category = js_category_manager.default_category(&mut profile);
        let allow_jit_function_recycling = profile_creation_props.reuse_threads;
        let js_jit_lib = SyntheticJitLibrary::new(
            "JS JIT".to_string(),
            default_js_jit_category.into(),
            &mut profile,
            allow_jit_function_recycling,
        );
        let coreclr_jit_category = categories.get(KnownCategory::CoreClrJit, &mut profile);
        let coreclr_jit_lib = SyntheticJitLibrary::new(
            "CoreCLR JIT".to_string(),
            coreclr_jit_category.into(),
            &mut profile,
            allow_jit_function_recycling,
        );

        let cpus = if profile_creation_props.create_per_cpu_threads {
            Some(Cpus::new(
                Timestamp::from_nanos_since_reference(0),
                &mut profile,
            ))
        } else {
            None
        };

        Self {
            profile,
            profile_creation_props,
            processes: Processes::new(),
            threads: Threads::new(),
            thread_handles: BTreeMap::new(),
            unresolved_stacks: UnresolvedStacks::default(),
            process_recycler,
            gpu_thread_handle: None,
            included_processes,
            categories,
            known_images: HashMap::new(),
            js_category_manager,
            js_jit_lib,
            coreclr_jit_lib,
            context_switch_handler: ContextSwitchHandler::new(122100), // hardcoded, but replaced once TraceStart is received
            device_mappings: winutils::get_dos_device_mappings(),
            kernel_min,
            address_classifier,
            arch: arch.to_string(),
            sample_count: 0,
            stack_sample_count: 0,
            event_count: 0,
            seen_header: false,
            // Dummy, will be replaced once we see the header
            timestamp_converter: TimestampConverter {
                reference_raw: 0,
                raw_to_ns_factor: 1,
            },
            event_timestamps_are_qpc: false,
            main_thread_only,
            time_range,
            cpus,
        }
    }

    pub fn creation_props(&self) -> ProfileCreationProps {
        self.profile_creation_props.clone()
    }

    pub fn is_arm64(&self) -> bool {
        self.arch == "arm64"
    }

    pub fn has_thread_at_time(&self, tid: u32, timestamp_raw: u64) -> bool {
        self.threads.has_thread_at_time(tid, timestamp_raw)
    }

    pub fn has_process_at_time(&self, pid: u32, timestamp_raw: u64) -> bool {
        self.processes.has_process_at_time(pid, timestamp_raw)
    }

    pub fn is_interesting_process(&self, pid: u32, ppid: Option<u32>, name: Option<&str>) -> bool {
        if pid == 0 {
            return false;
        }

        // already tracking this process or its parent?
        if self.processes.has(pid) || ppid.is_some_and(|k| self.processes.has(k)) {
            return true;
        }

        match &self.included_processes {
            Some(incl) => incl.should_include(name, pid),
            None => true,
        }
    }

    // The filename is a NT kernel path (https://chrisdenton.github.io/omnipath/NT.html) which isn't direclty
    // usable from user space.  perfview goes through a dance to convert it to a regular user space path
    // https://github.com/microsoft/perfview/blob/4fb9ec6947cb4e68ac7cb5e80f50ae3757d0ede4/src/TraceEvent/Parsers/KernelTraceEventParser.cs#L3461
    // and we do a bit of it here, just for dos drive mappings. Everything else we prefix with \\?\GLOBALROOT\
    pub fn map_device_path(&self, path: &str) -> String {
        for (k, v) in &self.device_mappings {
            if path.starts_with(k) {
                let r = format!("{}{}", v, path.split_at(k.len()).1);
                return r;
            }
        }

        // if we didn't translate (still have a \\ path), prefix with GLOBALROOT as
        // an escape
        if path.starts_with("\\\\") {
            format!("\\\\?\\GLOBALROOT{}", path)
        } else {
            path.into()
        }
    }

    pub fn known_category(&mut self, known_category: KnownCategory) -> CategoryHandle {
        self.categories.get(known_category, &mut self.profile)
    }

    pub fn intern_profile_string(&mut self, s: &str) -> StringHandle {
        self.profile.intern_string(s)
    }

    pub fn add_thread_instant_marker(
        &mut self,
        timestamp_raw: u64,
        tid: u32,
        marker: impl Marker,
    ) -> (ThreadHandle, MarkerHandle) {
        let timestamp = self.timestamp_converter.convert_time(timestamp_raw);
        let timing = MarkerTiming::Instant(timestamp);
        let thread = self
            .threads
            .get_by_tid_and_timestamp(tid, timestamp_raw)
            .unwrap();
        let marker_handle = self.profile.add_marker(thread.handle, timing, marker);
        (thread.handle, marker_handle)
    }

    pub fn add_thread_interval_marker(
        &mut self,
        start_timestamp_raw: u64,
        end_timestamp_raw: u64,
        tid: u32,
        marker: impl Marker,
    ) -> MarkerHandle {
        let start_timestamp = self.timestamp_converter.convert_time(start_timestamp_raw);
        let end_timestamp = self.timestamp_converter.convert_time(end_timestamp_raw);
        let timing = MarkerTiming::Interval(start_timestamp, end_timestamp);
        let thread = self.threads.get_by_tid(tid).unwrap();
        self.profile.add_marker(thread.handle, timing, marker)
    }

    pub fn handle_header(&mut self, timestamp_raw: u64, perf_freq: u64, clock_type: u32) {
        if clock_type != 1 {
            log::warn!("QPC not used as clock");
            self.event_timestamps_are_qpc = false;
        } else {
            self.event_timestamps_are_qpc = true;
        }

        if !self.seen_header {
            // Initialize our reference timestamp to the timestamp from the
            // first trace's header.
            self.timestamp_converter = TimestampConverter {
                reference_raw: timestamp_raw,
                raw_to_ns_factor: 1000 * 1000 * 1000 / perf_freq,
            };
            self.seen_header = true;
        } else {
            // The header we're processing is the header of the user trace.
            // Make sure the timestamps in the two traces are comparable.
            assert!(
                self.timestamp_converter.reference_raw <= timestamp_raw,
                "The first trace should have started first"
            );
            assert_eq!(
                self.timestamp_converter.raw_to_ns_factor,
                1000 * 1000 * 1000 / perf_freq,
                "The two traces have incompatible timestamps"
            );
        }
    }

    pub fn handle_collection_start(&mut self, interval_raw: u32) {
        let interval_nanos = interval_raw as u64 * 100;
        let interval = SamplingInterval::from_nanos(interval_nanos);
        log::info!("Sample rate {}ms", interval.as_secs_f64() * 1000.);
        self.profile.set_interval(interval);
        self.context_switch_handler = ContextSwitchHandler::new(interval_raw as u64);
    }

    pub fn make_process_name(&self, image_file_name: &str, cmdline: &str) -> String {
        let executable_path = self.map_device_path(image_file_name);
        let executable_name = extract_filename(&executable_path);
        make_process_name(
            executable_name,
            Shlex::new(cmdline).collect(),
            self.profile_creation_props
                .arg_count_to_include_in_process_name,
        )
    }

    pub fn handle_process_dcstart(
        &mut self,
        timestamp_raw: u64,
        pid: u32,
        parent_pid: u32,
        image_file_name: String,
        cmdline: String,
    ) {
        if !self.is_interesting_process(pid, Some(parent_pid), Some(&image_file_name)) {
            return;
        }

        let timestamp = self.timestamp_converter.convert_time(timestamp_raw);
        let name = self.make_process_name(&image_file_name, &cmdline);
        let process_handle = self.profile.add_process(&name, pid, timestamp);
        let main_thread_handle = self
            .profile
            .add_thread(process_handle, pid, timestamp, true);
        let main_thread_label_frame =
            make_thread_label_frame(&mut self.profile, Some(&name), pid, pid);
        let (thread_recycler, jit_function_recycler) = if self.process_recycler.is_some() {
            (
                Some(ThreadRecycler::new()),
                Some(JitFunctionRecycler::default()),
            )
        } else {
            (None, None)
        };
        let process = Process::new(
            name,
            pid,
            parent_pid,
            process_handle,
            main_thread_handle,
            main_thread_label_frame,
            thread_recycler,
            jit_function_recycler,
        );
        self.processes.add(pid, timestamp_raw, process);
    }

    pub fn handle_process_start(
        &mut self,
        timestamp_raw: u64,
        pid: u32,
        parent_pid: u32,
        image_file_name: String,
        cmdline: String,
    ) {
        self.processes.notify_process_created(pid, timestamp_raw);

        if !self.is_interesting_process(pid, Some(parent_pid), Some(&image_file_name)) {
            return;
        }

        let timestamp = self.timestamp_converter.convert_time(timestamp_raw);

        let name = self.make_process_name(&image_file_name, &cmdline);
        let recycling_data = self
            .process_recycler
            .as_mut()
            .and_then(|pr| pr.recycle_by_name(&name));

        let (process_handle, main_thread_handle, main_thread_label_frame) =
            if let Some(recycling_data) = &recycling_data {
                log::info!("Found old process for pid {} and name {}", pid, name);
                let (main_thread_handle, main_thread_label_frame) =
                    recycling_data.main_thread_recycling_data.clone();
                (
                    recycling_data.process_handle,
                    main_thread_handle,
                    main_thread_label_frame,
                )
            } else {
                let process_handle = self.profile.add_process(&name, pid, timestamp);
                let main_thread_handle =
                    self.profile
                        .add_thread(process_handle, pid, timestamp, true);
                let main_thread_label_frame =
                    make_thread_label_frame(&mut self.profile, Some(&name), pid, pid);
                (process_handle, main_thread_handle, main_thread_label_frame)
            };

        let (thread_recycler, jit_function_recycler) = if let Some(recycling_data) = recycling_data
        {
            (
                Some(recycling_data.thread_recycler),
                Some(recycling_data.jit_function_recycler),
            )
        } else if self.process_recycler.is_some() {
            (
                Some(ThreadRecycler::new()),
                Some(JitFunctionRecycler::default()),
            )
        } else {
            (None, None)
        };

        let process = Process::new(
            name,
            pid,
            parent_pid,
            process_handle,
            main_thread_handle,
            main_thread_label_frame,
            thread_recycler,
            jit_function_recycler,
        );
        self.processes.add(pid, timestamp_raw, process);
    }

    pub fn handle_process_end(&mut self, timestamp_raw: u64, pid: u32) {
        let Some(process) = self.processes.get_by_pid(pid) else {
            return;
        };

        let timestamp = self.timestamp_converter.convert_time(timestamp_raw);
        self.profile.set_process_end_time(process.handle, timestamp);

        if let Some(process_recycler) = self.process_recycler.as_mut() {
            if let Some(process_recycling_data) = process.take_recycling_data() {
                process_recycler.add_to_pool(&process.name, process_recycling_data);
                log::info!(
                    "Adding process with pid {} and name {} to pool",
                    process.process_id,
                    process.name
                );
            } else {
                log::info!("Could not get process recycling data");
            }
        }
    }

    pub fn handle_process_dcend(&mut self, _timestamp_raw: u64, _pid: u32) {
        // Nothing to do - the process is still alive at the end of profiling.
    }

    pub fn handle_thread_dcstart(
        &mut self,
        timestamp_raw: u64,
        tid: u32,
        pid: u32,
        mut name: Option<String>,
    ) {
        if !self.is_interesting_process(pid, None, None) {
            return;
        }

        if name.as_deref().is_some_and(|name| name.is_empty()) {
            name = None;
        }

        let timestamp = self.timestamp_converter.convert_time(timestamp_raw);

        let Some(process) = self.processes.get_by_pid(pid) else {
            log::warn!("Adding thread {tid} for unknown pid {pid}");
            return;
        };
        if !process.seen_main_thread_start {
            process.seen_main_thread_start = true;
            let thread_handle = process.main_thread_handle;
            let thread_name = name.as_deref().unwrap_or(&process.name);
            let thread_label_frame =
                make_thread_label_frame(&mut self.profile, Some(thread_name), pid, tid);
            process.main_thread_label_frame = thread_label_frame.clone();
            self.profile.set_thread_tid(thread_handle, tid);
            let thread = Thread::new(name, true, thread_handle, thread_label_frame, pid, tid);
            self.threads.add(tid, timestamp_raw, thread);
            self.thread_handles
                .insert((tid, timestamp_raw), thread_handle);
            return;
        }

        if self.main_thread_only {
            // Ignore this thread.
            return;
        }

        let thread_handle = self
            .profile
            .add_thread(process.handle, tid, timestamp, false);
        let thread_label_frame =
            make_thread_label_frame(&mut self.profile, name.as_deref(), pid, tid);
        if let Some(name) = name.as_deref() {
            if !name.is_empty() {
                self.profile.set_thread_name(thread_handle, name);
            }
        }

        let thread = Thread::new(name, false, thread_handle, thread_label_frame, pid, tid);
        self.threads.add(tid, timestamp_raw, thread);
        self.thread_handles
            .insert((tid, timestamp_raw), thread_handle);
    }

    pub fn handle_thread_start(
        &mut self,
        timestamp_raw: u64,
        tid: u32,
        pid: u32,
        name: Option<String>,
    ) {
        self.threads.notify_thread_created(tid, timestamp_raw);

        if !self.is_interesting_process(pid, None, None) {
            return;
        }

        let timestamp = self.timestamp_converter.convert_time(timestamp_raw);

        let Some(process) = self.processes.get_by_pid(pid) else {
            log::warn!("Adding thread {tid} for unknown pid {pid}");
            return;
        };
        if !process.seen_main_thread_start {
            process.seen_main_thread_start = true;
            let thread_handle = process.main_thread_handle;
            let thread_name = name.as_deref().unwrap_or(&process.name);
            let thread_label_frame =
                make_thread_label_frame(&mut self.profile, Some(thread_name), pid, tid);
            process.main_thread_label_frame = thread_label_frame.clone();
            self.profile.set_thread_tid(thread_handle, tid);
            let thread = Thread::new(name, true, thread_handle, thread_label_frame, pid, tid);
            self.threads.add(tid, timestamp_raw, thread);
            self.thread_handles
                .insert((tid, timestamp_raw), thread_handle);
            return;
        }

        if self.main_thread_only {
            // Ignore this thread.
            return;
        }

        if let (Some(thread_name), Some(thread_recycler)) =
            (&name, process.thread_recycler.as_mut())
        {
            if let Some((thread_handle, thread_label_frame)) =
                thread_recycler.recycle_by_name(thread_name)
            {
                let thread = Thread::new(name, false, thread_handle, thread_label_frame, pid, tid);
                self.threads.add(tid, timestamp_raw, thread);
                self.thread_handles
                    .insert((tid, timestamp_raw), thread_handle);
                return;
            }
        }

        let thread_handle = self
            .profile
            .add_thread(process.handle, tid, timestamp, false);
        let thread_label_frame =
            make_thread_label_frame(&mut self.profile, name.as_deref(), pid, tid);
        if let Some(name) = name.as_deref() {
            if !name.is_empty() {
                self.profile.set_thread_name(thread_handle, name);
            }
        }

        let thread = Thread::new(name, false, thread_handle, thread_label_frame, pid, tid);
        self.threads.add(tid, timestamp_raw, thread);
        self.thread_handles
            .insert((tid, timestamp_raw), thread_handle);
    }

    // Why not `self.threads.get_by_tid_and_timestamp(...)?.handle`? Because a thread
    // can change its handle during its lifetime in --reuse-threads mode if its name
    // changes.
    // Example: Thread with PID 1 gets created at time 10, renamed to "Booster" at time 20,
    // and destroyed at time 30.
    // Thread with PID 2 gets created at time 15, renamed to "Spare" at time 15, renamed
    // to "Booster" at time 35, and destroyed at time 50.
    // When the thread with PID 2 gets renamed to "Booster", in --reuse-threads mode,
    // it will change its handle to the one of the old thread with PID 1.
    // Now if we get a marker for PID 2 and time 25, we want to put it on the "Spare" handle,
    // not on the "Booster" handle. Just using thread.handle might put it on the "Booster"
    // handle because we may be processing the user session ETL after we've already processed
    // all the kernel session events.
    pub fn thread_handle_at_time(&self, tid: u32, timestamp_raw: u64) -> Option<ThreadHandle> {
        let lookup_key = (tid, timestamp_raw);
        let (found_key, last_entry_at_or_before_key) =
            self.thread_handles.range(..=lookup_key).next_back()?;
        let (found_tid, found_start_timestamp) = *found_key;
        assert!(found_tid <= tid);
        if found_tid != tid {
            return None;
        }
        assert!(found_start_timestamp <= timestamp_raw);
        let thread_handle = *last_entry_at_or_before_key;
        Some(thread_handle)
    }

    pub fn handle_thread_set_name(&mut self, timestamp_raw: u64, pid: u32, tid: u32, name: String) {
        if name.is_empty() {
            return;
        }
        let Some(thread) = self.threads.get_by_tid(tid) else {
            return;
        };
        let Some(process) = self.processes.get_by_pid(pid) else {
            return;
        };

        if let Some(thread_recycler) = process.thread_recycler.as_mut() {
            if let Some(old_name) = thread.name.as_deref() {
                let thread_recycling_data = (thread.handle, thread.label_frame.clone());
                thread_recycler.add_to_pool(old_name, thread_recycling_data);
            }
            if let Some((thread_handle, thread_label_frame)) =
                thread_recycler.recycle_by_name(&name)
            {
                thread.name = Some(name);
                thread.handle = thread_handle;
                thread.label_frame = thread_label_frame;
                self.thread_handles
                    .insert((tid, timestamp_raw), thread_handle);
                return;
            }
        }
        thread.label_frame = make_thread_label_frame(&mut self.profile, Some(&name), pid, tid);
        self.profile.set_thread_name(thread.handle, &name);
        thread.name = Some(name);
    }

    pub fn handle_thread_end(&mut self, timestamp_raw: u64, pid: u32, tid: u32) {
        let Some(thread) = self.threads.get_by_tid(tid) else {
            return;
        };
        let timestamp = self.timestamp_converter.convert_time(timestamp_raw);
        self.profile.set_thread_end_time(thread.handle, timestamp);

        let Some(process) = self.processes.get_by_pid(pid) else {
            return;
        };
        if let (Some(name), Some(thread_recycler)) =
            (thread.name.as_deref(), process.thread_recycler.as_mut())
        {
            let thread_recycling_data = (thread.handle, thread.label_frame.clone());
            thread_recycler.add_to_pool(name, thread_recycling_data);
        }
    }

    pub fn handle_thread_dcend(&mut self, _timestamp_raw: u64, _tid: u32) {
        // Nothing to do. The thread is still alive at the end of profiling.
    }

    /// Attach a stack to an existing marker.
    ///
    /// CoreCLR emits these stacks after the corresponding marker.
    pub fn handle_coreclr_stack(
        &mut self,
        timestamp_raw: u64,
        pid: u32,
        stack_address_iter: impl Iterator<Item = u64>,
        thread_marker_handle: (ThreadHandle, MarkerHandle),
    ) {
        let Some(process) = self.processes.get_by_pid_and_timestamp(pid, timestamp_raw) else {
            return;
        };

        let stack: Vec<StackFrame> = to_stack_frames(stack_address_iter, self.address_classifier);
        let stack_index = self.unresolved_stacks.convert(stack.into_iter().rev());
        //eprintln!("event: StackWalk stack: {:?}", stack);

        // Note: we don't add these as actual samples, and instead just attach them to the marker.
        // If we added them as samples, it would throw off the profile counting, because they arrive
        // in between regular interval samples. In the future, maybe we can support fractional samples
        // somehow (fractional weight), but for now, we just attach them to the marker.
        let (thread_handle, marker_handle) = thread_marker_handle;
        let timestamp = self.timestamp_converter.convert_time(timestamp_raw);
        process.unresolved_samples.attach_stack_to_marker(
            thread_handle,
            timestamp,
            timestamp_raw,
            stack_index,
            marker_handle,
        );
    }

    pub fn handle_stack_arm64(
        &mut self,
        timestamp_raw: u64,
        pid: u32,
        tid: u32,
        stack_address_iter: impl Iterator<Item = u64>,
    ) {
        let Some(process) = self.processes.get_by_pid(pid) else {
            return;
        };
        let Some(thread) = self.threads.get_by_tid(tid) else {
            return;
        };

        // On ARM64, this seems to be simpler -- stacks come in with full kernel and user frames.
        // At least, I've never seen a kernel stack come in separately.
        // TODO -- is this because I can't use PROFILE events in the VM?

        let stack: Vec<StackFrame> = to_stack_frames(stack_address_iter, self.address_classifier);

        let cpu_delta_raw = self
            .context_switch_handler
            .consume_cpu_delta(&mut thread.context_switch_data);
        let cpu_delta =
            CpuDelta::from_nanos(cpu_delta_raw * self.timestamp_converter.raw_to_ns_factor);
        let timestamp = self.timestamp_converter.convert_time(timestamp_raw);
        let stack_index = self.unresolved_stacks.convert(stack.into_iter().rev());
        process.unresolved_samples.add_sample(
            thread.handle,
            timestamp,
            timestamp_raw,
            stack_index,
            cpu_delta,
            1,
            None,
        );
    }

    pub fn handle_stack_x86(
        &mut self,
        timestamp_raw: u64,
        pid: u32,
        tid: u32,
        stack_len: usize,
        stack_address_iter: impl Iterator<Item = u64>,
    ) {
        let mut stack: Vec<StackFrame> = Vec::with_capacity(stack_len);
        let mut address_iter = stack_address_iter;
        let Some(first_frame_address) = address_iter.next() else {
            return;
        };
        let first_frame_stack_mode = self.address_classifier.get_stack_mode(first_frame_address);
        stack.push(StackFrame::InstructionPointer(
            first_frame_address,
            first_frame_stack_mode,
        ));
        stack.extend(address_iter.map(|addr| {
            let stack_mode = self.address_classifier.get_stack_mode(addr);
            StackFrame::ReturnAddress(addr, stack_mode)
        }));

        match first_frame_stack_mode {
            StackMode::Kernel => self.handle_kernel_stack(timestamp_raw, pid, tid, stack),
            StackMode::User => self.handle_user_stack(timestamp_raw, pid, tid, stack),
        }
    }

    fn handle_kernel_stack(
        &mut self,
        timestamp_raw: u64,
        pid: u32,
        tid: u32,
        stack: Vec<StackFrame>,
    ) {
        let Some(thread) = self.threads.get_by_tid(tid) else {
            return;
        };
        let Some(index) = thread
            .samples_with_pending_stacks
            .iter_mut()
            .rposition(|s| s.timestamp == timestamp_raw)
        else {
            return;
        };
        let sample_info = &mut thread.samples_with_pending_stacks[index];
        if let Some(kernel_stack) = sample_info.kernel_stack.as_mut() {
            log::warn!("Multiple kernel stacks for timestamp {timestamp_raw} on thread {tid}");
            kernel_stack.extend(&stack);
        } else {
            sample_info.kernel_stack = Some(stack);
        }

        if pid == 4 {
            // No user stack will arrive. Consume the sample now.
            let sample_info = thread.samples_with_pending_stacks.remove(index).unwrap();
            let thread_handle = thread.handle;
            let thread_label_frame = thread.label_frame.clone();
            self.consume_sample(
                pid,
                sample_info,
                UnresolvedStackHandle::EMPTY,
                thread_handle,
                thread_label_frame,
            );
        }
    }

    fn handle_user_stack(
        &mut self,
        timestamp_raw: u64,
        pid: u32,
        tid: u32,
        user_stack: Vec<StackFrame>,
    ) {
        let Some(thread) = self.threads.get_by_tid(tid) else {
            return;
        };

        // User stacks always come last. Consume any samples with pending stacks with matching timestamp.
        let user_stack_index = self.unresolved_stacks.convert(user_stack.into_iter().rev());

        // the number of pending stacks at or before our timestamp
        let num_samples_with_pending_stacks = thread
            .samples_with_pending_stacks
            .iter()
            .take_while(|s| s.timestamp <= timestamp_raw)
            .count();

        let samples_with_pending_stacks: VecDeque<_> = thread
            .samples_with_pending_stacks
            .drain(..num_samples_with_pending_stacks)
            .collect();

        let thread_handle = thread.handle;
        let thread_label_frame = thread.label_frame.clone();

        // Use this user stack for all pending stacks from this thread.
        for sample_info in samples_with_pending_stacks {
            self.consume_sample(
                pid,
                sample_info,
                user_stack_index,
                thread_handle,
                thread_label_frame.clone(),
            );
        }
    }

    fn consume_sample(
        &mut self,
        pid: u32,
        sample_info: SampleWithPendingStack,
        user_stack_index: UnresolvedStackHandle,
        thread_handle: ThreadHandle,
        thread_label_frame: FrameInfo,
    ) {
        let Some(process) = self.processes.get_by_pid(pid) else {
            return;
        };
        let SampleWithPendingStack {
            timestamp: timestamp_raw,
            kernel_stack,
            off_cpu_sample_group,
            mut cpu_delta,
            has_on_cpu_sample,
            per_cpu_stuff,
        } = sample_info;
        let timestamp = self.timestamp_converter.convert_time(timestamp_raw);

        if let Some(off_cpu_sample_group) = off_cpu_sample_group {
            let OffCpuSampleGroup {
                begin_timestamp: begin_timestamp_raw,
                end_timestamp: end_timestamp_raw,
                sample_count,
            } = off_cpu_sample_group;

            // Add a sample at the beginning of the paused range.
            // This "first sample" will carry any leftover accumulated running time ("cpu delta").
            let begin_timestamp = self.timestamp_converter.convert_time(begin_timestamp_raw);
            process.unresolved_samples.add_sample(
                thread_handle,
                begin_timestamp,
                begin_timestamp_raw,
                user_stack_index,
                cpu_delta,
                1,
                None,
            );
            cpu_delta = CpuDelta::ZERO;

            if sample_count > 1 {
                // Emit a "rest sample" with a CPU delta of zero covering the rest of the paused range.
                let weight = i32::try_from(sample_count - 1).unwrap_or(0);
                let end_timestamp = self.timestamp_converter.convert_time(end_timestamp_raw);
                process.unresolved_samples.add_sample(
                    thread_handle,
                    end_timestamp,
                    end_timestamp_raw,
                    user_stack_index,
                    CpuDelta::ZERO,
                    weight,
                    None,
                );
            }
        }

        if !has_on_cpu_sample {
            return;
        }

        let stack_index = if let Some(kernel_stack) = kernel_stack {
            self.unresolved_stacks
                .convert_with_prefix(user_stack_index, kernel_stack.into_iter().rev())
        } else {
            user_stack_index
        };
        process.unresolved_samples.add_sample(
            thread_handle,
            timestamp,
            timestamp_raw,
            stack_index,
            cpu_delta,
            1,
            None,
        );

        if let Some((cpu_thread_handle, cpu_delta)) = per_cpu_stuff {
            process.unresolved_samples.add_sample(
                cpu_thread_handle,
                timestamp,
                timestamp_raw,
                stack_index,
                cpu_delta,
                1,
                Some(thread_label_frame.clone()),
            );
            process.unresolved_samples.add_sample(
                self.cpus.as_ref().unwrap().combined_thread_handle(),
                timestamp,
                timestamp_raw,
                stack_index,
                CpuDelta::ZERO,
                1,
                Some(thread_label_frame.clone()),
            );
        }

        self.stack_sample_count += 1;
    }

    pub fn handle_sample(&mut self, timestamp_raw: u64, tid: u32, cpu_index: u32) {
        let Some(thread) = self.threads.get_by_tid(tid) else {
            return;
        };

        let off_cpu_sample_group = self
            .context_switch_handler
            .handle_on_cpu_sample(timestamp_raw, &mut thread.context_switch_data);
        let delta = self
            .context_switch_handler
            .consume_cpu_delta(&mut thread.context_switch_data);
        let cpu_delta = self.timestamp_converter.convert_cpu_delta(delta);

        let per_cpu_stuff = if let Some(cpus) = &mut self.cpus {
            let cpu = cpus.get_mut(cpu_index as usize, &mut self.profile);

            let cpu_thread_handle = cpu.thread_handle;

            // Consume idle cpu time.
            let _idle_cpu_sample = self
                .context_switch_handler
                .handle_on_cpu_sample(timestamp_raw, &mut cpu.context_switch_data);

            let cpu_delta = if true {
                self.timestamp_converter.convert_cpu_delta(
                    self.context_switch_handler
                        .consume_cpu_delta(&mut cpu.context_switch_data),
                )
            } else {
                CpuDelta::from_nanos(0)
            };
            Some((cpu_thread_handle, cpu_delta))
        } else {
            None
        };

        thread
            .samples_with_pending_stacks
            .push_back(SampleWithPendingStack {
                timestamp: timestamp_raw,
                kernel_stack: None,
                off_cpu_sample_group,
                cpu_delta,
                has_on_cpu_sample: true,
                per_cpu_stuff,
            });

        self.sample_count += 1;
    }

    pub fn handle_virtual_alloc_free(
        &mut self,
        timestamp_raw: u64,
        is_free: bool,
        pid: u32,
        _tid: u32,
        region_size: u64,
        _stringified_properties: String,
    ) {
        let Some(process) = self.processes.get_by_pid(pid) else {
            return;
        };

        let timestamp = self.timestamp_converter.convert_time(timestamp_raw);
        let delta_size = if is_free {
            -(region_size as f64)
        } else {
            region_size as f64
        };
        // let op_name = if is_free {
        //     "VirtualFree"
        // } else {
        //     "VirtualAlloc"
        // };

        let memory_usage_counter = process.get_memory_usage_counter(&mut self.profile);
        self.profile
            .add_counter_sample(memory_usage_counter, timestamp, 0.0, 0);
        self.profile
            .add_counter_sample(memory_usage_counter, timestamp, delta_size, 1);
        // TODO: Consider adding a marker here
    }

    fn lib_handle_and_category_for_image(
        &mut self,
        device_path: String,
        mut image_info: PeInfo,
    ) -> (LibraryHandle, KnownCategory) {
        let key = (
            device_path,
            image_info.image_size,
            image_info.image_checksum,
        );
        if let Some(lib_handle_and_category) = self.known_images.get(&key) {
            return *lib_handle_and_category;
        }

        let path = self.map_device_path(&key.0);
        image_info.lookup_missing_info_from_image_at_path(Path::new(&path));

        let code_id = image_info.code_id();
        let debug_id = image_info.debug_id.unwrap_or_default();
        let pdb_path = image_info.pdb_path.unwrap_or_else(|| path.clone());
        let path_lower = path.to_lowercase();
        let pdb_path_lower = pdb_path.to_lowercase();
        let name = extract_filename(&path).to_string();
        let pdb_name = extract_filename(&pdb_path).to_string();

        let lib_handle = self.profile.add_lib(LibraryInfo {
            name,
            path,
            debug_name: pdb_name,
            debug_path: pdb_path,
            debug_id,
            code_id: code_id.map(|ci| ci.to_string()),
            arch: Some(self.arch.to_owned()),
            symbol_table: None,
        });

        // attempt to categorize the library based on the path
        let known_category = if pdb_path_lower.contains(".ni.pdb") {
            KnownCategory::CoreClrR2r
        } else if path_lower.contains("windows\\system32") || path_lower.contains("windows\\winsxs")
        {
            KnownCategory::System
        } else {
            KnownCategory::Unknown
        };

        self.known_images.insert(key, (lib_handle, known_category));
        (lib_handle, known_category)
    }

    pub fn handle_image_load(
        &mut self,
        timestamp_raw: u64,
        pid: u32,
        image_base: u64,
        device_path: String,
        image_info: PeInfo,
    ) {
        if pid != 0 && !self.processes.has(pid) {
            return;
        }

        let image_size = image_info.image_size as u64;
        let (lib_handle, known_category) =
            self.lib_handle_and_category_for_image(device_path, image_info);

        let start_avma = image_base;
        let end_avma = image_base + image_size;
        if pid == 0 || start_avma >= self.kernel_min {
            self.profile
                .add_kernel_lib_mapping(lib_handle, start_avma, end_avma, 0);
            return;
        }

        let Some(process) = self.processes.get_by_pid(pid) else {
            return;
        };
        let info = if known_category != KnownCategory::Unknown {
            let category = self.categories.get(known_category, &mut self.profile);
            LibMappingInfo::new_lib_with_category(lib_handle, category.into())
        } else {
            LibMappingInfo::new_lib(lib_handle)
        };

        process.regular_lib_mapping_ops.push(
            timestamp_raw,
            LibMappingOp::Add(LibMappingAdd {
                start_avma,
                end_avma,
                relative_address_at_start: 0,
                info,
            }),
        );
    }

    pub fn handle_vsync(&mut self, timestamp_raw: u64) {
        #[derive(Debug, Clone)]
        pub struct VSyncMarker;

        impl StaticSchemaMarker for VSyncMarker {
            const UNIQUE_MARKER_TYPE_NAME: &'static str = "Vsync";

            const LOCATIONS: MarkerLocations = MarkerLocations::MARKER_CHART
                .union(MarkerLocations::MARKER_TABLE)
                .union(MarkerLocations::TIMELINE_OVERVIEW);

            const FIELDS: &'static [StaticSchemaMarkerField] = &[];

            fn name(&self, profile: &mut Profile) -> StringHandle {
                profile.intern_string("Vsync")
            }

            fn category(&self, _profile: &mut Profile) -> CategoryHandle {
                CategoryHandle::OTHER
            }

            fn string_field_value(&self, _field_index: u32) -> StringHandle {
                unreachable!()
            }

            fn number_field_value(&self, _field_index: u32) -> f64 {
                unreachable!()
            }
        }

        let gpu_thread = self.gpu_thread_handle.get_or_insert_with(|| {
            let start_timestamp = Timestamp::from_nanos_since_reference(0);
            let gpu = self.profile.add_process("GPU", 1, start_timestamp);
            self.profile.add_thread(gpu, 1, start_timestamp, false)
        });
        let timestamp = self.timestamp_converter.convert_time(timestamp_raw);
        self.profile
            .add_marker(*gpu_thread, MarkerTiming::Instant(timestamp), VSyncMarker);
    }

    pub fn handle_cswitch(
        &mut self,
        timestamp_raw: u64,
        old_tid: u32,
        new_tid: u32,
        cpu_index: u32,
        wait_reason: i8,
    ) {
        // CSwitch events may or may not have stacks.
        // If they have stacks, the stack will be the stack of new_tid.
        // In other words, if a thread sleeps, the sleeping stack is delivered to us at the end of the sleep,
        // once the CPU starts executing the switched-to thread.
        // (That's different to e.g. Linux with sched_switch samples, which deliver the stack at the start of the sleep, i.e. just before the switch-out.)

        if let Some(old_thread) = self.threads.get_by_tid(old_tid) {
            self.context_switch_handler
                .handle_switch_out(timestamp_raw, &mut old_thread.context_switch_data);

            if let Some(cpus) = &mut self.cpus {
                let combined_thread = cpus.combined_thread_handle();
                let cpu = cpus.get_mut(cpu_index as usize, &mut self.profile);
                self.context_switch_handler
                    .handle_switch_out(timestamp_raw, &mut cpu.context_switch_data);

                if self.profile_creation_props.should_emit_cswitch_markers {
                    // TODO: Find out if this actually is the right way to check whether a thread
                    // has been pre-empted.
                    let preempted = wait_reason == 0 || wait_reason == 32; // "Executive" | "WrPreempted"
                    cpu.notify_switch_out_for_marker(
                        old_tid as i32,
                        timestamp_raw,
                        &self.timestamp_converter,
                        &[cpu.thread_handle, combined_thread],
                        old_thread.handle,
                        preempted,
                        &mut self.profile,
                    );
                }
            }
        }

        if let Some(new_thread) = self.threads.get_by_tid(new_tid) {
            let off_cpu_sample_group = self
                .context_switch_handler
                .handle_switch_in(timestamp_raw, &mut new_thread.context_switch_data);
            let cpu_delta_raw = self
                .context_switch_handler
                .consume_cpu_delta(&mut new_thread.context_switch_data);
            let cpu_delta = self.timestamp_converter.convert_cpu_delta(cpu_delta_raw);
            if let Some(off_cpu_sample_group) = off_cpu_sample_group {
                new_thread
                    .samples_with_pending_stacks
                    .push_back(SampleWithPendingStack {
                        timestamp: timestamp_raw,
                        kernel_stack: None,
                        off_cpu_sample_group: Some(off_cpu_sample_group),
                        cpu_delta,
                        has_on_cpu_sample: false,
                        per_cpu_stuff: None,
                    });
            }
            if let Some(cpus) = &mut self.cpus {
                let combined_thread = cpus.combined_thread_handle();
                let idle_frame_label = cpus.idle_frame_label();
                let cpu = cpus.get_mut(cpu_index as usize, &mut self.profile);

                if let Some(idle_cpu_sample) = self
                    .context_switch_handler
                    .handle_switch_in(timestamp_raw, &mut cpu.context_switch_data)
                {
                    // Add two samples with a stack saying "<Idle>", with zero weight.
                    // This will correctly break up the stack chart to show that nothing was running in the idle time.
                    // This first sample will carry any leftover accumulated running time ("cpu delta"),
                    // and the second sample is placed at the end of the paused time.
                    let cpu_delta_raw = self
                        .context_switch_handler
                        .consume_cpu_delta(&mut cpu.context_switch_data);
                    let cpu_delta = self.timestamp_converter.convert_cpu_delta(cpu_delta_raw);
                    let begin_timestamp = self
                        .timestamp_converter
                        .convert_time(idle_cpu_sample.begin_timestamp);
                    let stack = self.profile.intern_stack_frames(
                        cpu.thread_handle,
                        std::iter::once(idle_frame_label.clone()),
                    );
                    self.profile.add_sample(
                        cpu.thread_handle,
                        begin_timestamp,
                        stack,
                        cpu_delta,
                        0,
                    );

                    // Emit a "rest sample" with a CPU delta of zero covering the rest of the paused range.
                    let end_timestamp = self
                        .timestamp_converter
                        .convert_time(idle_cpu_sample.end_timestamp);
                    self.profile.add_sample(
                        cpu.thread_handle,
                        end_timestamp,
                        stack,
                        CpuDelta::from_nanos(0),
                        0,
                    );
                }
                if self.profile_creation_props.should_emit_cswitch_markers {
                    cpu.notify_switch_in_for_marker(
                        new_tid as i32,
                        new_thread.thread_label(),
                        timestamp_raw,
                        &self.timestamp_converter,
                        &[cpu.thread_handle, combined_thread],
                        &mut self.profile,
                    );
                }
            }
        }
    }

    pub fn handle_js_source_load(
        &mut self,
        timestamp_raw: u64,
        pid: u32,
        source_id: u64,
        url: String,
    ) {
        let Some(process) = self.processes.get_by_pid_and_timestamp(pid, timestamp_raw) else {
            return;
        };

        process.js_sources.insert(source_id, url);
    }

    #[allow(clippy::too_many_arguments)]
    pub fn handle_js_method_load(
        &mut self,
        timestamp_raw: u64,
        pid: u32,
        mut method_name: String,
        method_start_address: u64,
        method_size: u32,
        source_id: u64,
        line: u32,
        column: u32,
    ) {
        let Some(process) = self.processes.get_by_pid_and_timestamp(pid, timestamp_raw) else {
            return;
        };

        let (category, js_frame) = if let Some(url) = process.js_sources.get(&source_id) {
            if method_name.starts_with("JS:") {
                // Probably a JIT frame from a locally patched version of Chrome where
                // we made it prefix the ETW JIT frames with the same prefixes as with
                // the Jitdump backend. The prefix gives us the Jit tier / category.
                self.js_category_manager
                    .classify_jit_symbol(&method_name, &mut self.profile)
            } else {
                // A JIT frame from a regular Chrome / Edge build.
                // For now we just add the script URL at the end of the function name.
                // In the future, we should store the function name and the script URL
                // separately in the profile.
                use std::fmt::Write;
                write!(&mut method_name, " {url}").unwrap();
                if line != 0 {
                    write!(&mut method_name, ":{line}:{column}").unwrap();
                }
                let category = self.js_jit_lib.default_category();
                let js_frame = Some(JsFrame::NativeFrameIsJs);
                (category, js_frame)
            }
        } else {
            // Probably a JIT frame from Firefox. Firefox doesn't emit SourceLoad events yet.
            self.js_category_manager
                .classify_jit_symbol(&method_name, &mut self.profile)
        };

        let lib = &mut self.js_jit_lib;
        let info = LibMappingInfo::new_jit_function(lib.lib_handle(), category, js_frame);

        if self.profile_creation_props.should_emit_jit_markers {
            let name_handle = self.profile.intern_string(&method_name);
            let timestamp = self.timestamp_converter.convert_time(timestamp_raw);
            self.profile.add_marker(
                process.main_thread_handle,
                MarkerTiming::Instant(timestamp),
                JitFunctionAddMarker(name_handle),
            );
        }

        process.add_jit_function(
            timestamp_raw,
            lib,
            method_name,
            method_start_address,
            method_size,
            info,
        );
    }

    pub fn handle_coreclr_method_load(
        &mut self,
        timestamp_raw: u64,
        pid: u32,
        method_name: String,
        method_start_address: u64,
        method_size: u32,
    ) {
        let Some(process) = self.processes.get_by_pid_and_timestamp(pid, timestamp_raw) else {
            return;
        };

        let lib = &mut self.coreclr_jit_lib;
        let info = LibMappingInfo::new_jit_function(lib.lib_handle(), lib.default_category(), None);

        process.add_jit_function(
            timestamp_raw,
            lib,
            method_name,
            method_start_address,
            method_size,
            info,
        );
    }

    pub fn handle_freeform_marker_start(
        &mut self,
        timestamp_raw: u64,
        tid: u32,
        name: &str,
        stringified_properties: String,
    ) {
        let Some(thread) = self.threads.get_by_tid_and_timestamp(tid, timestamp_raw) else {
            return;
        };
        let timestamp = self.timestamp_converter.convert_time(timestamp_raw);
        thread.pending_markers.insert(
            name.to_owned(),
            PendingMarker {
                text: stringified_properties,
                start: timestamp,
            },
        );
    }

    pub fn handle_freeform_marker_end(
        &mut self,
        timestamp_raw: u64,
        tid: u32,
        name: &str,
        stringified_properties: String,
        known_category: KnownCategory,
    ) {
        let Some(thread_handle) = self.thread_handle_at_time(tid, timestamp_raw) else {
            return;
        };
        let Some(thread) = self.threads.get_by_tid_and_timestamp(tid, timestamp_raw) else {
            return;
        };

        let timestamp = self.timestamp_converter.convert_time(timestamp_raw);

        // Combine the start and end markers into a single marker.
        // Alternatively, we could output the start marker with IntervalStart, however this has one big drawback:
        // The text stored in the start marker would not be available in the UI!
        // The Firefox Profiler combines IntervalStart and IntervalEnd marker into a single marker
        // whose data is taken only from the *end* marker.
        // So here we manually merge them, taking the data from the *start* marker.
        let (timing, text) = if let Some(pending) = thread.pending_markers.remove(name) {
            (
                MarkerTiming::Interval(pending.start, timestamp),
                pending.text,
            )
        } else {
            (MarkerTiming::IntervalEnd(timestamp), stringified_properties)
        };

        let category = self.categories.get(known_category, &mut self.profile);
        let name = self.profile.intern_string(name.split_once('/').unwrap().1);
        let description = self.profile.intern_string(&text);
        self.profile.add_marker(
            thread_handle,
            timing,
            FreeformMarker(name, description, category),
        );
    }

    #[allow(clippy::too_many_arguments)]
    pub fn handle_firefox_marker(
        &mut self,
        tid: u32,
        marker_name: &str,
        timestamp_raw: u64,
        start_time_qpc: u64,
        end_time_qpc: u64,
        phase: Option<u8>,
        maybe_user_timing_name: Option<String>,
        maybe_explicit_marker_name: Option<String>,
        text: String,
    ) {
        let Some(thread_handle) = self.thread_handle_at_time(tid, timestamp_raw) else {
            return;
        };

        assert!(self.event_timestamps_are_qpc, "Inconsistent timestamp formats! ETW traces with Firefox events should be captured with QPC timestamps (-ClockType PerfCounter) so that ETW sample timestamps are compatible with the QPC timestamps in Firefox ETW trace events, so that the markers appear in the right place.");
        let (phase, instant_time_qpc): (u8, u64) = match phase {
            Some(phase) => (phase, start_time_qpc),
            None => {
                // Before the landing of https://bugzilla.mozilla.org/show_bug.cgi?id=1882640 ,
                // Firefox ETW trace events didn't have phase information, so we need to
                // guess a phase based on the timestamps.
                if start_time_qpc != 0 && end_time_qpc != 0 {
                    (PHASE_INTERVAL, 0)
                } else if start_time_qpc != 0 {
                    (PHASE_INSTANT, start_time_qpc)
                } else {
                    (PHASE_INSTANT, end_time_qpc)
                }
            }
        };
        let timing = match phase {
            PHASE_INSTANT => {
                MarkerTiming::Instant(self.timestamp_converter.convert_time(instant_time_qpc))
            }
            PHASE_INTERVAL => MarkerTiming::Interval(
                self.timestamp_converter.convert_time(start_time_qpc),
                self.timestamp_converter.convert_time(end_time_qpc),
            ),
            PHASE_INTERVAL_START => {
                MarkerTiming::IntervalStart(self.timestamp_converter.convert_time(start_time_qpc))
            }
            PHASE_INTERVAL_END => {
                MarkerTiming::IntervalEnd(self.timestamp_converter.convert_time(end_time_qpc))
            }
            _ => panic!("Unexpected marker phase {phase}"),
        };

        if marker_name == "UserTiming" {
            let name = self.profile.intern_string(&maybe_user_timing_name.unwrap());
            self.profile
                .add_marker(thread_handle, timing, UserTimingMarker(name));
        } else if marker_name == "SimpleMarker" || marker_name == "Text" || marker_name == "tracing"
        {
            let marker_name = self
                .profile
                .intern_string(&maybe_explicit_marker_name.unwrap());
            let description = self.profile.intern_string(&text);
            self.profile.add_marker(
                thread_handle,
                timing,
                FreeformMarker(marker_name, description, CategoryHandle::OTHER),
            );
        } else {
            let marker_name = self.profile.intern_string(marker_name);
            let description = self.profile.intern_string(&text);
            self.profile.add_marker(
                thread_handle,
                timing,
                FreeformMarker(marker_name, description, CategoryHandle::OTHER),
            );
        }
    }

    #[allow(clippy::too_many_arguments)]
    pub fn handle_chrome_marker(
        &mut self,
        tid: u32,
        timestamp_raw: u64,
        marker_name: &str,
        timestamp_us: u64,
        phase: &str,
        keyword_bitfield: u64,
        text: String,
    ) {
        let Some(thread_handle) = self.thread_handle_at_time(tid, timestamp_raw) else {
            return;
        };

        let timestamp = self.timestamp_converter.convert_us(timestamp_us);

        let timing = match phase {
            "Begin" => MarkerTiming::IntervalStart(timestamp),
            "End" => MarkerTiming::IntervalEnd(timestamp),
            _ => MarkerTiming::Instant(timestamp),
        };
        let keyword = KeywordNames::from_bits(keyword_bitfield).unwrap();
        if keyword == KeywordNames::blink_user_timing {
            let name = self.profile.intern_string(marker_name);
            self.profile
                .add_marker(thread_handle, timing, UserTimingMarker(name));
        } else {
            let marker_name = self.profile.intern_string(marker_name);
            let description = self.profile.intern_string(&text);
            self.profile.add_marker(
                thread_handle,
                timing,
                FreeformMarker(marker_name, description, CategoryHandle::OTHER),
            );
        }
    }

    pub fn handle_unknown_event(
        &mut self,
        timestamp_raw: u64,
        tid: u32,
        task_and_op: &str,
        stringified_properties: String,
    ) {
        if !self.profile_creation_props.unknown_event_markers {
            return;
        }

        let Some(thread_handle) = self.thread_handle_at_time(tid, timestamp_raw) else {
            return;
        };

        let timestamp = self.timestamp_converter.convert_time(timestamp_raw);
        let timing = MarkerTiming::Instant(timestamp);
        // this used to create a new category based on provider_name, just lump them together for now
        let category = self
            .categories
            .get(KnownCategory::Unknown, &mut self.profile);
        let marker_name = self.profile.intern_string(task_and_op);
        let description = self.profile.intern_string(&stringified_properties);
        self.profile.add_marker(
            thread_handle,
            timing,
            FreeformMarker(marker_name, description, category),
        );
        //println!("unhandled {}", s.name())
    }

    pub fn is_in_time_range(&self, ts_raw: u64) -> bool {
        let Some((tstart, tstop)) = self.time_range else {
            return true;
        };

        let ts = self.timestamp_converter.convert_time(ts_raw);
        ts >= tstart && ts < tstop
    }

    pub fn set_os_name(&mut self, os_name: &str) {
        self.profile.set_os_name(os_name);
    }

    pub fn finish(mut self) -> Profile {
        // Push queued samples into the profile.
        // We queue them so that we can get symbolicated JIT function names. To get symbolicated JIT function names,
        // we have to call profile.add_sample after we call profile.set_lib_symbol_table, and we don't have the
        // complete JIT symbol table before we've seen all JIT symbols.
        // (This is a rather weak justification. The better justification is that this is consistent with what
        // samply does on Linux and macOS, where the queued samples also want to respect JIT function names from
        // a /tmp/perf-1234.map file, and this file may not exist until the profiled process finishes.)
        let mut stack_frame_scratch_buf = Vec::new();
        self.js_jit_lib
            .finish_and_set_symbol_table(&mut self.profile);
        self.coreclr_jit_lib
            .finish_and_set_symbol_table(&mut self.profile);
        let process_sample_datas = self.processes.finish();

        let user_category = self.categories.get(KnownCategory::User, &mut self.profile);
        let kernel_category = self
            .categories
            .get(KnownCategory::Kernel, &mut self.profile);

        for process_sample_data in process_sample_datas {
            process_sample_data.flush_samples_to_profile(
                &mut self.profile,
                user_category.into(),
                kernel_category.into(),
                &mut stack_frame_scratch_buf,
                &self.unresolved_stacks,
            )
        }

        log::info!(
            "{} events, {} samples, {} stack-samples",
            self.event_count,
            self.sample_count,
            self.stack_sample_count
        );

        self.profile
    }
}

#[derive(Debug, Clone)]
pub struct PeInfo {
    pub image_size: u32,
    pub image_checksum: u32,
    pub image_timestamp: Option<u32>,
    pub debug_id: Option<DebugId>,
    pub pdb_path: Option<String>,
}

impl PeInfo {
    pub fn new_with_size_and_checksum(image_size: u32, image_checksum: u32) -> Self {
        Self {
            image_size,
            image_checksum,
            image_timestamp: None,
            debug_id: None,
            pdb_path: None,
        }
    }

    pub fn try_from_image_at_path(image_path: &Path) -> Option<Self> {
        let file = std::fs::File::open(image_path).ok()?;
        let mmap = unsafe { memmap2::Mmap::map(&file).ok()? };
        use object::read::pe::{PeFile32, PeFile64};
        let info = match object::FileKind::parse(&mmap[..]).ok()? {
            object::FileKind::Pe32 => Self::from_object(&PeFile32::parse(&mmap[..]).ok()?),
            object::FileKind::Pe64 => Self::from_object(&PeFile64::parse(&mmap[..]).ok()?),
            kind => {
                log::warn!("Unexpected file kind {kind:?} for image file at {image_path:?}");
                return None;
            }
        };
        Some(info)
    }

    pub fn from_object<'a, Pe: object::read::pe::ImageNtHeaders, R: object::ReadRef<'a>>(
        pe: &object::read::pe::PeFile<'a, Pe, R>,
    ) -> Self {
        // The code identifier consists of the `time_date_stamp` field id the COFF header, followed by
        // the `size_of_image` field in the optional header. If the optional PE header is not present,
        // this identifier is `None`.
        let header = pe.nt_headers();
        let image_timestamp = header
            .file_header()
            .time_date_stamp
            .get(object::LittleEndian);
        use object::read::pe::ImageOptionalHeader;
        let image_size = header.optional_header().size_of_image();
        let image_checksum = header.optional_header().check_sum();

        use object::Object;
        let pdb_info = pe.pdb_info().ok().flatten();
        let pdb_path: Option<String> = pdb_info.and_then(|pdb_info| {
            let pdb_path = std::str::from_utf8(pdb_info.path()).ok()?;
            Some(pdb_path.to_string())
        });
        let debug_id: Option<DebugId> = pdb_info
            .and_then(|pdb_info| DebugId::from_guid_age(&pdb_info.guid(), pdb_info.age()).ok());

        Self {
            image_size,
            image_checksum,
            image_timestamp: Some(image_timestamp),
            debug_id,
            pdb_path,
        }
    }

    pub fn lookup_missing_info_from_image_at_path(&mut self, path: &Path) {
        if self.image_timestamp.is_some() && self.debug_id.is_some() && self.pdb_path.is_some() {
            // No extra information needed.
            return;
        }

        let Some(pe_info) = Self::try_from_image_at_path(path) else {
            // The file doesn't exist.
            // This happens for the ghost drivers mentioned here:
            // https://devblogs.microsoft.com/oldnewthing/20160913-00/?p=94305
            // It also happens for files that were removed since the trace was recorded.
            // We can also get here if the trace was recorded on a different machine.
            return;
        };

        if pe_info.image_size != self.image_size || pe_info.image_checksum != self.image_checksum {
            // image_size or image_checksum doesn't match, the file must be a different
            // image than we one we were expecting. Don't use any information from it.
            return;
        }

        if self.image_timestamp.is_none() {
            self.image_timestamp = pe_info.image_timestamp;
        }
        if self.debug_id.is_none() {
            self.debug_id = pe_info.debug_id;
        }
        if self.pdb_path.is_none() {
            self.pdb_path = pe_info.pdb_path;
        }
    }

    pub fn code_id(&self) -> Option<wholesym::CodeId> {
        let timestamp = self.image_timestamp?;
        let image_size = self.image_size;
        Some(wholesym::CodeId::PeCodeId(PeCodeId {
            timestamp,
            image_size,
        }))
    }
}

fn to_stack_frames(
    mut address_iter: impl Iterator<Item = u64>,
    address_classifier: AddressClassifier,
) -> Vec<StackFrame> {
    let Some(first_addr) = address_iter.next() else {
        return Vec::new();
    };
    let first_stack_mode = address_classifier.get_stack_mode(first_addr);
    let mut frames = vec![StackFrame::InstructionPointer(first_addr, first_stack_mode)];

    frames.extend(address_iter.map(|addr| {
        let stack_mode = address_classifier.get_stack_mode(addr);
        StackFrame::ReturnAddress(addr, stack_mode)
    }));
    frames
}

pub fn make_thread_label_frame(
    profile: &mut Profile,
    name: Option<&str>,
    pid: u32,
    tid: u32,
) -> FrameInfo {
    let s = match name {
        Some(name) => format!("{name} (pid: {pid}, tid: {tid})"),
        None => format!("Thread {tid} (pid: {pid}, tid: {tid})"),
    };
    let thread_label = profile.intern_string(&s);
    FrameInfo {
        frame: Frame::Label(thread_label),
        category_pair: CategoryHandle::OTHER.into(),
        flags: FrameFlags::empty(),
    }
}

#[derive(Debug, Clone)]
pub struct FreeformMarker(StringHandle, StringHandle, CategoryHandle);

impl StaticSchemaMarker for FreeformMarker {
    const UNIQUE_MARKER_TYPE_NAME: &'static str = "FreeformMarker";

    const CHART_LABEL: Option<&'static str> = Some("{marker.data.values}");
    const TOOLTIP_LABEL: Option<&'static str> = Some("{marker.name} - {marker.data.values}");
    const TABLE_LABEL: Option<&'static str> = Some("{marker.name} - {marker.data.values");

    const FIELDS: &'static [StaticSchemaMarkerField] = &[StaticSchemaMarkerField {
        key: "values",
        label: "Values",
        format: MarkerFieldFormat::String,
        flags: MarkerFieldFlags::SEARCHABLE,
    }];

    fn name(&self, _profile: &mut Profile) -> StringHandle {
        self.0
    }

    fn category(&self, _profile: &mut Profile) -> CategoryHandle {
        self.2
    }

    fn string_field_value(&self, _field_index: u32) -> StringHandle {
        self.1
    }

    fn number_field_value(&self, _field_index: u32) -> f64 {
        unreachable!()
    }
}

fn extract_filename(path: &str) -> &str {
    match path.rsplit_once(['/', '\\']) {
        Some((_base, file_name)) => file_name,
        None => path,
    }
}