1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
|
// Copyright Epic Games, Inc. All Rights Reserved.
#include "trace_model.h"
#include <zencore/basicfile.h>
#include <zencore/except_fmt.h>
#include <zencore/fmtutils.h>
#include <zencore/intmath.h>
#include <zencore/logging.h>
#include <zencore/scopeguard.h>
#include <zencore/string.h>
#include <zencore/thread.h>
#include <zencore/timer.h>
#include <zenutil/parallelsort.h>
ZEN_THIRD_PARTY_INCLUDES_START
#include <EASTL/hash_map.h>
#include <EASTL/map.h>
#include <EASTL/set.h>
#include <EASTL/sort.h>
#include <EASTL/vector.h>
#include <analysis/analyzer.h>
#include <analysis/dispatcher.h>
#include <trace/trace.h>
ZEN_THIRD_PARTY_INCLUDES_END
#include <algorithm>
#include <cmath>
#include <cstring>
using namespace std::literals;
// Toggle to A/B test cross-platform parallel sort vs sequential eastl::sort.
constexpr bool kUseParallelSort = true;
namespace eastl {
template<>
struct hash<std::string>
{
size_t operator()(const std::string& S) const { return eastl::hash<const char*>()(S.c_str()); }
};
} // namespace eastl
//////////////////////////////////////////////////////////////////////////////
// Trace analysis types (global namespace alongside tourist types)
namespace {
using zen::ReciprocalU64;
// Welford's online algorithm for computing mean and standard deviation
class Distribution
{
public:
void add(double X)
{
m_Count++;
if (m_Count == 1)
{
m_OldM = m_NewM = X;
m_OldS = 0.0;
}
else
{
m_NewM = m_OldM + (X - m_OldM) / double(m_Count);
m_NewS = m_OldS + (X - m_OldM) * (X - m_NewM);
m_OldM = m_NewM;
m_OldS = m_NewS;
}
}
uint32_t Count() const { return m_Count; }
double Mean() const { return (m_Count > 0) ? m_NewM : 0.0; }
double Variance() const { return (m_Count > 1) ? m_NewS / double(m_Count - 1) : 0.0; }
double StdDev() const { return std::sqrt(Variance()); }
private:
double m_OldM = 0.0;
double m_NewM = 0.0;
double m_OldS = 0.0;
double m_NewS = 0.0;
uint32_t m_Count = 0;
};
class NameDepot
{
public:
uint64 Add(StringView Name)
{
uint64 NameHash = Hash(Name);
Add(NameHash, Name);
return NameHash;
}
void Add(uint64 NameHash, StringView Name)
{
if (auto It = m_Names.insert({NameHash, String()}); It.second)
{
It.first->second = Name;
}
}
StringView Get(uint64 NameHash) const
{
auto Iter = m_Names.find(NameHash);
if (Iter == m_Names.end())
{
return "???";
}
return Iter->second;
}
private:
eastl::hash_map<uint64, String> m_Names;
};
struct CpuEventStat
{
Distribution Dist;
uint32_t Min = ~0u;
uint32_t Max = 0;
};
class EventStats
{
public:
void Record(uint64 NameHash, uint32 DurationUs)
{
CpuEventStat& Stat = m_Stats[NameHash];
Stat.Min = std::min(Stat.Min, DurationUs);
Stat.Max = std::max(Stat.Max, DurationUs);
Stat.Dist.add(double(DurationUs));
}
auto begin() const { return m_Stats.begin(); }
auto end() const { return m_Stats.end(); }
bool empty() const { return m_Stats.empty(); }
private:
eastl::hash_map<uint64, CpuEventStat> m_Stats;
};
//////////////////////////////////////////////////////////////////////////////
// Event outlines
// clang-format off
begin_outline($Trace, NewTrace)
field(uint64, CycleFrequency)
field(uint64, StartCycle)
end_outline()
begin_outline(CpuProfiler, EventSpec)
field(uint32, Id)
field(FieldStr, Name)
end_outline()
begin_outline(CpuProfiler, EventBatch)
field(uint32, ThreadId)
field(uint8[], Data)
end_outline()
begin_outline(CpuProfiler, EventBatchV2)
field(uint8[], Data)
end_outline()
begin_outline(CpuProfiler, EventBatchV3)
field(uint8[], Data)
end_outline()
begin_outline(CpuProfiler, Metadata)
field(uint32, Id)
field(uint32, SpecId)
field(uint8[], Metadata)
end_outline()
begin_outline($Trace, ThreadInfo)
field(FieldStr, Name)
field(int32, SortHint)
field(uint32, ThreadId)
field(uint32, SystemId)
end_outline()
begin_outline($Trace, ThreadGroupBegin)
field(FieldStr, Name)
end_outline()
begin_outline($Trace, ThreadGroupEnd)
end_outline()
begin_outline(Diagnostics, Session2)
field(FieldStr, Platform)
field(FieldStr, AppName)
field(FieldStr, ProjectName)
field(FieldStr, CommandLine)
field(FieldStr, Branch)
field(FieldStr, BuildVersion)
field(uint32, Changelist)
field(uint8, ConfigurationType)
field(uint8, TargetType)
end_outline()
begin_outline(Diagnostics, ModuleInit)
field(FieldStr, SymbolFormat)
field(uint8, ModuleBaseShift)
end_outline()
begin_outline(Diagnostics, ModuleLoad)
field(FieldStr, Name)
field(uint64, Base)
field(uint32, Size)
field(uint8[], ImageId)
end_outline()
begin_outline(Diagnostics, ModuleUnload)
field(uint64, Base)
end_outline()
begin_outline(Trace, ChannelAnnounce)
field(uint32, Id)
field(uint8, IsEnabled)
field(uint8, ReadOnly)
field(FieldStr, Name)
end_outline()
begin_outline(Trace, ChannelToggle)
field(uint32, Id)
field(uint8, IsEnabled)
end_outline()
begin_outline(Logging, LogCategory)
field(uint64, CategoryPointer)
field(uint8, DefaultVerbosity)
field(FieldStr, Name)
end_outline()
begin_outline(Logging, LogMessageSpec)
field(uint64, LogPoint)
field(uint64, CategoryPointer)
field(int32, Line)
field(uint8, Verbosity)
field(FieldStr, FileName)
field(FieldStr, FormatString)
end_outline()
begin_outline(Logging, LogMessage)
field(uint64, LogPoint)
field(uint64, Cycle)
field(uint8[], FormatArgs)
end_outline()
begin_outline(Misc, BookmarkSpec)
field(uint64, BookmarkPoint)
field(int32, Line)
field(FieldStr, FormatString)
field(FieldStr, FileName)
end_outline()
begin_outline(Misc, Bookmark)
field(uint64, Cycle)
field(uint64, BookmarkPoint)
field(uint8[], FormatArgs)
end_outline()
begin_outline(Misc, RegionBegin)
field(uint64, Cycle)
field(uint8[], RegionName)
field(uint8[], Category)
end_outline()
begin_outline(Misc, RegionBeginWithId)
field(uint64, CycleAndId)
field(uint8[], RegionName)
field(uint8[], Category)
end_outline()
begin_outline(Misc, RegionEnd)
field(uint64, Cycle)
field(uint8[], RegionName)
end_outline()
begin_outline(Misc, RegionEndWithId)
field(uint64, Cycle)
field(uint64, RegionId)
end_outline()
// CsvProfiler events
begin_outline(CsvProfiler, RegisterCategory)
field(int32, Index)
field(uint8[], Name)
end_outline()
begin_outline(CsvProfiler, DefineInlineStat)
field(uint64, StatId)
field(int32, CategoryIndex)
field(uint8[], Name)
end_outline()
begin_outline(CsvProfiler, DefineDeclaredStat)
field(uint64, StatId)
field(int32, CategoryIndex)
field(uint8[], Name)
end_outline()
begin_outline(CsvProfiler, BeginStat)
field(uint64, StatId)
field(uint64, Cycle)
end_outline()
begin_outline(CsvProfiler, EndStat)
field(uint64, StatId)
field(uint64, Cycle)
end_outline()
begin_outline(CsvProfiler, BeginExclusiveStat)
field(uint64, StatId)
field(uint64, Cycle)
end_outline()
begin_outline(CsvProfiler, EndExclusiveStat)
field(uint64, StatId)
field(uint64, Cycle)
end_outline()
begin_outline(CsvProfiler, CustomStatInt)
field(uint64, StatId)
field(uint64, Cycle)
field(int32, Value)
field(uint8, OpType)
end_outline()
begin_outline(CsvProfiler, CustomStatFloat)
field(uint64, StatId)
field(uint64, Cycle)
field(float, Value)
field(uint8, OpType)
end_outline()
begin_outline(CsvProfiler, Event)
field(uint64, Cycle)
field(int32, CategoryIndex)
field(uint8[], Text)
end_outline()
begin_outline(CsvProfiler, BeginCapture)
field(uint64, Cycle)
field(uint32, RenderThreadId)
field(uint32, RHIThreadId)
field(uint8, EnableCounts)
field(uint8[], FileName)
end_outline()
begin_outline(CsvProfiler, EndCapture)
field(uint64, Cycle)
end_outline()
begin_outline(CsvProfiler, Metadata)
field(uint8[], Key)
field(uint8[], Value)
end_outline()
// clang-format on
//////////////////////////////////////////////////////////////////////////////
// Forward declarations needed by the helper analyzers below.
using zen::trace_detail::SafeFieldStr;
//////////////////////////////////////////////////////////////////////////////
// Minimal CBOR formatter
//
// CpuProfiler.Metadata payloads are CBOR-encoded (RFC 7049) blobs produced
// by UE's FCborWriter. We don't need a full decoder -- we just walk the
// bytes and append human-readable values to an output string. Handles the
// subset actually emitted by UE's metadata scopes: unsigned / negative
// integers, byte / text strings, arrays, maps, floats, and the boolean /
// null simple values.
static bool CborAppendValue(const uint8*& p, const uint8* end, std::string& out, int depth);
static bool
CborReadArg(const uint8*& p, const uint8* end, uint8 info, uint64& value)
{
if (info < 24)
{
value = info;
return true;
}
if (info == 24)
{
if (end - p < 1)
return false;
value = *p++;
return true;
}
if (info == 25)
{
if (end - p < 2)
return false;
value = (uint64(p[0]) << 8) | p[1];
p += 2;
return true;
}
if (info == 26)
{
if (end - p < 4)
return false;
value = (uint64(p[0]) << 24) | (uint64(p[1]) << 16) | (uint64(p[2]) << 8) | p[3];
p += 4;
return true;
}
if (info == 27)
{
if (end - p < 8)
return false;
value = 0;
for (int i = 0; i < 8; ++i)
{
value = (value << 8) | p[i];
}
p += 8;
return true;
}
return false;
}
static bool
CborAppendValue(const uint8*& p, const uint8* end, std::string& out, int depth)
{
if (depth > 4 || p >= end)
{
return false;
}
const uint8 ib = *p++;
const uint8 major = ib >> 5;
const uint8 info = ib & 0x1f;
switch (major)
{
case 0: // unsigned integer
{
uint64 v;
if (!CborReadArg(p, end, info, v))
return false;
out += fmt::format("{}", v);
return true;
}
case 1: // negative integer: -1 - value
{
uint64 v;
if (!CborReadArg(p, end, info, v))
return false;
out += fmt::format("{}", -1 - int64_t(v));
return true;
}
case 2: // byte string
case 3: // text string
{
uint64 len;
if (!CborReadArg(p, end, info, len))
return false;
if (len > uint64(end - p))
return false;
out.append(reinterpret_cast<const char*>(p), size_t(len));
p += len;
return true;
}
case 4: // array
{
uint64 count;
if (!CborReadArg(p, end, info, count))
return false;
for (uint64 i = 0; i < count; ++i)
{
if (i > 0)
out += ", ";
if (!CborAppendValue(p, end, out, depth + 1))
return false;
}
return true;
}
case 5: // map
{
uint64 count;
if (!CborReadArg(p, end, info, count))
return false;
for (uint64 i = 0; i < count; ++i)
{
if (i > 0)
out += ", ";
if (!CborAppendValue(p, end, out, depth + 1))
return false;
out += "=";
if (!CborAppendValue(p, end, out, depth + 1))
return false;
}
return true;
}
case 7: // simple values / floats
{
if (info == 20)
{
out += "false";
return true;
}
if (info == 21)
{
out += "true";
return true;
}
if (info == 22)
{
out += "null";
return true;
}
if (info == 26)
{
if (end - p < 4)
return false;
uint32 bits = (uint32(p[0]) << 24) | (uint32(p[1]) << 16) | (uint32(p[2]) << 8) | p[3];
float v;
std::memcpy(&v, &bits, 4);
out += fmt::format("{}", v);
p += 4;
return true;
}
if (info == 27)
{
if (end - p < 8)
return false;
uint64 bits = 0;
for (int i = 0; i < 8; ++i)
{
bits = (bits << 8) | p[i];
}
p += 8;
double v;
std::memcpy(&v, &bits, 8);
out += fmt::format("{}", v);
return true;
}
return false;
}
default:
return false;
}
}
static std::string
FormatMetadataValues(const uint8_t* Bytes, size_t Size)
{
std::string out;
if (Size == 0)
{
return out;
}
const uint8* p = Bytes;
CborAppendValue(p, Bytes + Size, out, 0);
return out;
}
using zen::trace_detail::TraceTiming;
//////////////////////////////////////////////////////////////////////////////
// Metadata registry
//
// Subscribes to CpuProfiler.Metadata events and stores each payload's
// CBOR-encoded bytes keyed by MetadataId, along with the SpecId they
// reference. Both CpuAnalyzer and TimelineAnalyzer query the registry when
// they encounter a V3 scope with the metadata bit set so the scope can be
// rendered as `{base name} - {formatted values}`.
struct MetadataEntry
{
uint32_t SpecId = 0;
eastl::vector<uint8_t> Bytes;
};
class MetadataRegistry : public Analyzer
{
public:
void subscribe(Vector<Subscription>& Subs) override { Subs.emplace_back(this, &MetadataRegistry::OnMetadata); }
const MetadataEntry* Lookup(uint32_t MetadataId) const
{
auto It = m_Entries.find(MetadataId);
return (It != m_Entries.end()) ? &It->second : nullptr;
}
private:
void OnMetadata(const CpuProfiler_Metadata& Ev)
{
uint32_t MetadataId = Ev.Id();
uint32_t SpecId = Ev.SpecId();
Array<uint8[]> Data = Ev.Metadata();
MetadataEntry& Entry = m_Entries[MetadataId];
Entry.SpecId = SpecId;
Entry.Bytes.assign(Data.get(), Data.get() + Data.get_size());
}
eastl::hash_map<uint32_t, MetadataEntry> m_Entries;
};
//////////////////////////////////////////////////////////////////////////////
// Log message formatting
//
// UE's trace emits log messages as a sequence of typed arguments that need
// to be substituted into a printf-style format string. The wire format is:
//
// [ArgumentCount: uint8]
// [Descriptors: uint8 * ArgumentCount] // each byte = category | size
// [Payload: bytes]
//
// Category bits live in the upper 2 bits (shifted by FormatArgTypeCode_-
// CategoryBitShift == 6): Integer=1, Float=2, String=3. The low 6 bits are
// the argument size in bytes; for strings the size is the per-character
// width (1 == ANSI, 2 == UTF-16).
//
// We walk the format string, extract each specifier, pull the matching arg
// from the stream and hand both to std::snprintf. Width/precision stars
// (e.g. "%*.*f") are not supported; they're rare in log formats.
struct FormatArgStream
{
const uint8_t* Descriptors;
const uint8_t* Payload;
uint8_t Remaining;
bool HasNext() const { return Remaining > 0; }
uint8_t PeekCategory() const { return (*Descriptors) & 0xC0; }
uint8_t PeekSize() const { return (*Descriptors) & 0x3F; }
void Advance(size_t PayloadBytes)
{
Payload += PayloadBytes;
++Descriptors;
--Remaining;
}
};
static bool
InitFormatArgStream(FormatArgStream& Ctx, const uint8_t* Data, size_t Size)
{
if (!Data || Size == 0)
{
Ctx.Remaining = 0;
return false;
}
uint8_t Count = Data[0];
if (size_t(1) + Count > Size)
{
Ctx.Remaining = 0;
return false;
}
Ctx.Descriptors = Data + 1;
Ctx.Payload = Data + 1 + Count;
Ctx.Remaining = Count;
return true;
}
static bool
IsPrintfSpecifierChar(char c)
{
switch (c)
{
case 'd':
case 'i':
case 'u':
case 'o':
case 'x':
case 'X':
case 'c':
case 'p':
case 'f':
case 'F':
case 'e':
case 'E':
case 'g':
case 'G':
case 'a':
case 'A':
case 's':
case 'S':
case 'n':
return true;
default:
return false;
}
}
static std::string
FormatLogMessage(std::string_view Format, const uint8_t* ArgsData, size_t ArgsSize)
{
FormatArgStream Stream{};
InitFormatArgStream(Stream, ArgsData, ArgsSize);
std::string Out;
Out.reserve(Format.size() + 32);
size_t i = 0;
while (i < Format.size())
{
char c = Format[i];
if (c != '%')
{
Out.push_back(c);
++i;
continue;
}
// Handle "%%" -> literal percent.
if (i + 1 < Format.size() && Format[i + 1] == '%')
{
Out.push_back('%');
i += 2;
continue;
}
// Walk the specifier until we find a terminating character.
size_t SpecStart = i++;
while (i < Format.size() && !IsPrintfSpecifierChar(Format[i]))
{
++i;
}
if (i >= Format.size())
{
// Truncated specifier -- copy the remainder literally.
Out.append(Format.substr(SpecStart));
break;
}
char Specifier = Format[i++];
std::string Spec(Format.substr(SpecStart, i - SpecStart));
if (!Stream.HasNext())
{
// Not enough arguments: emit the raw specifier so the user can
// at least tell something is missing.
Out.append(Spec);
continue;
}
const uint8_t Category = Stream.PeekCategory();
const uint8_t Size = Stream.PeekSize();
char Buf[512];
Buf[0] = '\0';
if (Category == 0x40) // integer
{
uint64_t Raw = 0;
if (Size <= sizeof(Raw) && Size > 0)
{
std::memcpy(&Raw, Stream.Payload, Size);
}
// Route through the correct snprintf type based on the
// specifier. Cast to int64_t for signed integer specifiers.
switch (Specifier)
{
case 'd':
case 'i':
{
// Sign-extend based on Size.
int64_t Signed = 0;
switch (Size)
{
case 1:
Signed = int8_t(Raw & 0xff);
break;
case 2:
Signed = int16_t(Raw & 0xffff);
break;
case 4:
Signed = int32_t(Raw & 0xffffffff);
break;
case 8:
Signed = int64_t(Raw);
break;
default:
Signed = int64_t(Raw);
break;
}
// Replace length modifier so snprintf interprets the
// correctly-sized value. Simplest: append "ll".
std::string AdjustedSpec = Spec;
AdjustedSpec.insert(AdjustedSpec.size() - 1, "ll");
std::snprintf(Buf, sizeof(Buf), AdjustedSpec.c_str(), static_cast<long long>(Signed));
break;
}
case 'u':
case 'o':
case 'x':
case 'X':
case 'p':
{
std::string AdjustedSpec = Spec;
AdjustedSpec.insert(AdjustedSpec.size() - 1, "ll");
std::snprintf(Buf, sizeof(Buf), AdjustedSpec.c_str(), static_cast<unsigned long long>(Raw));
break;
}
case 'c':
{
std::snprintf(Buf, sizeof(Buf), Spec.c_str(), int(Raw & 0xff));
break;
}
default:
std::snprintf(Buf, sizeof(Buf), "%llu", static_cast<unsigned long long>(Raw));
break;
}
Stream.Advance(Size);
}
else if (Category == 0x80) // floating point
{
double Value = 0.0;
if (Size == 4)
{
float F;
std::memcpy(&F, Stream.Payload, 4);
Value = double(F);
}
else if (Size == 8)
{
std::memcpy(&Value, Stream.Payload, 8);
}
std::snprintf(Buf, sizeof(Buf), Spec.c_str(), Value);
Stream.Advance(Size);
}
else if (Category == 0xC0) // string
{
std::string Tmp;
if (Size == 1)
{
const char* S = reinterpret_cast<const char*>(Stream.Payload);
size_t Len = std::strlen(S);
Tmp.assign(S, Len);
std::snprintf(Buf, sizeof(Buf), Spec.c_str(), Tmp.c_str());
Stream.Advance(Len + 1);
}
else if (Size == 2)
{
const char16_t* W = reinterpret_cast<const char16_t*>(Stream.Payload);
size_t Len = 0;
while (W[Len] != 0)
++Len;
Tmp.reserve(Len);
for (size_t k = 0; k < Len; ++k)
{
char16_t ch = W[k];
Tmp.push_back(ch < 0x80 ? char(ch) : '?');
}
std::snprintf(Buf, sizeof(Buf), Spec.c_str(), Tmp.c_str());
Stream.Advance((Len + 1) * 2);
}
else
{
std::snprintf(Buf, sizeof(Buf), "<unsupported string width %u>", unsigned(Size));
Stream.Advance(0);
++Stream.Descriptors;
--Stream.Remaining;
}
}
else
{
std::snprintf(Buf, sizeof(Buf), "<arg>");
Stream.Advance(Size);
}
Out.append(Buf);
}
return Out;
}
//////////////////////////////////////////////////////////////////////////////
// Log analyzer
class LogAnalyzer : public Analyzer
{
public:
explicit LogAnalyzer(const TraceTiming* Timing = nullptr) : m_Timing(Timing) {}
void subscribe(Vector<Subscription>& Subs) override
{
Subs.emplace_back(this, &LogAnalyzer::OnLogCategory);
Subs.emplace_back(this, &LogAnalyzer::OnLogMessageSpec);
Subs.emplace_back(this, &LogAnalyzer::OnLogMessage);
}
eastl::vector<zen::trace_detail::LogCategoryInfo> BuildCategories(eastl::hash_map<uint64_t, uint32_t>& OutPointerToIndex) const
{
eastl::vector<zen::trace_detail::LogCategoryInfo> Cats;
Cats.reserve(m_Categories.size());
OutPointerToIndex.clear();
for (const auto& [Ptr, Info] : m_Categories)
{
OutPointerToIndex[Ptr] = uint32_t(Cats.size());
Cats.push_back(Info);
}
return Cats;
}
const eastl::vector<zen::trace_detail::LogEntry>& Entries() const { return m_Entries; }
eastl::vector<zen::trace_detail::LogEntry>& MutableEntries() { return m_Entries; }
// The shared TraceTiming pointer lets external callers read the trace's
// cycle base / frequency without each analyzer having to own a copy.
const TraceTiming* Timing() const { return m_Timing; }
struct MessageSpec
{
uint64_t CategoryPointer = 0;
int32_t Line = 0;
uint8_t Verbosity = 0;
std::string File;
std::string FormatString;
};
const eastl::hash_map<uint64_t, MessageSpec>& MessageSpecs() const { return m_Specs; }
private:
void OnLogCategory(const Logging_LogCategory& Ev)
{
uint64_t Ptr = Ev.CategoryPointer();
zen::trace_detail::LogCategoryInfo& Info = m_Categories[Ptr];
Info.Name = SafeFieldStr(Ev.Name());
Info.DefaultVerbosity = Ev.DefaultVerbosity();
}
void OnLogMessageSpec(const Logging_LogMessageSpec& Ev)
{
MessageSpec& Spec = m_Specs[Ev.LogPoint()];
Spec.CategoryPointer = Ev.CategoryPointer();
Spec.Line = Ev.Line();
Spec.Verbosity = Ev.Verbosity();
Spec.File = SafeFieldStr(Ev.FileName());
Spec.FormatString = SafeFieldStr(Ev.FormatString());
}
void OnLogMessage(const Logging_LogMessage& Ev)
{
uint64_t LogPoint = Ev.LogPoint();
auto SpecIt = m_Specs.find(LogPoint);
if (SpecIt == m_Specs.end())
{
return;
}
const MessageSpec& Spec = SpecIt->second;
uint32_t TimeUs = m_Timing ? m_Timing->CycleToTimeUs(Ev.Cycle()) : 0;
Array<uint8[]> Args = Ev.FormatArgs();
std::string Msg = FormatLogMessage(std::string_view(Spec.FormatString), Args.get(), Args.get_size());
zen::trace_detail::LogEntry Entry;
Entry.TimeUs = TimeUs;
Entry.CategoryIndex = ~0u; // resolved in BuildTraceModel
Entry.Verbosity = Spec.Verbosity;
Entry.Line = Spec.Line;
Entry.File = Spec.File;
Entry.Message = std::move(Msg);
// Use the category pointer temporarily so BuildTraceModel can resolve
// it against the categories table.
Entry.CategoryIndex = SpecToCategoryIndex(Spec.CategoryPointer);
m_Entries.push_back(std::move(Entry));
}
uint32_t SpecToCategoryIndex(uint64_t Ptr)
{
// Encoded pointer stuffed into uint32_t so BuildTraceModel can remap.
// Lossy but deterministic: use a stable sequential index per unique
// pointer so we never need the full 64-bit value beyond build time.
auto It = m_CategoryIndex.find(Ptr);
if (It != m_CategoryIndex.end())
{
return It->second;
}
uint32_t Idx = uint32_t(m_CategoryIndex.size());
m_CategoryIndex[Ptr] = Idx;
return Idx;
}
public:
// Mapping from the intermediate index stored in LogEntry::CategoryIndex
// during capture to the real category pointer; BuildTraceModel uses
// this to remap entries against the flattened LogCategories array.
const eastl::hash_map<uint64_t, uint32_t>& CategoryPointerIndex() const { return m_CategoryIndex; }
private:
const TraceTiming* m_Timing = nullptr;
eastl::hash_map<uint64_t, zen::trace_detail::LogCategoryInfo> m_Categories;
eastl::hash_map<uint64_t, MessageSpec> m_Specs;
eastl::hash_map<uint64_t, uint32_t> m_CategoryIndex;
eastl::vector<zen::trace_detail::LogEntry> m_Entries;
};
//////////////////////////////////////////////////////////////////////////////
// Bookmarks and regions
//
// UE's bookmark wire format mirrors LogMessage: a BookmarkSpec introduces
// a (FileName, Line, FormatString) triple keyed by a BookmarkPoint pointer,
// and each Misc.Bookmark event carries that pointer, a cycle, and the same
// FFormatArgsTrace payload the log pipeline already knows how to decode.
// Region events come in two flavours: the legacy name-paired
// RegionBegin/RegionEnd and the newer *WithId variants that pack a unique
// id into the begin event's cycle.
class BookmarksAnalyzer : public Analyzer
{
public:
explicit BookmarksAnalyzer(const TraceTiming* Timing = nullptr) : m_Timing(Timing) {}
void subscribe(Vector<Subscription>& Subs) override
{
Subs.emplace_back(this, &BookmarksAnalyzer::OnBookmarkSpec);
Subs.emplace_back(this, &BookmarksAnalyzer::OnBookmark);
Subs.emplace_back(this, &BookmarksAnalyzer::OnRegionBegin);
Subs.emplace_back(this, &BookmarksAnalyzer::OnRegionBeginWithId);
Subs.emplace_back(this, &BookmarksAnalyzer::OnRegionEnd);
Subs.emplace_back(this, &BookmarksAnalyzer::OnRegionEndWithId);
}
eastl::vector<zen::trace_detail::Bookmark>& MutableBookmarks() { return m_Bookmarks; }
eastl::vector<zen::trace_detail::RegionEntry>& MutableRegions() { return m_Regions; }
private:
struct BookmarkSpec
{
int32_t Line = 0;
std::string File;
std::string FormatString;
};
uint32_t CycleToTimeUs(uint64_t Cycle) const { return m_Timing ? m_Timing->CycleToTimeUs(Cycle) : 0; }
void OnBookmarkSpec(const Misc_BookmarkSpec& Ev)
{
BookmarkSpec& Spec = m_Specs[Ev.BookmarkPoint()];
Spec.Line = Ev.Line();
Spec.File = SafeFieldStr(Ev.FileName());
Spec.FormatString = SafeFieldStr(Ev.FormatString());
}
void OnBookmark(const Misc_Bookmark& Ev)
{
auto SpecIt = m_Specs.find(Ev.BookmarkPoint());
if (SpecIt == m_Specs.end())
{
return;
}
const BookmarkSpec& Spec = SpecIt->second;
Array<uint8[]> Args = Ev.FormatArgs();
std::string Text = FormatLogMessage(std::string_view(Spec.FormatString), Args.get(), Args.get_size());
zen::trace_detail::Bookmark Out;
Out.TimeUs = CycleToTimeUs(Ev.Cycle());
Out.Line = Spec.Line;
Out.File = Spec.File;
Out.Text = std::move(Text);
m_Bookmarks.push_back(std::move(Out));
}
uint32_t CreatePartialRegion(uint32_t TimeUs, std::string Name, std::string Category)
{
zen::trace_detail::RegionEntry Entry;
Entry.BeginUs = TimeUs;
Entry.EndUs = ~uint32_t(0); // sentinel: still open
Entry.Depth = 0;
Entry.Reserved = 0;
Entry.Name = std::move(Name);
Entry.Category = std::move(Category);
uint32_t Idx = uint32_t(m_Regions.size());
m_Regions.push_back(std::move(Entry));
return Idx;
}
// Decodes the raw array bytes of a RegionName field into a std::string.
// UE emits RegionName as either AnsiString (1-byte) or WideString (2-byte)
// depending on the trace's age -- for the 2-byte case we do the same
// lossy ASCII fold tourist's FieldStr does, which is all we need for
// display.
static std::string DecodeRegionName(const Array<uint8[]>& Data)
{
const uint8_t* p = Data.get();
size_t size = Data.get_size();
uint32_t count = Data.get_count();
if (!p || size == 0 || count == 0)
{
return {};
}
if (size == count)
{
// 1 byte per element -- AnsiString.
return std::string(reinterpret_cast<const char*>(p), count);
}
if (size == count * 2)
{
// 2 bytes per element -- WideString. Lossy ASCII fold.
std::string out;
out.reserve(count);
const char16_t* w = reinterpret_cast<const char16_t*>(p);
for (uint32_t i = 0; i < count; ++i)
{
out.push_back(w[i] < 0x80 ? char(w[i]) : '?');
}
return out;
}
return {};
}
void OnRegionBegin(const Misc_RegionBegin& Ev)
{
uint32_t TimeUs = CycleToTimeUs(Ev.Cycle());
Array<uint8[]> NameArr = Ev.RegionName();
std::string Name = DecodeRegionName(NameArr);
std::string Category = DecodeRegionName(Ev.Category());
uint32_t Idx = CreatePartialRegion(TimeUs, Name, std::move(Category));
m_OpenByName[Name].push_back(Idx);
}
void OnRegionBeginWithId(const Misc_RegionBeginWithId& Ev)
{
// Despite its name, CycleAndId is just Cycles64() -- a plain 64-bit
// cycle count that doubles as a unique region identifier. The caller
// keeps the returned value and passes it back as RegionId at end.
uint64_t CycleAndId = Ev.CycleAndId();
uint32_t TimeUs = CycleToTimeUs(CycleAndId);
Array<uint8[]> NameArr = Ev.RegionName();
std::string Name = DecodeRegionName(NameArr);
std::string Category = DecodeRegionName(Ev.Category());
uint32_t Idx = CreatePartialRegion(TimeUs, std::move(Name), std::move(Category));
m_OpenById[CycleAndId] = Idx;
}
void OnRegionEnd(const Misc_RegionEnd& Ev)
{
uint32_t TimeUs = CycleToTimeUs(Ev.Cycle());
Array<uint8[]> NameArr = Ev.RegionName();
std::string Name = DecodeRegionName(NameArr);
auto It = m_OpenByName.find(Name);
if (It == m_OpenByName.end() || It->second.empty())
{
return;
}
uint32_t Idx = It->second.back();
It->second.pop_back();
m_Regions[Idx].EndUs = TimeUs;
}
void OnRegionEndWithId(const Misc_RegionEndWithId& Ev)
{
uint32_t TimeUs = CycleToTimeUs(Ev.Cycle());
uint64_t Id = Ev.RegionId();
auto It = m_OpenById.find(Id);
if (It == m_OpenById.end())
{
return;
}
m_Regions[It->second].EndUs = TimeUs;
m_OpenById.erase(It);
}
const TraceTiming* m_Timing = nullptr;
eastl::hash_map<uint64_t, BookmarkSpec> m_Specs;
eastl::vector<zen::trace_detail::Bookmark> m_Bookmarks;
eastl::vector<zen::trace_detail::RegionEntry> m_Regions;
eastl::hash_map<std::string, eastl::vector<uint32_t>> m_OpenByName;
eastl::hash_map<uint64_t, uint32_t> m_OpenById;
};
//////////////////////////////////////////////////////////////////////////////
// CsvProfiler analyzer -- parses CSV stat categories, definitions, timing,
// custom values, events, capture markers, and metadata.
class CsvProfilerAnalyzer : public Analyzer
{
public:
explicit CsvProfilerAnalyzer(const TraceTiming* Timing = nullptr) : m_Timing(Timing) {}
void subscribe(Vector<Subscription>& Subs) override
{
Subs.emplace_back(this, &CsvProfilerAnalyzer::OnRegisterCategory);
Subs.emplace_back(this, &CsvProfilerAnalyzer::OnDefineInlineStat);
Subs.emplace_back(this, &CsvProfilerAnalyzer::OnDefineDeclaredStat);
Subs.emplace_back(this, &CsvProfilerAnalyzer::OnBeginStat);
Subs.emplace_back(this, &CsvProfilerAnalyzer::OnEndStat);
Subs.emplace_back(this, &CsvProfilerAnalyzer::OnBeginExclusiveStat);
Subs.emplace_back(this, &CsvProfilerAnalyzer::OnEndExclusiveStat);
Subs.emplace_back(this, &CsvProfilerAnalyzer::OnCustomStatInt);
Subs.emplace_back(this, &CsvProfilerAnalyzer::OnCustomStatFloat);
Subs.emplace_back(this, &CsvProfilerAnalyzer::OnEvent);
Subs.emplace_back(this, &CsvProfilerAnalyzer::OnBeginCapture);
Subs.emplace_back(this, &CsvProfilerAnalyzer::OnEndCapture);
Subs.emplace_back(this, &CsvProfilerAnalyzer::OnMetadata);
}
eastl::vector<zen::trace_detail::TraceModel::CsvCategory>& MutableCategories() { return m_Categories; }
eastl::vector<zen::trace_detail::TraceModel::CsvStatDef>& MutableStatDefs() { return m_StatDefs; }
eastl::vector<zen::trace_detail::TraceModel::CsvEvent>& MutableEvents() { return m_Events; }
eastl::vector<zen::trace_detail::TraceModel::CsvMeta>& MutableMetadata() { return m_Metadata; }
// Build the per-stat+thread time series from the accumulated samples.
eastl::vector<zen::trace_detail::TraceModel::CsvSeries> BuildTimeSeries()
{
eastl::vector<zen::trace_detail::TraceModel::CsvSeries> Result;
for (auto& [Key, Samples] : m_SeriesMap)
{
eastl::sort(Samples.begin(), Samples.end(), [](const auto& A, const auto& B) { return A.TimeUs < B.TimeUs; });
zen::trace_detail::TraceModel::CsvSeries S;
S.StatId = Key.StatId;
S.ThreadId = Key.ThreadId;
S.Samples = std::move(Samples);
Result.push_back(std::move(S));
}
return Result;
}
private:
uint32_t CycleToTimeUs(uint64_t Cycle) const
{
if (!m_Timing || m_Timing->Freq == 0)
{
return 0;
}
uint64_t Elapsed = (Cycle >= m_Timing->Base) ? (Cycle - m_Timing->Base) : 0;
return uint32_t(Elapsed * 1'000'000 / m_Timing->Freq);
}
static std::string DecodeAnsiName(const Array<uint8[]>& Data)
{
const uint8_t* P = Data.get();
size_t Size = Data.get_size();
if (!P || Size == 0)
{
return {};
}
return std::string(reinterpret_cast<const char*>(P), Size);
}
static std::string DecodeWideName(const Array<uint8[]>& Data)
{
const uint8_t* P = Data.get();
size_t Size = Data.get_size();
uint32_t Count = Data.get_count();
if (!P || Size == 0 || Count == 0)
{
return {};
}
uint32_t ElemSize = Data.get_element_size();
if (ElemSize == 2)
{
std::string Out;
Out.reserve(Count);
const char16_t* W = reinterpret_cast<const char16_t*>(P);
for (uint32_t I = 0; I < Count; ++I)
{
Out.push_back(W[I] < 0x80 ? char(W[I]) : '?');
}
return Out;
}
return std::string(reinterpret_cast<const char*>(P), Size);
}
struct SeriesKey
{
uint64_t StatId;
uint32_t ThreadId;
bool operator==(const SeriesKey& O) const { return StatId == O.StatId && ThreadId == O.ThreadId; }
};
struct SeriesKeyHash
{
size_t operator()(const SeriesKey& K) const
{
return eastl::hash<uint64_t>{}(K.StatId) ^ (eastl::hash<uint32_t>{}(K.ThreadId) * 2654435761u);
}
};
void AddSample(uint64_t StatId, uint32_t ThreadId, uint32_t TimeUs, float Value)
{
m_SeriesMap[SeriesKey{StatId, ThreadId}].push_back({TimeUs, Value});
}
// -- Event handlers -----------------------------------------------
void OnRegisterCategory(const CsvProfiler_RegisterCategory& Ev)
{
zen::trace_detail::TraceModel::CsvCategory Cat;
Cat.Index = Ev.Index();
Cat.Name = DecodeAnsiName(Ev.Name());
m_Categories.push_back(std::move(Cat));
}
void OnDefineInlineStat(const CsvProfiler_DefineInlineStat& Ev)
{
DefineStat(Ev.StatId(), Ev.CategoryIndex(), DecodeAnsiName(Ev.Name()));
}
void OnDefineDeclaredStat(const CsvProfiler_DefineDeclaredStat& Ev)
{
DefineStat(Ev.StatId(), Ev.CategoryIndex(), DecodeAnsiName(Ev.Name()));
}
void DefineStat(uint64_t StatId, int32_t CategoryIndex, std::string Name)
{
if (m_StatIdToIndex.count(StatId))
{
return; // already defined
}
m_StatIdToIndex[StatId] = uint32_t(m_StatDefs.size());
zen::trace_detail::TraceModel::CsvStatDef Def;
Def.StatId = StatId;
Def.CategoryIndex = CategoryIndex;
Def.Name = std::move(Name);
m_StatDefs.push_back(std::move(Def));
}
void OnBeginStat(const CsvProfiler_BeginStat& Ev)
{
uint32_t ThreadId = Ev.get_thread_id();
uint32_t TimeUs = CycleToTimeUs(Ev.Cycle());
m_OpenStacks[{Ev.StatId(), ThreadId}].push_back(TimeUs);
}
void OnEndStat(const CsvProfiler_EndStat& Ev)
{
uint32_t ThreadId = Ev.get_thread_id();
uint32_t TimeUs = CycleToTimeUs(Ev.Cycle());
auto Key = SeriesKey{Ev.StatId(), ThreadId};
auto It = m_OpenStacks.find(Key);
if (It == m_OpenStacks.end() || It->second.empty())
{
return;
}
uint32_t BeginUs = It->second.back();
It->second.pop_back();
float DurationMs = float(TimeUs - BeginUs) / 1000.0f;
AddSample(Ev.StatId(), ThreadId, BeginUs, DurationMs);
}
void OnBeginExclusiveStat(const CsvProfiler_BeginExclusiveStat& Ev)
{
// For basic support, treat exclusive stats like regular stats.
uint32_t ThreadId = Ev.get_thread_id();
uint32_t TimeUs = CycleToTimeUs(Ev.Cycle());
m_OpenStacks[{Ev.StatId(), ThreadId}].push_back(TimeUs);
}
void OnEndExclusiveStat(const CsvProfiler_EndExclusiveStat& Ev)
{
uint32_t ThreadId = Ev.get_thread_id();
uint32_t TimeUs = CycleToTimeUs(Ev.Cycle());
auto Key = SeriesKey{Ev.StatId(), ThreadId};
auto It = m_OpenStacks.find(Key);
if (It == m_OpenStacks.end() || It->second.empty())
{
return;
}
uint32_t BeginUs = It->second.back();
It->second.pop_back();
float DurationMs = float(TimeUs - BeginUs) / 1000.0f;
AddSample(Ev.StatId(), ThreadId, BeginUs, DurationMs);
}
void OnCustomStatInt(const CsvProfiler_CustomStatInt& Ev)
{
uint32_t ThreadId = Ev.get_thread_id();
uint32_t TimeUs = CycleToTimeUs(Ev.Cycle());
AddSample(Ev.StatId(), ThreadId, TimeUs, float(Ev.Value()));
}
void OnCustomStatFloat(const CsvProfiler_CustomStatFloat& Ev)
{
uint32_t ThreadId = Ev.get_thread_id();
uint32_t TimeUs = CycleToTimeUs(Ev.Cycle());
AddSample(Ev.StatId(), ThreadId, TimeUs, Ev.Value());
}
void OnEvent(const CsvProfiler_Event& Ev)
{
zen::trace_detail::TraceModel::CsvEvent E;
E.TimeUs = CycleToTimeUs(Ev.Cycle());
E.CategoryIndex = Ev.CategoryIndex();
E.Text = DecodeWideName(Ev.Text());
m_Events.push_back(std::move(E));
}
void OnBeginCapture(const CsvProfiler_BeginCapture& Ev) { m_CaptureStartUs = CycleToTimeUs(Ev.Cycle()); }
void OnEndCapture(const CsvProfiler_EndCapture& Ev) { m_CaptureEndUs = CycleToTimeUs(Ev.Cycle()); }
void OnMetadata(const CsvProfiler_Metadata& Ev)
{
zen::trace_detail::TraceModel::CsvMeta M;
M.Key = DecodeWideName(Ev.Key());
M.Value = DecodeWideName(Ev.Value());
m_Metadata.push_back(std::move(M));
}
const TraceTiming* m_Timing = nullptr;
eastl::vector<zen::trace_detail::TraceModel::CsvCategory> m_Categories;
eastl::vector<zen::trace_detail::TraceModel::CsvStatDef> m_StatDefs;
eastl::hash_map<uint64_t, uint32_t> m_StatIdToIndex;
// Timing stacks: (StatId, ThreadId) -> stack of begin times
eastl::hash_map<SeriesKey, eastl::vector<uint32_t>, SeriesKeyHash> m_OpenStacks;
// Accumulated samples: (StatId, ThreadId) -> samples
eastl::hash_map<SeriesKey, eastl::vector<zen::trace_detail::TraceModel::CsvSample>, SeriesKeyHash> m_SeriesMap;
eastl::vector<zen::trace_detail::TraceModel::CsvEvent> m_Events;
eastl::vector<zen::trace_detail::TraceModel::CsvMeta> m_Metadata;
uint32_t m_CaptureStartUs = 0;
uint32_t m_CaptureEndUs = 0;
};
//////////////////////////////////////////////////////////////////////////////
// Analyzers
class CpuAnalyzer : public Analyzer
{
public:
CpuAnalyzer(EventStats& Stats, NameDepot& Names, const MetadataRegistry* Metadata)
: m_Names(Names)
, m_Stats(Stats)
, m_Metadata(Metadata)
{
Names.Add(NO_NAME, "???");
}
void subscribe(Vector<Subscription>& Subs) override
{
Subs.emplace_back(this, &CpuAnalyzer::OnNewTrace);
Subs.emplace_back(this, &CpuAnalyzer::OnCpuSpec);
Subs.emplace_back(this, &CpuAnalyzer::OnCpuBatch);
Subs.emplace_back(this, &CpuAnalyzer::OnCpuBatchV2);
Subs.emplace_back(this, &CpuAnalyzer::OnCpuBatchV3);
}
private:
static constexpr uint32 NO_INDEX = ~0u;
static constexpr uint64 NO_NAME = ~0ull;
static constexpr uint32 METADATA_BIT = 0x8000'0000u;
uint64 ResolveNameHash(uint32 PackedId)
{
const bool IsMetadata = (PackedId & METADATA_BIT) != 0;
const uint32 Id = PackedId & ~METADATA_BIT;
if (IsMetadata && m_Metadata)
{
auto CachedIt = m_MetadataNames.find(Id);
if (CachedIt != m_MetadataNames.end())
{
return CachedIt->second;
}
const MetadataEntry* Entry = m_Metadata->Lookup(Id);
if (Entry)
{
auto BaseIt = m_Specs.find(Entry->SpecId);
StringView BaseName = (BaseIt != m_Specs.end()) ? m_Names.Get(BaseIt->second) : StringView("???");
std::string Formatted(BaseName);
std::string Values = FormatMetadataValues(Entry->Bytes.data(), Entry->Bytes.size());
if (!Values.empty())
{
Formatted += " - ";
Formatted += Values;
}
uint64 Hash = m_Names.Add(StringView(Formatted));
m_MetadataNames[Id] = Hash;
return Hash;
}
return NO_NAME;
}
auto It = m_Specs.find(Id);
return (It != m_Specs.end()) ? It->second : NO_NAME;
}
struct EventStack
{
uint32 Tail = NO_INDEX;
};
struct ScopeEvent
{
uint32 Id;
uint32 TimeUs;
union
{
uint32 Next;
uint32 Index;
};
};
struct EventPool
{
uint32 Alloc()
{
if (m_FreeHead == NO_INDEX)
{
uint32 Idx = uint32(m_Pool.size());
m_Pool.push_back({.Index = Idx});
return Idx;
}
uint32 Idx = m_FreeHead;
m_FreeHead = m_Pool[Idx].Index;
return Idx;
}
void Free(uint32 Idx)
{
m_Pool[Idx].Index = m_FreeHead;
m_FreeHead = Idx;
}
ScopeEvent& Get(uint32 Idx) { return m_Pool[Idx]; }
eastl::vector<ScopeEvent> m_Pool;
uint32 m_FreeHead = NO_INDEX;
};
void OnNewTrace(const $Trace_NewTrace& NewTrace)
{
m_Freq = NewTrace.CycleFrequency();
m_Base = NewTrace.StartCycle();
m_UsDiv = m_Freq / 1'000'000;
if (m_UsDiv == 0)
{
m_UsDiv = 1;
}
m_UsDivRecip = ReciprocalU64(m_UsDiv);
}
void OnCpuSpec(const CpuProfiler_EventSpec& Spec)
{
uint32 SpecId = Spec.Id();
FieldStr SpecName = Spec.Name();
StringView NameView = SpecName.as_view();
if (NameView.starts_with("Frame "))
{
NameView = "Frame";
}
if (size_t Pos = NameView.find("\""); Pos != StringView::npos)
{
NameView = NameView.substr(0, Pos);
}
if (size_t Pos = NameView.find("\\"); Pos != StringView::npos)
{
NameView = NameView.substr(0, Pos);
}
m_Specs[SpecId] = m_Names.Add(NameView);
}
void OnCpuBatch(const CpuProfiler_EventBatch& Batch)
{
uint32 ThreadId = Batch.get_thread_id();
Array<uint8[]> Data = Batch.Data();
AbsorbBatch(/*Version=*/1, ThreadId, Data);
}
void OnCpuBatchV2(const CpuProfiler_EventBatchV2& Batch)
{
uint32 ThreadId = Batch.get_thread_id();
Array<uint8[]> Data = Batch.Data();
AbsorbBatch(/*Version=*/2, ThreadId, Data);
}
void OnCpuBatchV3(const CpuProfiler_EventBatchV3& Batch)
{
uint32 ThreadId = Batch.get_thread_id();
Array<uint8[]> Data = Batch.Data();
AbsorbBatch(/*Version=*/3, ThreadId, Data);
}
// Decodes a CpuProfiler scope batch. Mirrors UE's reference
// TraceServices/.../CpuProfilerTraceAnalysis.cpp ProcessBuffer /
// ProcessBufferV2.
//
// Version 1 (`CpuProfiler.EventBatch`): cycle is `value >> 1`; bit 0 is
// IsEnter; IsEnter events carry a SpecId varint.
//
// Version 2 (`CpuProfiler.EventBatchV2`, UE 5.1..5.5) and Version 3
// (`CpuProfiler.EventBatchV3`, UE 5.6+): cycle is `value >> 2`; bit 0 is
// IsEnter, bit 1 is IsCoroutine. Coroutine begin events carry CoroutineId
// and TimerScopeDepth varints; coroutine end events carry a single
// TimerScopeDepth varint. V3 additionally reserves the low bit of the
// SpecId to mark metadata-bearing timers, so SpecId must be shifted
// right by 1 to recover the actual spec id.
void AbsorbBatch(uint32 Version, uint32 ThreadId, const Array<uint8[]>& Data)
{
const uint8* Cursor = Data.get();
const uint8* End = Cursor + Data.get_size();
auto Decode = [&]() {
uint64 Value = 0;
for (uint32 I = 1, J = 0; I; J += 7)
{
I = *Cursor++;
Value |= uint64(I & 0x7f) << J;
I &= 0x80;
}
return Value;
};
if (ThreadId >= m_Threads.size())
{
m_Threads.resize(ThreadId + 1);
}
EventStack& Stack = m_Threads[ThreadId];
const uint32 CycleShift = (Version == 1) ? 1u : 2u;
uint64 Base = m_Base;
uint64 Cycle = ~Base + 1;
while (Cursor < End)
{
uint64 Value = Decode();
uint32 IsEnter = (Value & 0b01);
if (Version > 1 && (Value & 0b10))
{
// Coroutine event -- not visualised, but the trailing varints
// still need to be consumed so we stay in sync with the
// stream.
if (IsEnter)
{
(void)Decode(); // CoroutineId
(void)Decode(); // TimerScopeDepth
}
else
{
(void)Decode(); // TimerScopeDepth
}
continue;
}
uint64 EventId = IsEnter ? Decode() : ~0ull;
Cycle += (Value >> CycleShift);
uint32 TimeUs = m_UsDivRecip.Divide(Cycle + (m_UsDiv >> 1));
if (IsEnter)
{
uint32 ScopeId = uint32(EventId);
bool IsMetadata = false;
if (Version == 3)
{
IsMetadata = (ScopeId & 1u) != 0;
ScopeId >>= 1;
}
uint32 EvIdx = m_Events.Alloc();
ScopeEvent& Ev = m_Events.Get(EvIdx);
// Pack the metadata flag in the high bit so the close path
// can distinguish metadata-id scopes from regular ones without
// an extra field.
Ev.Id = IsMetadata ? (ScopeId | 0x8000'0000u) : ScopeId;
Ev.TimeUs = TimeUs;
Ev.Next = Stack.Tail;
Stack.Tail = EvIdx;
continue;
}
if (Stack.Tail == NO_INDEX)
{
continue;
}
ScopeEvent& Ev = m_Events.Get(Stack.Tail);
uint32 DurationUs = TimeUs - Ev.TimeUs;
uint64 NameHash = ResolveNameHash(Ev.Id);
m_Stats.Record(NameHash, DurationUs);
uint32 NextIdx = Ev.Next;
m_Events.Free(Stack.Tail);
Stack.Tail = NextIdx;
}
}
uint64 m_Freq = 0;
uint64 m_Base = 0;
uint64 m_UsDiv = 1;
ReciprocalU64 m_UsDivRecip;
eastl::hash_map<uint32, uint64> m_Specs;
NameDepot& m_Names;
EventPool m_Events;
eastl::vector<EventStack> m_Threads;
EventStats& m_Stats;
const MetadataRegistry* m_Metadata = nullptr;
// Caches the resolved name hash for each MetadataId so we don't
// re-format the same CBOR payload on every scope-close.
eastl::hash_map<uint32, uint64> m_MetadataNames;
};
//////////////////////////////////////////////////////////////////////////////
// Per-event CPU scope capture for the interactive trace viewer.
//
// Mirrors CpuAnalyzer's decode loop but instead of aggregating statistics,
// it records one TimelineScope per closed CPU scope so the viewer can draw a
// flame graph. Scope names are interned into a flat vector so each event only
// stores a compact uint32 NameId.
class TimelineAnalyzer : public Analyzer
{
public:
explicit TimelineAnalyzer(const MetadataRegistry* Metadata = nullptr, TraceTiming* SharedTiming = nullptr)
: m_SharedTiming(SharedTiming)
, m_Metadata(Metadata)
{
}
void subscribe(Vector<Subscription>& Subs) override
{
Subs.emplace_back(this, &TimelineAnalyzer::OnNewTrace);
Subs.emplace_back(this, &TimelineAnalyzer::OnCpuSpec);
Subs.emplace_back(this, &TimelineAnalyzer::OnCpuBatch);
Subs.emplace_back(this, &TimelineAnalyzer::OnCpuBatchV2);
Subs.emplace_back(this, &TimelineAnalyzer::OnCpuBatchV3);
}
struct ThreadData
{
eastl::vector<zen::trace_detail::TimelineScope> Scopes;
// Open-scope stack: parallel arrays keeping begin time and name id.
eastl::vector<uint32_t> OpenBeginUs;
eastl::vector<uint32_t> OpenNameIds;
};
const eastl::vector<std::string>& ScopeNames() const { return m_ScopeNames; }
const eastl::map<uint32_t, ThreadData>& Threads() const { return m_Threads; }
uint32_t MinBeginUs() const { return m_MinBeginUs; }
uint32_t MaxEndUs() const { return m_MaxEndUs; }
private:
static constexpr uint32_t INVALID_NAME = ~0u;
uint32_t InternName(StringView Name)
{
String Key(Name);
auto [It, Inserted] = m_NameIndex.try_emplace(std::move(Key), 0);
if (Inserted)
{
It->second = uint32_t(m_ScopeNames.size());
m_ScopeNames.emplace_back(Name);
}
return It->second;
}
void OnNewTrace(const $Trace_NewTrace& NewTrace)
{
m_Freq = NewTrace.CycleFrequency();
m_Base = NewTrace.StartCycle();
m_UsDiv = m_Freq / 1'000'000;
if (m_UsDiv == 0)
{
m_UsDiv = 1;
}
m_UsDivRecip = ReciprocalU64(m_UsDiv);
if (m_SharedTiming)
{
m_SharedTiming->Freq = m_Freq;
m_SharedTiming->Base = m_Base;
m_SharedTiming->UsDiv = m_UsDiv;
}
}
void OnCpuSpec(const CpuProfiler_EventSpec& Spec)
{
uint32 SpecId = Spec.Id();
FieldStr SpecName = Spec.Name();
StringView NameView = SpecName.as_view();
if (NameView.starts_with("Frame "))
{
NameView = "Frame";
}
if (size_t Pos = NameView.find("\""); Pos != StringView::npos)
{
NameView = NameView.substr(0, Pos);
}
if (size_t Pos = NameView.find("\\"); Pos != StringView::npos)
{
NameView = NameView.substr(0, Pos);
}
m_Specs[SpecId] = InternName(NameView);
}
void OnCpuBatch(const CpuProfiler_EventBatch& Batch)
{
uint32 ThreadId = Batch.get_thread_id();
Array<uint8[]> Data = Batch.Data();
AbsorbBatch(/*Version=*/1, ThreadId, Data);
}
void OnCpuBatchV2(const CpuProfiler_EventBatchV2& Batch)
{
uint32 ThreadId = Batch.get_thread_id();
Array<uint8[]> Data = Batch.Data();
AbsorbBatch(/*Version=*/2, ThreadId, Data);
}
void OnCpuBatchV3(const CpuProfiler_EventBatchV3& Batch)
{
uint32 ThreadId = Batch.get_thread_id();
Array<uint8[]> Data = Batch.Data();
AbsorbBatch(/*Version=*/3, ThreadId, Data);
}
TraceTiming* m_SharedTiming = nullptr;
// See CpuAnalyzer::AbsorbBatch for a detailed description of the wire
// format for each version.
void AbsorbBatch(uint32 Version, uint32 ThreadId, const Array<uint8[]>& Data)
{
const uint8* Cursor = Data.get();
const uint8* End = Cursor + Data.get_size();
auto Decode = [&]() {
uint64 Value = 0;
for (uint32 I = 1, J = 0; I; J += 7)
{
I = *Cursor++;
Value |= uint64(I & 0x7f) << J;
I &= 0x80;
}
return Value;
};
ThreadData& Thread = m_Threads[ThreadId];
const uint32 CycleShift = (Version == 1) ? 1u : 2u;
uint64 Base = m_Base;
uint64 Cycle = ~Base + 1;
while (Cursor < End)
{
uint64 Value = Decode();
uint32 IsEnter = (Value & 0b01);
if (Version > 1 && (Value & 0b10))
{
// Coroutine event -- consume the trailing varints so we stay
// in sync with the stream, but drop the event on the floor.
if (IsEnter)
{
(void)Decode(); // CoroutineId
(void)Decode(); // TimerScopeDepth
}
else
{
(void)Decode(); // TimerScopeDepth
}
continue;
}
uint64 EventId = IsEnter ? Decode() : ~0ull;
Cycle += (Value >> CycleShift);
uint32 TimeUs = m_UsDivRecip.Divide(Cycle + (m_UsDiv >> 1));
if (IsEnter)
{
uint32 ScopeId = uint32(EventId);
bool IsMetadata = false;
if (Version == 3)
{
IsMetadata = (ScopeId & 1u) != 0;
ScopeId >>= 1;
}
uint32_t NameId = IsMetadata ? ResolveMetadataNameId(ScopeId) : LookupSpecNameId(ScopeId);
Thread.OpenBeginUs.push_back(TimeUs);
Thread.OpenNameIds.push_back(NameId);
continue;
}
if (Thread.OpenBeginUs.empty())
{
continue;
}
uint32_t BeginUs = Thread.OpenBeginUs.back();
uint32_t NameId = Thread.OpenNameIds.back();
Thread.OpenBeginUs.pop_back();
Thread.OpenNameIds.pop_back();
if (NameId == INVALID_NAME)
{
continue;
}
uint16_t Depth = uint16_t(Thread.OpenBeginUs.size());
Thread.Scopes.push_back(zen::trace_detail::TimelineScope{
.BeginUs = BeginUs,
.DurationUs = TimeUs - BeginUs,
.NameId = NameId,
.Depth = Depth,
.MergeCount = 0,
});
if (BeginUs < m_MinBeginUs)
{
m_MinBeginUs = BeginUs;
}
if (TimeUs > m_MaxEndUs)
{
m_MaxEndUs = TimeUs;
}
}
}
uint32_t LookupSpecNameId(uint32 SpecId) const
{
auto It = m_Specs.find(SpecId);
return (It != m_Specs.end()) ? It->second : INVALID_NAME;
}
uint32_t ResolveMetadataNameId(uint32 MetadataId)
{
if (!m_Metadata)
{
return INVALID_NAME;
}
auto CachedIt = m_MetadataNameIds.find(MetadataId);
if (CachedIt != m_MetadataNameIds.end())
{
return CachedIt->second;
}
const MetadataEntry* Entry = m_Metadata->Lookup(MetadataId);
if (!Entry)
{
return INVALID_NAME;
}
auto BaseIt = m_Specs.find(Entry->SpecId);
const std::string& BaseName = (BaseIt != m_Specs.end()) ? m_ScopeNames[BaseIt->second] : kUnknownName;
std::string Formatted = BaseName;
std::string Values = FormatMetadataValues(Entry->Bytes.data(), Entry->Bytes.size());
if (!Values.empty())
{
Formatted += " - ";
Formatted += Values;
}
uint32_t NameId = InternName(StringView(Formatted.data(), Formatted.size()));
m_MetadataNameIds[MetadataId] = NameId;
return NameId;
}
static inline const std::string kUnknownName{"???"};
uint64 m_Freq = 0;
uint64 m_Base = 0;
uint64 m_UsDiv = 1;
ReciprocalU64 m_UsDivRecip;
uint32_t m_MinBeginUs = ~0u;
uint32_t m_MaxEndUs = 0;
eastl::hash_map<uint32, uint32_t> m_Specs;
eastl::hash_map<String, uint32_t> m_NameIndex;
eastl::vector<std::string> m_ScopeNames;
eastl::map<uint32_t, ThreadData> m_Threads;
const MetadataRegistry* m_Metadata = nullptr;
eastl::hash_map<uint32_t, uint32_t> m_MetadataNameIds;
};
//////////////////////////////////////////////////////////////////////////////
} // anonymous namespace
std::string
zen::trace_detail::SafeFieldStr(FieldStr&& Field)
{
try
{
std::string_view View = Field.as_view();
// Some trace writers include the NUL terminator in the field length
// (see UE trace ToAnsiCheap / ThreadRegister). Strip any trailing NULs
// so downstream consumers don't see garbage.
while (!View.empty() && View.back() == '\0')
{
View.remove_suffix(1);
}
return std::string(View);
}
catch (const std::exception& E)
{
ZEN_DEBUG("Failed to decode trace string field: {}", E.what());
return {};
}
}
namespace {
// Derive a thread group name from a thread name by stripping a trailing
// integer suffix (optionally preceded by a separator). E.g. "IoPool Worker 3"
// -> "IoPool Worker", "DbWorker_12" -> "DbWorker", "HttpThread42" ->
// "HttpThread". Returns an empty string if no suffix is present or the
// resulting prefix would be empty.
static std::string
SynthesizeThreadGroupFromName(std::string_view Name)
{
size_t I = Name.size();
while (I > 0 && Name[I - 1] >= '0' && Name[I - 1] <= '9')
{
--I;
}
if (I == Name.size())
{
return {}; // no trailing digits
}
if (I > 0)
{
char C = Name[I - 1];
if (C == '_' || C == '-' || C == '.' || C == ':' || C == '#' || C == '/' || C == ' ' || C == '\t')
{
--I;
}
}
while (I > 0 && (Name[I - 1] == ' ' || Name[I - 1] == '\t'))
{
--I;
}
if (I == 0)
{
return {}; // pure-numeric name
}
return std::string(Name.substr(0, I));
}
class SessionAnalyzer : public Analyzer
{
public:
zen::trace_detail::SessionInfo Session;
eastl::map<uint32_t, zen::trace_detail::ThreadInfoEntry> ThreadNames;
eastl::map<uint32_t, zen::trace_detail::ChannelInfo> Channels;
void subscribe(Vector<Subscription>& Subs) override
{
Subs.emplace_back(this, &SessionAnalyzer::OnSession);
Subs.emplace_back(this, &SessionAnalyzer::OnThreadGroupBegin);
Subs.emplace_back(this, &SessionAnalyzer::OnThreadGroupEnd);
Subs.emplace_back(this, &SessionAnalyzer::OnThreadInfo);
Subs.emplace_back(this, &SessionAnalyzer::OnChannelAnnounce);
Subs.emplace_back(this, &SessionAnalyzer::OnChannelToggle);
}
private:
eastl::vector<String> m_GroupStack;
void OnSession(const Diagnostics_Session2& Ev)
{
Session.Platform = SafeFieldStr(Ev.Platform());
Session.AppName = SafeFieldStr(Ev.AppName());
Session.ProjectName = SafeFieldStr(Ev.ProjectName());
Session.CommandLine = SafeFieldStr(Ev.CommandLine());
Session.Branch = SafeFieldStr(Ev.Branch());
Session.BuildVersion = SafeFieldStr(Ev.BuildVersion());
Session.Changelist = Ev.Changelist();
Session.ConfigurationType = Ev.ConfigurationType();
Session.HasSession = true;
}
void OnThreadGroupBegin(const $Trace_ThreadGroupBegin& Ev) { m_GroupStack.push_back(SafeFieldStr(Ev.Name())); }
void OnThreadGroupEnd(const $Trace_ThreadGroupEnd&)
{
if (!m_GroupStack.empty())
{
m_GroupStack.pop_back();
}
}
void OnThreadInfo(const $Trace_ThreadInfo& Ev)
{
uint32_t Tid = Ev.ThreadId();
zen::trace_detail::ThreadInfoEntry& Info = ThreadNames[Tid];
Info.ThreadId = Tid;
Info.Name = SafeFieldStr(Ev.Name());
Info.GroupName = m_GroupStack.empty() ? "" : m_GroupStack.back();
if (Info.GroupName.empty())
{
Info.GroupName = SynthesizeThreadGroupFromName(Info.Name);
}
Info.SystemId = Ev.SystemId();
Info.SortHint = Ev.SortHint();
}
void OnChannelAnnounce(const Trace_ChannelAnnounce& Ev)
{
uint32_t Id = Ev.Id();
zen::trace_detail::ChannelInfo& Info = Channels[Id];
Info.Name = SafeFieldStr(Ev.Name());
Info.Enabled = Ev.IsEnabled() != 0;
Info.ReadOnly = Ev.ReadOnly() != 0;
}
void OnChannelToggle(const Trace_ChannelToggle& Ev)
{
uint32_t Id = Ev.Id();
auto It = Channels.find(Id);
if (It != Channels.end())
{
It->second.Enabled = Ev.IsEnabled() != 0;
}
}
};
//////////////////////////////////////////////////////////////////////////////
// Module analyzer
//
// Captures Diagnostics.Module{Init,Load,Unload} so TraceModel::Modules has a
// populated list of loaded DLLs. These events are NoSync+Important so they
// don't carry a Cycle field (no load/unload timestamps available) but they
// do survive reconnects and the trim filter. The analyzer is intentionally
// passive -- we stash the raw data here and leave symbolication and memory
// attribution to whatever consumes TraceModel::Modules later.
class ModuleAnalyzer : public Analyzer
{
public:
eastl::map<uint64_t, zen::trace_detail::ModuleInfo> ModulesByBase;
std::string SymbolFormat;
uint8_t BaseShift = 0;
void subscribe(Vector<Subscription>& Subs) override
{
Subs.emplace_back(this, &ModuleAnalyzer::OnModuleInit);
Subs.emplace_back(this, &ModuleAnalyzer::OnModuleLoad);
Subs.emplace_back(this, &ModuleAnalyzer::OnModuleUnload);
}
private:
void OnModuleInit(const Diagnostics_ModuleInit& Ev)
{
SymbolFormat = SafeFieldStr(Ev.SymbolFormat());
BaseShift = Ev.ModuleBaseShift();
}
void OnModuleLoad(const Diagnostics_ModuleLoad& Ev)
{
// Older traces stored Base as a 32-bit value shifted right by
// ModuleBaseShift to fit. Modern traces set BaseShift to zero and
// Base is a full 64-bit address; applying the shift then is a
// harmless no-op.
uint64_t Base = uint64_t(Ev.Base()) << BaseShift;
zen::trace_detail::ModuleInfo& Info = ModulesByBase[Base];
Info.FullPath = SafeFieldStr(Ev.Name());
Info.Base = Base;
Info.Size = Ev.Size();
Info.Unloaded = false;
// Extract the basename without pulling in the whole filesystem
// library for a single operation. UE emits forward- or backslashes
// depending on platform, so handle both.
const std::string& Path = Info.FullPath;
size_t Cut = Path.find_last_of("/\\");
Info.Name = (Cut == std::string::npos) ? Path : Path.substr(Cut + 1);
::Array<uint8[]> ImageId = Ev.ImageId();
const uint8* IdPtr = ImageId.get();
const uint32 IdSize = ImageId.get_size();
Info.ImageId.assign(IdPtr, IdPtr + IdSize);
}
void OnModuleUnload(const Diagnostics_ModuleUnload& Ev)
{
uint64_t Base = uint64_t(Ev.Base()) << BaseShift;
auto It = ModulesByBase.find(Base);
if (It != ModulesByBase.end())
{
It->second.Unloaded = true;
}
}
};
//////////////////////////////////////////////////////////////////////////////
// Trim analyzer
//
// Decodes CpuProfiler batch events to extract per-batch timestamp ranges AND
// to track open/close scope bracketing per thread. The scope tracker lets us
// identify "must-keep" packets: any packet containing the Leave event for a
// scope whose Enter was at or before the user's trim EndUs. Preserving those
// Leaves is what lets the downstream TimelineAnalyzer (and Unreal Insights)
// still render long-running scopes that span the window end -- if we dropped
// their closing event the scope would sit unmatched on the open-scope stack
// and not render at all.
//
// Attribution to raw packet indices is approximate due to Tourist's internal
// per-thread packet buffering; the trim driver processes the trace one packet
// at a time (bundle of size 1) to keep it as tight as possible. Packets that
// never get an attributed time range are conservatively retained by the
// caller.
class TrimAnalyzer : public Analyzer
{
public:
// Maps packet index (matching both Tourist's Packet::get_index() and our
// raw walker's vector position) -> (MinUs, MaxUs) of all events attributed
// to that packet.
struct Range
{
uint32_t MinUs = ~0u;
uint32_t MaxUs = 0;
};
eastl::hash_map<uint32_t, Range> PacketRanges;
// Maps thread id -> the maximum packet index that contains a Leave event
// for a scope whose matching Enter was at or before EndUs. These packets
// must be retained so the downstream analyzer can close the scope.
eastl::hash_map<uint32_t, uint32_t> MustKeepPacketByThread;
// Set by the trim driver from TraceTrimArgs::EndSec before the analysis
// pass begins. Used by the scope tracker to decide which leaves are
// "must keep".
uint32_t EndUs = ~0u;
// Updated by the trim driver before each Proto.read call when the next
// packet is on a normal thread. Maps normal-thread id -> the most
// recently scattered packet's index.
eastl::hash_map<uint32_t, uint32_t> LastPacketIndexByThread;
void subscribe(Vector<Subscription>& Subs) override
{
Subs.emplace_back(this, &TrimAnalyzer::OnNewTrace);
Subs.emplace_back(this, &TrimAnalyzer::OnCpuBatch);
Subs.emplace_back(this, &TrimAnalyzer::OnCpuBatchV2);
Subs.emplace_back(this, &TrimAnalyzer::OnCpuBatchV3);
}
bool HasTimeBase() const { return m_Freq != 0; }
private:
void OnNewTrace(const $Trace_NewTrace& NewTrace)
{
m_Freq = NewTrace.CycleFrequency();
m_Base = NewTrace.StartCycle();
m_UsDiv = (m_Freq > 0) ? (m_Freq / 1'000'000) : 1;
if (m_UsDiv == 0)
{
m_UsDiv = 1;
}
m_UsDivRecip = ReciprocalU64(m_UsDiv);
}
void OnCpuBatch(const CpuProfiler_EventBatch& Batch) { AbsorbBatchTimes(/*Version=*/1, Batch.get_thread_id(), Batch.Data()); }
void OnCpuBatchV2(const CpuProfiler_EventBatchV2& Batch) { AbsorbBatchTimes(/*Version=*/2, Batch.get_thread_id(), Batch.Data()); }
void OnCpuBatchV3(const CpuProfiler_EventBatchV3& Batch) { AbsorbBatchTimes(/*Version=*/3, Batch.get_thread_id(), Batch.Data()); }
// Decodes cycle deltas in a CpuProfiler batch to find the timestamp range
// AND to maintain a per-thread open-scope stack. Mirrors the wire format
// documented in CpuAnalyzer::AbsorbBatch. Scope ids are decoded just far
// enough to keep the varint cursor in sync; we don't store them.
void AbsorbBatchTimes(uint32 Version, uint32 ThreadId, const Array<uint8[]>& Data)
{
if (m_Freq == 0)
{
return;
}
auto It = LastPacketIndexByThread.find(ThreadId);
if (It == LastPacketIndexByThread.end())
{
return;
}
const uint32_t PacketIndex = It->second;
// The open-scope stack is maintained across every batch on a thread.
// Each entry stores the Enter time in microseconds from trace start.
eastl::vector<uint32_t>& OpenStack = m_OpenScopes[ThreadId];
const uint8* Cursor = Data.get();
const uint8* End = Cursor + Data.get_size();
auto Decode = [&]() {
uint64 Value = 0;
for (uint32 I = 1, J = 0; I; J += 7)
{
I = *Cursor++;
Value |= uint64(I & 0x7f) << J;
I &= 0x80;
}
return Value;
};
const uint32 CycleShift = (Version == 1) ? 1u : 2u;
const uint64 Base = m_Base;
uint32_t BatchMinUs = ~0u;
uint32_t BatchMaxUs = 0;
bool HasAny = false;
uint64 Cycle = ~Base + 1;
while (Cursor < End)
{
uint64 Value = Decode();
uint32 IsEnter = (Value & 0b01);
if (Version > 1 && (Value & 0b10))
{
// Coroutine event -- consume the trailing varints and skip.
// These don't participate in the scope bracket tracking; the
// existing TimelineAnalyzer ignores them for the same reason.
if (IsEnter)
{
(void)Decode(); // CoroutineId
(void)Decode(); // TimerScopeDepth
}
else
{
(void)Decode(); // TimerScopeDepth
}
continue;
}
if (IsEnter)
{
(void)Decode(); // EventId / SpecId
}
Cycle += (Value >> CycleShift);
uint32_t TimeUs = m_UsDivRecip.Divide(Cycle + (m_UsDiv >> 1));
if (!HasAny || TimeUs < BatchMinUs)
{
BatchMinUs = TimeUs;
}
if (!HasAny || TimeUs > BatchMaxUs)
{
BatchMaxUs = TimeUs;
}
HasAny = true;
if (IsEnter)
{
OpenStack.push_back(TimeUs);
}
else if (!OpenStack.empty())
{
uint32_t EnterTimeUs = OpenStack.back();
OpenStack.pop_back();
// If the scope started at or before the window end, we need
// its closing Leave event to survive so the downstream
// analyzer can render it. Mark the current packet (the one
// holding this Leave) as must-keep for the thread.
if (EnterTimeUs <= EndUs)
{
uint32_t& MustKeep = MustKeepPacketByThread[ThreadId];
if (PacketIndex > MustKeep)
{
MustKeep = PacketIndex;
}
}
}
}
if (!HasAny)
{
return;
}
Range& R = PacketRanges[PacketIndex];
R.MinUs = std::min(R.MinUs, BatchMinUs);
R.MaxUs = std::max(R.MaxUs, BatchMaxUs);
}
uint64 m_Freq = 0;
uint64 m_Base = 0;
uint64 m_UsDiv = 1;
ReciprocalU64 m_UsDivRecip;
// Per-thread open scope stack, carrying the Enter times in microseconds
// from trace start. Entries are pushed on Enter and popped on Leave; the
// stack may contain unclosed entries when decoding ends (scopes that
// outlive the captured trace).
eastl::hash_map<uint32_t, eastl::vector<uint32_t>> m_OpenScopes;
};
//////////////////////////////////////////////////////////////////////////////
// Common trace iteration
struct TraceSummary
{
eastl::map<uint32_t, std::pair<std::string, uint64_t>> TypeInfo;
eastl::set<uint16_t> Threads;
uint64_t TotalEvents = 0;
};
template<typename ParcelCallback>
static TraceSummary
IterateTrace(::DataSource& Source, ParcelCallback OnParcel, const zen::trace_detail::ProgressCallback& OnProgress = {})
{
TraceSummary Summary;
try
{
uint64_t TotalFileBytes = uint64_t(std::max(Source.get_size(), int64(0)));
::Allocator TraceAllocator;
::Preamble Pream(Source, TraceAllocator);
::Transport Xport = Pream.get_transport();
::Protocol Proto = Pream.get_protocol();
::Packet Packets[128];
::EventParcel Parcel;
while (::Bundle Bndl = Xport.read_packets(Packets))
{
Parcel.reset();
Proto.read(Parcel, Bndl);
OnParcel(Parcel);
for (const ::Type* TraceType : Parcel.new_types)
{
auto [LoggerName, EventName] = TraceType->get_name();
std::string TypeName = fmt::format("{}.{}", std::string_view(LoggerName), std::string_view(EventName));
Summary.TypeInfo[TraceType->get_uid()] = {std::move(TypeName), 0};
}
for (const ::Event& Ev : Parcel.events)
{
Summary.TotalEvents++;
Summary.Threads.insert(Ev.thread_id);
auto It = Summary.TypeInfo.find(Ev.uid);
if (It != Summary.TypeInfo.end())
{
It->second.second++;
}
}
if (OnProgress)
{
OnProgress(Xport.tell(), TotalFileBytes, Summary.TotalEvents);
}
}
}
catch (const DataStream::Eof&)
{
}
catch (const Exception::StreamError& E)
{
throw std::runtime_error(fmt::format("Trace stream error at position {}: {} (value: {})", E.position, E.message, E.value));
}
return Summary;
}
// Print session metadata
static void
PrintSessionInfo(const SessionAnalyzer& SessionAn)
{
const zen::trace_detail::SessionInfo& Sess = SessionAn.Session;
if (!Sess.HasSession)
{
return;
}
ZEN_CONSOLE("Platform: {}", Sess.Platform);
ZEN_CONSOLE("App: {}", Sess.AppName);
if (!Sess.ProjectName.empty())
{
ZEN_CONSOLE("Project: {}", Sess.ProjectName);
}
if (!Sess.Branch.empty())
{
ZEN_CONSOLE("Branch: {}", Sess.Branch);
}
if (!Sess.BuildVersion.empty())
{
ZEN_CONSOLE("Build: {}", Sess.BuildVersion);
}
if (Sess.Changelist)
{
ZEN_CONSOLE("Changelist: {}", Sess.Changelist);
}
if (!Sess.CommandLine.empty())
{
ZEN_CONSOLE("CommandLine: {}", Sess.CommandLine);
}
ZEN_CONSOLE("");
}
// Print thread names
static void
PrintThreadInfo(const SessionAnalyzer& SessionAn)
{
if (SessionAn.ThreadNames.empty())
{
return;
}
eastl::vector<std::pair<uint32_t, const zen::trace_detail::ThreadInfoEntry*>> ThreadsSorted;
for (const auto& [Tid, Info] : SessionAn.ThreadNames)
{
ThreadsSorted.emplace_back(Tid, &Info);
}
eastl::sort(ThreadsSorted.begin(), ThreadsSorted.end(), [](const auto& A, const auto& B) {
return A.second->SortHint < B.second->SortHint;
});
ZEN_CONSOLE("");
ZEN_CONSOLE("Threads:");
ZEN_CONSOLE("");
ZEN_CONSOLE("{:>6} {:>10} {}", "TID", "SystemID", "Name");
ZEN_CONSOLE("{:-<{}}", "", 6 + 10 + 40 + 4);
for (const auto& [Tid, Info] : ThreadsSorted)
{
ZEN_CONSOLE("{:>6} {:>10} {}", Tid, Info->SystemId, Info->Name);
}
}
// Print trace channel info
static void
PrintChannelInfo(const SessionAnalyzer& SessionAn)
{
if (SessionAn.Channels.empty())
{
return;
}
eastl::vector<const zen::trace_detail::ChannelInfo*> ChannelsSorted;
for (const auto& [Id, Info] : SessionAn.Channels)
{
ChannelsSorted.push_back(&Info);
}
eastl::sort(ChannelsSorted.begin(), ChannelsSorted.end(), [](const auto* A, const auto* B) { return A->Name < B->Name; });
ZEN_CONSOLE("");
ZEN_CONSOLE("Trace Channels:");
ZEN_CONSOLE("");
for (const zen::trace_detail::ChannelInfo* Ch : ChannelsSorted)
{
std::string_view State = Ch->Enabled ? "enabled" : "disabled";
if (Ch->ReadOnly)
{
ZEN_CONSOLE(" {} ({}, read-only)", Ch->Name, State);
}
else
{
ZEN_CONSOLE(" {} ({})", Ch->Name, State);
}
}
}
} // namespace
//////////////////////////////////////////////////////////////////////////////
namespace zen::trace_detail {
std::filesystem::path
ResolveTraceFile(const std::filesystem::path& Input, cxxopts::Options& HelpOptions)
{
if (Input.empty())
{
throw zen::OptionParseException("File path is required", HelpOptions.help());
}
std::filesystem::path FilePath = std::filesystem::absolute(Input);
if (!std::filesystem::exists(FilePath))
{
throw std::runtime_error(fmt::format("File not found: {}", FilePath));
}
return FilePath;
}
void
RunInspect(const std::filesystem::path& FilePath)
{
::DataSource Source(FilePath);
SessionAnalyzer SessionAn;
::Dispatcher Dispatch;
Dispatch.add_analyzer(SessionAn);
// Collect type schemas
struct TypeSchema
{
std::string FullName;
uint32_t Uid = 0;
uint32_t FieldCount = 0;
uint32_t Flags = 0;
uint64_t EventCount = 0;
eastl::vector<std::string> FieldNames;
eastl::vector<uint32_t> FieldSizes;
eastl::vector<uint32_t> FieldTypeInfos;
};
eastl::map<uint32_t, TypeSchema> Schemas;
TraceSummary Summary = IterateTrace(Source, [&](const ::EventParcel& Parcel) {
Dispatch.on_parcel(Parcel);
for (const ::Type* TraceType : Parcel.new_types)
{
auto [LoggerName, EventName] = TraceType->get_name();
uint32_t Uid = TraceType->get_uid();
TypeSchema& Schema = Schemas[Uid];
Schema.FullName = fmt::format("{}.{}", std::string_view(LoggerName), std::string_view(EventName));
Schema.Uid = Uid;
Schema.FieldCount = TraceType->get_field_count();
Schema.Flags = 0;
if (TraceType->has_flag(TYPE_FLAG_IMPORTANT))
{
Schema.Flags |= TYPE_FLAG_IMPORTANT;
}
if (TraceType->has_flag(TYPE_FLAG_AUX))
{
Schema.Flags |= TYPE_FLAG_AUX;
}
for (uint32_t I = 0; I < Schema.FieldCount; I++)
{
auto [FieldName, Field] = TraceType->get_field_info(I);
Schema.FieldNames.emplace_back(FieldName);
Schema.FieldSizes.push_back(Field.get_size());
Schema.FieldTypeInfos.push_back(Field.get_type_info());
}
}
for (const ::Event& Ev : Parcel.events)
{
auto It = Schemas.find(Ev.uid);
if (It != Schemas.end())
{
It->second.EventCount++;
}
}
});
// -- Session info --
PrintSessionInfo(SessionAn);
ZEN_CONSOLE("Trace: {}", FilePath);
ZEN_CONSOLE("Size: {}", zen::NiceBytes(uint64_t(std::filesystem::file_size(FilePath))));
ZEN_CONSOLE("Events: {}", zen::ThousandsNum(Summary.TotalEvents));
ZEN_CONSOLE("Threads: {}", Summary.Threads.size());
ZEN_CONSOLE("Types: {}", Schemas.size());
// -- Thread names --
PrintThreadInfo(SessionAn);
// -- Trace channels --
PrintChannelInfo(SessionAn);
// -- Event schemas --
ZEN_CONSOLE("");
ZEN_CONSOLE("Event Schemas:");
ZEN_CONSOLE("");
eastl::vector<const TypeSchema*> SortedSchemas;
SortedSchemas.reserve(Schemas.size());
for (const auto& [Uid, Schema] : Schemas)
{
SortedSchemas.push_back(&Schema);
}
eastl::sort(SortedSchemas.begin(), SortedSchemas.end(), [](const auto* A, const auto* B) { return A->FullName < B->FullName; });
auto FieldTypeStr = [](uint32_t TypeInfo, uint32_t Size) -> std::string_view {
uint32_t Cat = TypeInfo & TYPE_INFO_CAT_MASK;
if (Cat == TYPE_INFO_CAT_ARRAY)
{
return "array";
}
if (Cat == TYPE_INFO_CAT_FLOAT)
{
return (Size == 8) ? "float64" : "float32";
}
bool IsSigned = (TypeInfo & TYPE_INFO_SPECIAL_MASK) == TYPE_INFO_SPECIAL_SIGNED;
switch (Size)
{
case 1:
return IsSigned ? "int8" : "uint8";
case 2:
return IsSigned ? "int16" : "uint16";
case 4:
return IsSigned ? "int32" : "uint32";
case 8:
return IsSigned ? "int64" : "uint64";
default:
return "unknown";
}
};
for (const TypeSchema* Schema : SortedSchemas)
{
std::string Flags;
if (Schema->Flags & TYPE_FLAG_IMPORTANT)
{
Flags += " [important]";
}
if (Schema->Flags & TYPE_FLAG_AUX)
{
Flags += " [aux]";
}
ZEN_CONSOLE("{} (uid={}, events={}){}", Schema->FullName, Schema->Uid, zen::ThousandsNum(Schema->EventCount), Flags);
for (uint32_t I = 0; I < Schema->FieldCount; I++)
{
ZEN_CONSOLE(" {} {}", FieldTypeStr(Schema->FieldTypeInfos[I], Schema->FieldSizes[I]), Schema->FieldNames[I]);
}
if (Schema->FieldCount > 0)
{
ZEN_CONSOLE("");
}
}
}
// Build a single LOD level by merging Lod0 scopes below the given resolution.
// Lod0 must already be sorted by BeginUs. Safe to call concurrently for
// different (Level, Resolution) pairs sharing the same Lod0.
static void
BuildSingleLod(const eastl::vector<TimelineScope>& Lod0, TimelineDetailLevel& Level, uint32_t Resolution)
{
Level.ResolutionUs = Resolution;
// Per-depth merge accumulators. Since depths are typically small (< 64),
// a flat array indexed by depth is more cache-friendly than a hash map.
struct PendingMerge
{
uint32_t BeginUs = 0;
uint32_t EndUs = 0;
uint32_t NameId = 0;
uint32_t MaxChildDur = 0;
uint16_t Depth = 0;
uint16_t Count = 0;
bool Active = false;
};
eastl::vector<PendingMerge> Pending(64); // grows if needed
auto FlushPending = [&Level](PendingMerge& P) {
if (!P.Active)
{
return;
}
Level.Scopes.push_back(TimelineScope{
.BeginUs = P.BeginUs,
.DurationUs = P.EndUs - P.BeginUs,
.NameId = P.NameId,
.Depth = P.Depth,
.MergeCount = P.Count,
});
P.Active = false;
};
// Single O(n) sweep over LOD 0 scopes (sorted by BeginUs). For each
// depth, merge adjacent small scopes that fall within one resolution
// bucket of each other. Large scopes (>= Resolution) pass through.
for (const TimelineScope& Scope : Lod0)
{
uint16_t Depth = Scope.Depth;
if (Depth >= Pending.size())
{
Pending.resize(Depth + 1);
}
if (Scope.DurationUs >= Resolution)
{
// Large scope -- flush any pending merge for this depth,
// then emit the scope un-merged.
FlushPending(Pending[Depth]);
Level.Scopes.push_back(TimelineScope{
.BeginUs = Scope.BeginUs,
.DurationUs = Scope.DurationUs,
.NameId = Scope.NameId,
.Depth = Scope.Depth,
.MergeCount = 1,
});
continue;
}
PendingMerge& P = Pending[Depth];
uint32_t EndUs = Scope.BeginUs + Scope.DurationUs;
if (P.Active && Scope.BeginUs < P.EndUs + Resolution)
{
// Extend the pending merge.
if (EndUs > P.EndUs)
{
P.EndUs = EndUs;
}
++P.Count;
if (Scope.DurationUs > P.MaxChildDur)
{
P.MaxChildDur = Scope.DurationUs;
P.NameId = Scope.NameId;
}
}
else
{
// Start a new pending merge (flush previous if any).
FlushPending(P);
P.BeginUs = Scope.BeginUs;
P.EndUs = EndUs;
P.NameId = Scope.NameId;
P.MaxChildDur = Scope.DurationUs;
P.Depth = Scope.Depth;
P.Count = 1;
P.Active = true;
}
}
// Flush remaining per-depth accumulators.
for (PendingMerge& P : Pending)
{
FlushPending(P);
}
// Sort by (BeginUs, Depth) -- the per-depth flush may have interleaved
// entries from different depths. Tie-breaking on depth keeps the
// ordering consistent with LOD 0 (parents before nested children) so
// the front-end never sees a child rendered before its parent.
eastl::sort(Level.Scopes.begin(), Level.Scopes.end(), [](const TimelineScope& A, const TimelineScope& B) {
if (A.BeginUs != B.BeginUs)
{
return A.BeginUs < B.BeginUs;
}
return A.Depth < B.Depth;
});
}
void
BuildTimelineLods(ThreadTimeline& Timeline)
{
if (Timeline.Scopes.empty())
{
return;
}
for (size_t LodIdx = 0; LodIdx < kTimelineLodCount; ++LodIdx)
{
BuildSingleLod(Timeline.Scopes, Timeline.DetailLevels[LodIdx], kTimelineLodResolutions[LodIdx]);
}
}
namespace {
// Post-iteration phases, extracted from BuildTraceModel for clarity. Each one
// runs after the event-iteration pass has populated the analyzers and mutates
// only the pieces of TraceModel it owns.
void ComputeScopeStats(const TimelineAnalyzer& TimelineAn, TraceModel& Model)
{
const eastl::vector<std::string>& ScopeNames = TimelineAn.ScopeNames();
eastl::vector<Distribution> Dists(ScopeNames.size());
eastl::vector<uint32_t> Mins(ScopeNames.size(), ~0u);
eastl::vector<uint32_t> Maxs(ScopeNames.size(), 0u);
for (const auto& [Tid, Thread] : TimelineAn.Threads())
{
for (const TimelineScope& Scope : Thread.Scopes)
{
if (Scope.NameId >= Dists.size())
{
continue;
}
Dists[Scope.NameId].add(double(Scope.DurationUs));
Mins[Scope.NameId] = std::min(Mins[Scope.NameId], Scope.DurationUs);
Maxs[Scope.NameId] = std::max(Maxs[Scope.NameId], Scope.DurationUs);
}
}
Model.ScopeStats.reserve(ScopeNames.size());
for (size_t I = 0; I < ScopeNames.size(); ++I)
{
if (Dists[I].Count() == 0)
{
continue;
}
CpuScopeStat Entry;
Entry.Name = ScopeNames[I];
Entry.Count = Dists[I].Count();
Entry.MinUs = Mins[I];
Entry.MaxUs = Maxs[I];
Entry.MeanUs = Dists[I].Mean();
Entry.StdDevUs = Dists[I].StdDev();
Model.ScopeStats.push_back(std::move(Entry));
}
eastl::sort(Model.ScopeStats.begin(), Model.ScopeStats.end(), [](const CpuScopeStat& A, const CpuScopeStat& B) {
return A.Count > B.Count;
});
}
// Translate each LogEntry's captured CategoryIndex (a sequential id keyed on
// the source category pointer) into the flat LogCategories index the frontend
// consumes. Entries whose category pointer never got a matching LogCategory
// event are bucketed into a synthetic "(unknown)" category.
void ResolveLogCategories(LogAnalyzer& LogAn, TraceModel& Model)
{
const eastl::hash_map<uint64_t, uint32_t>& CategoryPtrToSeqIdx = LogAn.CategoryPointerIndex();
eastl::hash_map<uint64_t, uint32_t> RealPtrToFlatIdx;
Model.LogCategories = LogAn.BuildCategories(RealPtrToFlatIdx);
const uint32_t UnknownIdx = uint32_t(Model.LogCategories.size());
Model.LogCategories.push_back(LogCategoryInfo{.Name = "(unknown)", .DefaultVerbosity = 0});
eastl::vector<uint32_t> SeqToFlat(CategoryPtrToSeqIdx.size(), UnknownIdx);
for (const auto& [Ptr, SeqIdx] : CategoryPtrToSeqIdx)
{
auto It = RealPtrToFlatIdx.find(Ptr);
if (It != RealPtrToFlatIdx.end())
{
SeqToFlat[SeqIdx] = It->second;
}
}
Model.LogEntries = LogAn.MutableEntries();
for (LogEntry& E : Model.LogEntries)
{
E.CategoryIndex = (E.CategoryIndex < SeqToFlat.size()) ? SeqToFlat[E.CategoryIndex] : UnknownIdx;
}
eastl::sort(Model.LogEntries.begin(), Model.LogEntries.end(), [](const LogEntry& A, const LogEntry& B) {
return A.TimeUs < B.TimeUs;
});
}
// Finalize any still-open regions, group by category, and greedily pack each
// category's regions into non-overlapping lanes so the frontend can stack them
// without re-running collision detection.
void BuildRegionCategories(eastl::vector<RegionEntry>&& AllRegions, uint32_t TraceEndUs, TraceModel& Model)
{
for (RegionEntry& R : AllRegions)
{
if (R.EndUs == ~uint32_t(0))
{
R.EndUs = TraceEndUs;
}
if (R.EndUs < R.BeginUs)
{
R.EndUs = R.BeginUs;
}
}
eastl::map<std::string, eastl::vector<RegionEntry>> ByCategory;
for (RegionEntry& R : AllRegions)
{
ByCategory[R.Category].push_back(std::move(R));
}
for (auto& [CatName, Regions] : ByCategory)
{
eastl::sort(Regions.begin(), Regions.end(), [](const RegionEntry& A, const RegionEntry& B) {
if (A.BeginUs != B.BeginUs)
{
return A.BeginUs < B.BeginUs;
}
return A.EndUs < B.EndUs;
});
eastl::vector<uint32_t> LaneEndUs;
uint32_t MaxLane = 0;
for (RegionEntry& R : Regions)
{
uint16_t Depth = 0;
bool Assigned = false;
for (size_t I = 0; I < LaneEndUs.size(); ++I)
{
if (LaneEndUs[I] <= R.BeginUs)
{
Depth = uint16_t(I);
LaneEndUs[I] = R.EndUs;
Assigned = true;
break;
}
}
if (!Assigned)
{
Depth = uint16_t(LaneEndUs.size());
LaneEndUs.push_back(R.EndUs);
}
R.Depth = Depth;
if (Depth + 1u > MaxLane)
{
MaxLane = Depth + 1u;
}
}
RegionCategory Cat;
Cat.Name = CatName;
Cat.LaneCount = MaxLane;
Cat.Regions = std::move(Regions);
Model.RegionCategories.push_back(std::move(Cat));
}
// Sort: uncategorized (empty name) first, then alphabetical.
eastl::sort(Model.RegionCategories.begin(), Model.RegionCategories.end(), [](const RegionCategory& A, const RegionCategory& B) {
if (A.Name.empty() != B.Name.empty())
{
return A.Name.empty();
}
return A.Name < B.Name;
});
}
// Map callstack frame addresses to (module, offset) pairs using a sorted
// (Base, End) lookup over the already-populated Model.Modules.
void ResolveCallstacks(const ModuleAnalyzer& ModuleAn,
const CallstackAnalyzer& CallstackAn,
AllocationAnalyzer& AllocAn,
TraceModel& Model)
{
const auto& RawCallstacks = CallstackAn.RawCallstacks();
struct ModuleLookup
{
uint64_t Base;
uint64_t End;
uint32_t ModelIndex;
};
eastl::vector<ModuleLookup> Lookup;
Lookup.reserve(ModuleAn.ModulesByBase.size());
for (const auto& [Base, Info] : ModuleAn.ModulesByBase)
{
for (uint32_t I = 0; I < Model.Modules.size(); ++I)
{
if (Model.Modules[I].Base == Base)
{
Lookup.push_back({Base, Base + Info.Size, I});
break;
}
}
}
eastl::sort(Lookup.begin(), Lookup.end(), [](const ModuleLookup& A, const ModuleLookup& B) { return A.Base < B.Base; });
auto ResolveFrame = [&Lookup](uint64_t Address) -> ResolvedFrame {
ResolvedFrame F;
F.Address = Address;
auto It = eastl::upper_bound(Lookup.begin(), Lookup.end(), Address, [](uint64_t Addr, const ModuleLookup& M) {
return Addr < M.Base;
});
if (It != Lookup.begin())
{
--It;
if (Address < It->End)
{
F.ModuleIndex = It->ModelIndex;
F.Offset = Address - It->Base;
}
}
return F;
};
eastl::vector<uint32_t> SortedCallstackIds;
SortedCallstackIds.reserve(RawCallstacks.size());
for (const auto& [Id, RawFrames] : RawCallstacks)
{
ZEN_UNUSED(RawFrames);
SortedCallstackIds.push_back(Id);
}
eastl::sort(SortedCallstackIds.begin(), SortedCallstackIds.end());
Model.Callstacks.reserve(RawCallstacks.size());
for (uint32_t Id : SortedCallstackIds)
{
auto RawIt = RawCallstacks.find(Id);
ZEN_ASSERT(RawIt != RawCallstacks.end());
const eastl::vector<uint64_t>& RawFrames = RawIt->second;
CallstackEntry Entry;
Entry.Id = Id;
Entry.Frames.reserve(RawFrames.size());
for (uint64_t Addr : RawFrames)
{
Entry.Frames.push_back(ResolveFrame(Addr));
}
Model.Callstacks.push_back(std::move(Entry));
}
Model.CallstackStats = AllocAn.BuildCallstackStats();
Model.ChurnStats = AllocAn.BuildChurnStats(~uint64_t(0));
Model.AllocSizeHistogram = AllocAn.BuildSizeHistogram();
}
} // namespace
TraceModel
BuildTraceModel(const std::filesystem::path& FilePath, WorkerThreadPool& ThreadPool, const ProgressCallback& OnProgress)
{
::DataSource Source(FilePath);
TraceTiming Timing;
SessionAnalyzer SessionAn;
ModuleAnalyzer ModuleAn;
MetadataRegistry MetadataReg;
TimelineAnalyzer TimelineAn(&MetadataReg, &Timing);
LogAnalyzer LogAn(&Timing);
BookmarksAnalyzer BookmarkAn(&Timing);
CsvProfilerAnalyzer CsvAn(&Timing);
AllocationAnalyzer AllocAn(&Timing);
CallstackAnalyzer CallstackAn;
// Tourist's Dispatcher only supports one subscription per event type, so we
// cannot run CpuAnalyzer alongside TimelineAnalyzer -- CpuAnalyzer would
// claim the CpuProfiler.Event* types first and TimelineAnalyzer would
// never receive any events. Instead, TimelineAnalyzer captures every
// scope interval and we derive the aggregate statistics from those
// intervals in a cheap post-pass below.
::Dispatcher Dispatch;
Dispatch.add_analyzer(SessionAn);
Dispatch.add_analyzer(ModuleAn);
Dispatch.add_analyzer(MetadataReg);
Dispatch.add_analyzer(TimelineAn);
Dispatch.add_analyzer(LogAn);
Dispatch.add_analyzer(BookmarkAn);
Dispatch.add_analyzer(CsvAn);
Dispatch.add_analyzer(AllocAn);
Dispatch.add_analyzer(CallstackAn);
zen::Stopwatch Timer;
TraceSummary Summary = IterateTrace(
Source,
[&](const ::EventParcel& Parcel) { Dispatch.on_parcel(Parcel); },
OnProgress);
ZEN_INFO("Trace iteration complete: {} events in {}",
zen::ThousandsNum(Summary.TotalEvents),
zen::NiceTimeSpanMs(Timer.GetElapsedTimeMs()));
{
uint32_t StartUs = (TimelineAn.MinBeginUs() == ~0u) ? 0u : TimelineAn.MinBeginUs();
uint32_t EndUs = TimelineAn.MaxEndUs();
uint64_t DurationMs = (EndUs > StartUs) ? (uint64_t(EndUs - StartUs) + 500) / 1000 : 0;
ZEN_INFO("Trace duration: {}", zen::NiceTimeSpanMs(DurationMs));
}
TraceModel Model;
Model.FilePath = FilePath;
Model.FileSize = uint64_t(std::filesystem::file_size(FilePath));
Model.TotalEvents = Summary.TotalEvents;
Model.ParseTimeMs = Timer.GetElapsedTimeMs();
Model.Session = SessionAn.Session;
// Event type counts (sorted by count descending)
Model.EventTypeCounts.reserve(Summary.TypeInfo.size());
for (auto& [Uid, Info] : Summary.TypeInfo)
{
Model.EventTypeCounts.push_back({std::move(Info.first), Info.second});
}
eastl::sort(Model.EventTypeCounts.begin(), Model.EventTypeCounts.end(), [](const auto& A, const auto& B) { return A.Count > B.Count; });
// Flatten and sort threads by sort hint
Model.Threads.reserve(SessionAn.ThreadNames.size());
for (const auto& [Tid, Info] : SessionAn.ThreadNames)
{
Model.Threads.push_back(Info);
}
eastl::sort(Model.Threads.begin(), Model.Threads.end(), [](const ThreadInfoEntry& A, const ThreadInfoEntry& B) {
return A.SortHint < B.SortHint;
});
// Flatten and sort channels by name
Model.Channels.reserve(SessionAn.Channels.size());
for (const auto& [Id, Info] : SessionAn.Channels)
{
Model.Channels.push_back(Info);
}
eastl::sort(Model.Channels.begin(), Model.Channels.end(), [](const ChannelInfo& A, const ChannelInfo& B) { return A.Name < B.Name; });
{
ExtendableStringBuilder<512> Enabled;
for (const ChannelInfo& Ch : Model.Channels)
{
if (Ch.Enabled)
{
if (Enabled.Size() > 0)
{
Enabled.Append(", ");
}
Enabled.Append(Ch.Name);
}
}
if (Enabled.Size() > 0)
{
ZEN_INFO("Enabled channels: {}", Enabled);
}
}
// Flatten and sort modules by name
Model.Modules.reserve(ModuleAn.ModulesByBase.size());
for (const auto& [Base, Info] : ModuleAn.ModulesByBase)
{
Model.Modules.push_back(Info);
}
eastl::sort(Model.Modules.begin(), Model.Modules.end(), [](const ModuleInfo& A, const ModuleInfo& B) { return A.Name < B.Name; });
// CPU scope statistics and timeline building read from TimelineAn
// independently and write to separate Model fields, so overlap them.
Model.ScopeNames = TimelineAn.ScopeNames();
ZEN_INFO("Computing CPU scope statistics ({} scope names)", TimelineAn.ScopeNames().size());
// Kick off scope stats on a worker -- runs concurrently with the
// timeline copy + sort below.
Latch StatsLatch(1);
ThreadPool.ScheduleWork(
[&StatsLatch, &Model, &TimelineAn]() {
auto _ = MakeGuard([&StatsLatch]() { StatsLatch.CountDown(); });
ComputeScopeStats(TimelineAn, Model);
},
WorkerThreadPool::EMode::EnableBacklog);
// Timelines -- build per-thread sort + LODs in parallel.
{
const auto& Threads = TimelineAn.Threads();
size_t TotalScopes = 0;
for (const auto& [Tid, Thread] : Threads)
{
TotalScopes += Thread.Scopes.size();
}
ZEN_INFO("Building timelines: {} threads, {} scopes (sort + LODs)", Threads.size(), zen::ThousandsNum(TotalScopes));
Model.Timelines.resize(Threads.size());
// Populate timeline metadata on the main thread (cheap lookups).
size_t Idx = 0;
for (const auto& [Tid, Thread] : Threads)
{
ThreadTimeline& Timeline = Model.Timelines[Idx++];
Timeline.ThreadId = Tid;
auto It = SessionAn.ThreadNames.find(Tid);
if (It != SessionAn.ThreadNames.end())
{
Timeline.Name = It->second.Name;
Timeline.SortHint = It->second.SortHint;
}
Timeline.Scopes = Thread.Scopes;
}
// Phase 1: Sort LOD 0 scopes per thread.
// ParallelSort fans out internally using the pool, so it must be
// called from the main thread to avoid nested fan-out deadlocks.
// Small timelines are dispatched to workers first (they just call
// eastl::sort -- no nesting). Then large ones are sorted one at a
// time from the main thread with full pool utilisation each.
//
// Tie-break on Depth so that scopes which start at the same micro
// timestamp come out parent-first (lower depth wins). This keeps
// the scope ordering well-defined and lets the front-end rely on
// outer scopes appearing before their nested children regardless
// of the order the analyzer happened to emit them.
{
auto Cmp = [](const TimelineScope& A, const TimelineScope& B) {
if (A.BeginUs != B.BeginUs)
{
return A.BeginUs < B.BeginUs;
}
return A.Depth < B.Depth;
};
if constexpr (kUseParallelSort)
{
constexpr size_t kParallelThreshold = 65536;
// Dispatch small timelines to workers.
Latch SmallLatch(1);
for (size_t I = 0; I < Model.Timelines.size(); ++I)
{
if (Model.Timelines[I].Scopes.size() >= kParallelThreshold)
{
continue;
}
SmallLatch.AddCount(1);
ThreadPool.ScheduleWork(
[&SmallLatch, &Cmp, &Timeline = Model.Timelines[I]]() {
auto _ = MakeGuard([&SmallLatch]() { SmallLatch.CountDown(); });
eastl::sort(Timeline.Scopes.begin(), Timeline.Scopes.end(), Cmp);
},
WorkerThreadPool::EMode::EnableBacklog);
}
SmallLatch.CountDown();
SmallLatch.Wait();
// Sort large timelines from the main thread so ParallelSort
// can fan out across the (now idle) pool without deadlocking.
for (ThreadTimeline& Timeline : Model.Timelines)
{
if (Timeline.Scopes.size() >= kParallelThreshold)
{
zen::ParallelSort(ThreadPool, Timeline.Scopes.begin(), Timeline.Scopes.end(), Cmp);
}
}
}
else
{
Latch SortLatch(1);
for (size_t I = 0; I < Model.Timelines.size(); ++I)
{
SortLatch.AddCount(1);
ThreadPool.ScheduleWork(
[&SortLatch, &Cmp, &Timeline = Model.Timelines[I]]() {
auto _ = MakeGuard([&SortLatch]() { SortLatch.CountDown(); });
eastl::sort(Timeline.Scopes.begin(), Timeline.Scopes.end(), Cmp);
},
WorkerThreadPool::EMode::EnableBacklog);
}
SortLatch.CountDown();
SortLatch.Wait();
}
}
// Phase 2: Build LOD levels -- one task per (thread, LOD) pair.
// Flat dispatch avoids nested fan-out which could deadlock the pool.
Latch LodLatch(1);
for (size_t I = 0; I < Model.Timelines.size(); ++I)
{
if (Model.Timelines[I].Scopes.empty())
{
continue;
}
for (size_t L = 0; L < kTimelineLodCount; ++L)
{
LodLatch.AddCount(1);
ThreadPool.ScheduleWork(
[&LodLatch, &Timeline = Model.Timelines[I], L]() {
auto _ = MakeGuard([&LodLatch]() { LodLatch.CountDown(); });
BuildSingleLod(Timeline.Scopes, Timeline.DetailLevels[L], kTimelineLodResolutions[L]);
},
WorkerThreadPool::EMode::EnableBacklog);
}
}
LodLatch.CountDown();
LodLatch.Wait();
}
eastl::sort(Model.Timelines.begin(), Model.Timelines.end(), [](const ThreadTimeline& A, const ThreadTimeline& B) {
return A.SortHint < B.SortHint;
});
Model.TraceStartUs = (TimelineAn.MinBeginUs() == ~0u) ? 0u : TimelineAn.MinBeginUs();
Model.TraceEndUs = TimelineAn.MaxEndUs();
// Ensure scope stats computation (kicked off earlier) has finished.
StatsLatch.Wait();
ZEN_INFO("Processing {} log entries", zen::ThousandsNum(LogAn.Entries().size()));
ResolveLogCategories(LogAn, Model);
ZEN_INFO("Sorting {} bookmarks, {} regions", BookmarkAn.MutableBookmarks().size(), BookmarkAn.MutableRegions().size());
// Bookmarks: move and sort by TimeUs.
Model.Bookmarks = std::move(BookmarkAn.MutableBookmarks());
eastl::sort(Model.Bookmarks.begin(), Model.Bookmarks.end(), [](const Bookmark& A, const Bookmark& B) { return A.TimeUs < B.TimeUs; });
BuildRegionCategories(std::move(BookmarkAn.MutableRegions()), Model.TraceEndUs, Model);
// CsvProfiler data
{
Model.CsvCategories = std::move(CsvAn.MutableCategories());
Model.CsvStatDefs = std::move(CsvAn.MutableStatDefs());
Model.CsvTimeSeries = CsvAn.BuildTimeSeries();
Model.CsvEvents = std::move(CsvAn.MutableEvents());
eastl::sort(Model.CsvEvents.begin(), Model.CsvEvents.end(), [](const auto& A, const auto& B) { return A.TimeUs < B.TimeUs; });
Model.CsvMetadata = std::move(CsvAn.MutableMetadata());
ZEN_INFO("CSV profiler: {} categories, {} stats, {} series, {} events",
Model.CsvCategories.size(),
Model.CsvStatDefs.size(),
Model.CsvTimeSeries.size(),
Model.CsvEvents.size());
}
// Memory allocation data
{
AllocAn.EmitFinalSample(Model.TraceEndUs);
Model.AllocSummary = AllocAn.Summary();
// Flatten heaps map into sorted vector
Model.Heaps.reserve(AllocAn.Heaps().size());
for (const auto& [Id, Info] : AllocAn.Heaps())
{
Model.Heaps.push_back(Info);
}
eastl::sort(Model.Heaps.begin(), Model.Heaps.end(), [](const HeapInfo& A, const HeapInfo& B) { return A.Id < B.Id; });
// Flatten tags map into sorted vector
Model.Tags.reserve(AllocAn.Tags().size());
for (const auto& [Tag, Info] : AllocAn.Tags())
{
Model.Tags.push_back(Info);
}
eastl::sort(Model.Tags.begin(), Model.Tags.end(), [](const TagInfo& A, const TagInfo& B) { return A.Tag < B.Tag; });
// Move timeline (already time-ordered from Marker events)
Model.MemoryTimeline = std::move(AllocAn.MutableTimeline());
// Flatten per-root-heap stats into sorted vector
Model.HeapStats.reserve(AllocAn.RootHeapStats().size());
for (const auto& [HeapId, Stat] : AllocAn.RootHeapStats())
{
Model.HeapStats.push_back(Stat);
}
eastl::sort(Model.HeapStats.begin(), Model.HeapStats.end(), [](const HeapStat& A, const HeapStat& B) {
return A.HeapId < B.HeapId;
});
if (Model.AllocSummary.HasMemoryData)
{
ZEN_INFO("Memory: {} allocs, {} frees, peak {}, {} live, {} timeline samples",
zen::ThousandsNum(Model.AllocSummary.TotalAllocs + Model.AllocSummary.TotalReallocAllocs),
zen::ThousandsNum(Model.AllocSummary.TotalFrees + Model.AllocSummary.TotalReallocFrees),
zen::NiceBytes(uint64_t(Model.AllocSummary.PeakBytes)),
zen::ThousandsNum(Model.AllocSummary.LiveAllocations),
zen::ThousandsNum(Model.MemoryTimeline.size()));
}
}
ResolveCallstacks(ModuleAn, CallstackAn, AllocAn, Model);
ZEN_INFO("Callstacks: {} unique, {} with live allocations",
zen::ThousandsNum(Model.Callstacks.size()),
zen::ThousandsNum(Model.CallstackStats.size()));
return Model;
}
//////////////////////////////////////////////////////////////////////////////
// Trace trim
//
// The trim pipeline operates entirely at the raw packet level: a .utrace on
// disk is identical to the wire format (see src/zenserver/trace/tracerecorder.cpp
// for the capture-side passthrough), so trimming reduces to "copy the preamble,
// then copy only the packets we want to keep". We never re-encode or re-emit
// any events, which sidesteps the fact that Tourist has no writer path.
//
// The algorithm:
//
// 1. Slurp the input file into memory and walk raw packets using the
// [size:uint16][thread_id:uint16][payload] framing. This gives an ordered
// list of packet descriptors keyed by file offset.
//
// 2. Classify packets by their on-disk thread_id:
// TID_TYPE -> always keep (type definitions)
// TID_IMPORTANT -> always keep (events of types marked TYPE_FLAG_IMPORTANT,
// i.e. session info, thread names, channel state,
// log categories, CPU specs, etc.)
// TID_SYNC -> always keep (transport barriers)
// TID_NORMAL+ -> keep only if the packet's events overlap the window
//
// 3. For normal-thread packets, run Tourist's reader with a bundle of size 1
// so each Proto.read() scatters exactly one raw packet before emitting any
// events. Before the read call, we record the file offset of the current
// packet as the "latest packet" for its thread. TrimAnalyzer then decodes
// CpuProfiler batch events and attributes their timestamp ranges back to
// that thread's latest packet. The attribution can drift if Tourist
// buffers multiple packets on one thread, but the failure mode is that
// earlier packets lose attribution and are conservatively retained.
//
// 4. Write the output: the preamble bytes verbatim, followed by the raw
// bytes of each kept packet in original order. There is no trailer; the
// Tourist reader catches DataStream::Eof at the end of the stream.
//
// Coarse per-packet precision is accepted by design: a packet straddling a
// window edge is kept in full. CpuProfiler batches are self-contained per
// packet (each re-derives cycles from the trace-wide StartCycle), so dropping
// packets does not desync delta decoding on surviving ones, and orphaned leave
// events from half-open scopes are silently ignored by decoders.
namespace {
struct TrimPacketDesc
{
uint64_t FileOffset = 0; // offset of the [size:uint16] header in the file
uint32_t Size = 0; // total size including the 4-byte header
uint16_t ThreadIdRaw = 0; // thread_id as stored on disk, including PACKET_FLAG_COMPRESSED
};
// Parses the .utrace preamble in place to determine the byte offset where
// packets begin. Mirrors Preamble::parse_header in Tourist so we can run the
// raw walker without spinning up a second DataSource. Throws on a malformed
// preamble.
static uint64_t ParsePreambleLength(const uint8_t* Data, uint64_t Size)
{
if (Size < 8)
{
throw zen::runtime_error("Trace file too small to contain a preamble ({} bytes)", Size);
}
uint32_t Magic = 0;
std::memcpy(&Magic, Data, sizeof(uint32_t));
if (Magic != 'TRC2')
{
throw zen::runtime_error("Unexpected trace file magic value 0x{:08x}", Magic);
}
uint16_t MetaSize = 0;
std::memcpy(&MetaSize, Data + 4, sizeof(uint16_t));
// magic(4) + meta_size(2) + metadata + transport(1) + protocol(1)
uint64_t PreambleLen = uint64_t(4) + 2 + MetaSize + 1 + 1;
if (PreambleLen > Size)
{
throw zen::runtime_error("Trace preamble extends past end of file ({} > {})", PreambleLen, Size);
}
return PreambleLen;
}
// Walks raw packets starting at PreambleLen. Returns one TrimPacketDesc per
// packet in original stream order. The walker stops gracefully on truncated
// data so partial traces still produce a usable packet list.
static eastl::vector<TrimPacketDesc> WalkRawPackets(const uint8_t* Data, uint64_t Size, uint64_t PreambleLen)
{
eastl::vector<TrimPacketDesc> Packets;
uint64_t Offset = PreambleLen;
while (Offset + 4 <= Size)
{
uint16_t PacketSize = 0;
uint16_t ThreadIdRaw = 0;
std::memcpy(&PacketSize, Data + Offset, sizeof(uint16_t));
std::memcpy(&ThreadIdRaw, Data + Offset + 2, sizeof(uint16_t));
if (PacketSize < 4)
{
// Malformed size; stop walking and accept whatever we have.
break;
}
if (Offset + PacketSize > Size)
{
// Truncated tail -- drop it.
break;
}
TrimPacketDesc Desc;
Desc.FileOffset = Offset;
Desc.Size = PacketSize;
Desc.ThreadIdRaw = ThreadIdRaw;
Packets.push_back(Desc);
Offset += PacketSize;
}
return Packets;
}
} // namespace
void
RunTraceTrim(const TraceTrimArgs& Args)
{
if (!(Args.EndSec > Args.StartSec))
{
throw zen::runtime_error("Invalid trim range: start={} end={}", Args.StartSec, Args.EndSec);
}
// --- Read the input file ---
zen::BasicFile InputFile(Args.InputPath, zen::BasicFile::Mode::kRead);
zen::IoBuffer InputBuffer = InputFile.ReadAll();
InputFile.Close();
const uint8_t* FileBytes = static_cast<const uint8_t*>(InputBuffer.GetData());
const uint64_t FileSize = InputBuffer.GetSize();
const uint64_t PreambleLen = ParsePreambleLength(FileBytes, FileSize);
// --- Raw packet walk ---
eastl::vector<TrimPacketDesc> Packets = WalkRawPackets(FileBytes, FileSize, PreambleLen);
if (Packets.empty())
{
throw zen::runtime_error("Trace file contains no packets");
}
// Initial keep classification: definitions, important events, sync are
// always retained. Normal-thread packets start as drop candidates and get
// promoted if their decoded time range overlaps the window.
eastl::vector<uint8_t> Keep(Packets.size(), 0);
size_t NumAlwaysKept = 0;
for (size_t I = 0; I < Packets.size(); ++I)
{
uint32_t Tid = Packets[I].ThreadIdRaw & ~PACKET_FLAG_COMPRESSED;
if (Tid == TID_TYPE || Tid == TID_IMPORTANT || Tid == TID_SYNC)
{
Keep[I] = 1;
++NumAlwaysKept;
}
}
// --- Time-range classification via Tourist (bundle of 1) ---
TrimAnalyzer TrimAn;
TrimAn.EndUs = (Args.EndSec * 1e6 > double(~uint32_t(0))) ? ~uint32_t(0) : uint32_t(Args.EndSec * 1e6);
::Dispatcher Dispatch;
Dispatch.add_analyzer(TrimAn);
{
::DataSource Source(Args.InputPath);
::Allocator TraceAllocator;
::Preamble Pream(Source, TraceAllocator);
::Transport Xport = Pream.get_transport();
::Protocol Proto = Pream.get_protocol();
::Packet OnePacket[1];
::EventParcel Parcel;
try
{
while (::Bundle Bndl = Xport.read_packets(OnePacket))
{
if (Bndl.empty())
{
break;
}
const ::Packet& P = Bndl[0];
uint32_t Tid = P.get_thread_id();
if (Tid >= TID_NORMAL && Tid != TID_SYNC)
{
// Tourist's Packet::get_index() is the same sequential
// packet counter as our raw walker's vector position,
// since both read the stream from the start in order.
TrimAn.LastPacketIndexByThread[Tid] = P.get_index();
}
Parcel.reset();
Proto.read(Parcel, Bndl);
Dispatch.on_parcel(Parcel);
}
}
catch (const DataStream::Eof&)
{
}
catch (const Exception::StreamError& E)
{
throw zen::runtime_error("Trace stream error at position {}: {} (value: {})", E.position, E.message, E.value);
}
}
// --- Apply the window filter ---
//
// Per-packet filtering in the middle of a thread's stream is unsafe:
// Tourist's event parser holds per-thread continuation state (see
// EventParser::_fragment / _missing in
// thirdparty/tourist/trace/src/protocol.cpp) so an event can straddle a
// packet boundary on a normal thread. Removing a packet from the middle
// leaves subsequent packets on the same thread decoded against the wrong
// position in an in-flight event and Tourist crashes. We therefore only
// drop packets in two safe ways:
//
// 1. Whole-thread drop: a thread whose attributed packets are all
// outside the window has every one of its packets dropped. No
// surviving packet references that thread, so there is no state
// machine to corrupt.
//
// 2. Per-thread tail truncation: for a thread that does have in-window
// activity, drop every packet AFTER the latest in-window packet on
// that thread. Tail drops are safe because no later packet on the
// same thread can be looking forward to the dropped bytes; the
// parser just ends its stream for that thread at the truncation
// point, exactly like a trace that naturally stopped recording.
//
// Threads for which we never attributed any CpuProfiler batch events are
// retained in full; we have no evidence about their time range and
// can't safely drop them.
const uint32_t StartUs = uint32_t(std::max(0.0, Args.StartSec) * 1e6);
const uint32_t EndUs = (Args.EndSec * 1e6 > double(~uint32_t(0))) ? ~uint32_t(0) : uint32_t(Args.EndSec * 1e6);
struct ThreadInfo
{
bool HasAnyBatch = false;
bool HasInWindowBatch = false;
// First packet index on this thread whose attributed CPU batches are
// *entirely* past EndUs. Every packet on this thread with an index
// >= this value is safe to tail-drop. Defaults to size_t(-1) (no cut
// point) when the thread has no such packet.
size_t FirstPastWindowIdx = size_t(-1);
};
eastl::hash_map<uint32_t, ThreadInfo> ThreadInfos;
for (size_t I = 0; I < Packets.size(); ++I)
{
uint32_t Tid = Packets[I].ThreadIdRaw & ~PACKET_FLAG_COMPRESSED;
if (Tid < TID_NORMAL || Tid == TID_SYNC)
{
continue;
}
auto RangeIt = TrimAn.PacketRanges.find(uint32_t(I));
if (RangeIt == TrimAn.PacketRanges.end())
{
continue;
}
ThreadInfo& Info = ThreadInfos[Tid];
Info.HasAnyBatch = true;
const auto& Range = RangeIt->second;
if (Range.MaxUs >= StartUs && Range.MinUs <= EndUs)
{
Info.HasInWindowBatch = true;
}
if (Range.MinUs > EndUs && I < Info.FirstPastWindowIdx)
{
Info.FirstPastWindowIdx = I;
}
}
size_t NumThreadsKept = 0;
size_t NumThreadsDropped = 0;
for (const auto& [Tid, Info] : ThreadInfos)
{
if (Info.HasInWindowBatch)
{
++NumThreadsKept;
}
else
{
++NumThreadsDropped;
}
}
size_t NumInWindow = 0;
size_t NumTailDropped = 0;
size_t NumUnattributed = 0;
size_t NumDropped = 0;
for (size_t I = 0; I < Packets.size(); ++I)
{
if (Keep[I])
{
continue;
}
uint32_t Tid = Packets[I].ThreadIdRaw & ~PACKET_FLAG_COMPRESSED;
auto It = ThreadInfos.find(Tid);
if (It == ThreadInfos.end() || !It->second.HasAnyBatch)
{
// We have no evidence for this thread's time range. Retain all
// its packets conservatively to avoid breaking Tourist's per-
// thread parser state.
Keep[I] = 1;
++NumUnattributed;
continue;
}
if (!It->second.HasInWindowBatch)
{
// Thread's attributed packets are all outside the window -- drop
// every packet on this thread.
++NumDropped;
continue;
}
if (I >= It->second.FirstPastWindowIdx)
{
// Past the first entirely-after-window packet on this thread --
// candidate for tail truncation. Before dropping, check whether
// this packet carries a Leave event that closes a scope whose
// Enter was at or before the window end. If so, we MUST keep it
// so the downstream analyzer can render the long-running scope;
// otherwise the scope would sit unmatched on the open stack.
auto MustKeepIt = TrimAn.MustKeepPacketByThread.find(Tid);
if (MustKeepIt != TrimAn.MustKeepPacketByThread.end() && I <= MustKeepIt->second)
{
Keep[I] = 1;
++NumInWindow;
continue;
}
++NumTailDropped;
continue;
}
Keep[I] = 1;
++NumInWindow;
}
// --- Write output ---
std::error_code Ec;
std::filesystem::create_directories(Args.OutputPath.parent_path(), Ec);
zen::BasicFile OutputFile(Args.OutputPath, zen::BasicFile::Mode::kTruncate);
uint64_t OutOffset = 0;
OutputFile.Write(FileBytes, PreambleLen, OutOffset);
OutOffset += PreambleLen;
uint64_t KeptBytes = 0;
for (size_t I = 0; I < Packets.size(); ++I)
{
if (!Keep[I])
{
continue;
}
OutputFile.Write(FileBytes + Packets[I].FileOffset, Packets[I].Size, OutOffset);
OutOffset += Packets[I].Size;
KeptBytes += Packets[I].Size;
}
OutputFile.Flush();
OutputFile.Close();
ZEN_CONSOLE("Trimmed trace written to {}", Args.OutputPath);
ZEN_CONSOLE(" Input: {} ({} packets)", zen::NiceBytes(FileSize), zen::ThousandsNum(Packets.size()));
ZEN_CONSOLE(" Output: {} ({} packets)",
zen::NiceBytes(OutOffset),
zen::ThousandsNum(NumAlwaysKept + NumInWindow + NumUnattributed));
ZEN_CONSOLE(" Always kept: {} packets (types / important / sync)", zen::ThousandsNum(NumAlwaysKept));
ZEN_CONSOLE(" Thread kept: {} packets from {} threads with in-window activity",
zen::ThousandsNum(NumInWindow),
zen::ThousandsNum(NumThreadsKept));
ZEN_CONSOLE(" Thread dropped: {} packets from {} threads with no in-window activity",
zen::ThousandsNum(NumDropped),
zen::ThousandsNum(NumThreadsDropped));
ZEN_CONSOLE(" Tail dropped: {} packets past the latest in-window packet on their thread", zen::ThousandsNum(NumTailDropped));
ZEN_CONSOLE(" Unattributed: {} packets (retained conservatively)", zen::ThousandsNum(NumUnattributed));
ZEN_UNUSED(KeptBytes);
// --- Diagnostic: summarise the attributed time range distribution ---
{
uint32_t GlobalMin = ~0u;
uint32_t GlobalMax = 0;
for (const auto& [Idx, R] : TrimAn.PacketRanges)
{
GlobalMin = std::min(GlobalMin, R.MinUs);
GlobalMax = std::max(GlobalMax, R.MaxUs);
}
ZEN_CONSOLE(" Attributed: {} packets, window {:.3f}s .. {:.3f}s",
zen::ThousandsNum(TrimAn.PacketRanges.size()),
double(GlobalMin) / 1e6,
double(GlobalMax) / 1e6);
}
}
} // namespace zen::trace_detail
|