wavepeek 2.0.0

Command-line tool for RTL waveform inspection with deterministic machine-friendly output.
Documentation
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
#include "wavepeek_fsdb_shim.h"

#include "ffrAPI.h"

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <exception>
#include <limits>
#include <memory>
#include <mutex>
#include <new>
#include <string>
#include <unordered_map>
#include <utility>
#include <unordered_set>
#include <vector>

#include <fcntl.h>
#include <unistd.h>

struct wp_fsdb_signal_session;

struct wp_fsdb_reader {
    ffrObject *object;
    wp_fsdb_signal_session *active_signal_session;
};

namespace {

bool native_verbose_enabled() {
    const char *value = std::getenv("WAVEPEEK_FSDB_NATIVE_VERBOSE");
    return value != nullptr && std::strcmp(value, "1") == 0;
}

std::recursive_mutex &reader_mutex() {
    static std::recursive_mutex mutex;
    return mutex;
}

class scoped_output_suppressor {
  public:
    scoped_output_suppressor() {
        if (native_verbose_enabled()) {
            return;
        }

        std::fflush(stdout);
        std::fflush(stderr);

        devnull_ = open("/dev/null", O_WRONLY);
        if (devnull_ < 0) {
            return;
        }

        saved_stdout_ = dup(STDOUT_FILENO);
        saved_stderr_ = dup(STDERR_FILENO);
        if (saved_stdout_ >= 0) {
            dup2(devnull_, STDOUT_FILENO);
        }
        if (saved_stderr_ >= 0) {
            dup2(devnull_, STDERR_FILENO);
        }
    }

    scoped_output_suppressor(const scoped_output_suppressor &) = delete;
    scoped_output_suppressor &operator=(const scoped_output_suppressor &) = delete;

    ~scoped_output_suppressor() {
        if (devnull_ < 0) {
            return;
        }

        std::fflush(stdout);
        std::fflush(stderr);

        if (saved_stdout_ >= 0) {
            dup2(saved_stdout_, STDOUT_FILENO);
            close(saved_stdout_);
        }
        if (saved_stderr_ >= 0) {
            dup2(saved_stderr_, STDERR_FILENO);
            close(saved_stderr_);
        }
        close(devnull_);
    }

  private:
    int devnull_ = -1;
    int saved_stdout_ = -1;
    int saved_stderr_ = -1;
};

void suppress_reader_messages() {
    ffrObject::ffrInfoSuppress(1);
    ffrObject::ffrWarnSuppress(1);
}

char *copy_string(const char *value) {
    if (value == nullptr) {
        value = "";
    }

    const std::size_t length = std::strlen(value);
    char *copy = static_cast<char *>(std::malloc(length + 1));
    if (copy == nullptr) {
        return nullptr;
    }

    std::memcpy(copy, value, length + 1);
    return copy;
}

wp_fsdb_status fail(char **error_message, const std::string &message) {
    if (error_message != nullptr) {
        *error_message = copy_string(message.c_str());
    }
    return WP_FSDB_STATUS_ERROR;
}

wp_fsdb_status fail_unknown_exception(char **error_message) {
    return fail(error_message, "FSDB Reader: native shim caught an unknown C++ exception");
}

uint64_t tag64_to_u64(const fsdbTag64 &tag) {
    return (static_cast<uint64_t>(tag.H) << 32) | static_cast<uint64_t>(tag.L);
}

fsdbTag64 u64_to_tag64(uint64_t value) {
    fsdbTag64 tag{};
    tag.H = static_cast<uint32_t>(value >> 32);
    tag.L = static_cast<uint32_t>(value & 0xffffffffu);
    return tag;
}

wp_fsdb_status require_integer_time_tags(ffrObject *object, char **error_message) {
    if (object == nullptr) {
        return fail(error_message, "FSDB Reader: time tag validation received a null reader");
    }

    const fsdbXTagType xtag_type = object->ffrGetXTagType();
    if (xtag_type != FSDB_XTAG_TYPE_L && xtag_type != FSDB_XTAG_TYPE_HL) {
        return fail(
            error_message,
            "FSDB Reader: unsupported non-integer FSDB time tag representation"
        );
    }
    return WP_FSDB_STATUS_OK;
}

struct free_deleter {
    void operator()(char *value) const {
        std::free(value);
    }
};

using owned_c_string = std::unique_ptr<char, free_deleter>;

void clear_error(char **error_message) {
    if (error_message != nullptr) {
        *error_message = nullptr;
    }
}

wp_fsdb_status reject_active_signal_session(
    wp_fsdb_reader *reader,
    const char *operation,
    char **error_message
) {
    if (reader != nullptr && reader->active_signal_session != nullptr) {
        return fail(
            error_message,
            std::string("FSDB Reader: cannot perform one-shot ") + operation +
                " while an FSDB signal session is active"
        );
    }
    return WP_FSDB_STATUS_OK;
}

wp_fsdb_scope_kind map_scope_kind(uint_T raw_type) {
    switch (raw_type) {
    case FSDB_ST_VCD_MODULE:
    case FSDB_ST_SV_MODULE:
    case FSDB_ST_SC_MODULE:
        return WP_FSDB_SCOPE_KIND_MODULE;
    case FSDB_ST_VCD_TASK:
        return WP_FSDB_SCOPE_KIND_TASK;
    case FSDB_ST_VCD_FUNCTION:
    case FSDB_ST_VHDL_FUNCTION:
        return WP_FSDB_SCOPE_KIND_FUNCTION;
    case FSDB_ST_VCD_BEGIN:
        return WP_FSDB_SCOPE_KIND_BEGIN;
    case FSDB_ST_VCD_FORK:
        return WP_FSDB_SCOPE_KIND_FORK;
    case FSDB_ST_VCD_GENERATE:
    case FSDB_ST_VHDL_GENERATE:
    case FSDB_ST_VHDL_FOR_GENERATE:
    case FSDB_ST_VHDL_IF_GENERATE:
        return WP_FSDB_SCOPE_KIND_GENERATE;
    case FSDB_ST_VHDL_RECORD:
        return WP_FSDB_SCOPE_KIND_STRUCT;
    case FSDB_ST_SV_CLASS:
        return WP_FSDB_SCOPE_KIND_CLASS;
    case FSDB_ST_SV_INTERFACE:
    case FSDB_ST_SV_MODPORT:
    case FSDB_ST_SV_INTERFACEPORT_REF:
    case FSDB_ST_SV_MODPORT_REF:
    case FSDB_ST_SV_INTERFACE_PORT:
    case FSDB_ST_SV_MODPORT_PORT:
        return WP_FSDB_SCOPE_KIND_INTERFACE;
    case FSDB_ST_SV_PACKAGE:
        return WP_FSDB_SCOPE_KIND_PACKAGE;
    case FSDB_ST_SV_PROGRAM:
        return WP_FSDB_SCOPE_KIND_PROGRAM;
    default:
        return WP_FSDB_SCOPE_KIND_UNKNOWN;
    }
}

wp_fsdb_signal_kind map_signal_kind(uint_T raw_type) {
    const uint_T type = raw_type & ~static_cast<uint_T>(FSDB_VT_MC_MASK);
    switch (type) {
    case FSDB_VT_VCD_EVENT:
    case FSDB_VT_EVENT_VARIABLE:
        return WP_FSDB_SIGNAL_KIND_EVENT;
    case FSDB_VT_VCD_INTEGER:
        return WP_FSDB_SIGNAL_KIND_INTEGER;
    case FSDB_VT_VCD_PARAMETER:
        return WP_FSDB_SIGNAL_KIND_PARAMETER;
    case FSDB_VT_VCD_REAL:
        return WP_FSDB_SIGNAL_KIND_REAL;
    case FSDB_VT_VCD_REG:
    case FSDB_VT_VCD_REG2:
        return WP_FSDB_SIGNAL_KIND_REG;
    case FSDB_VT_VCD_SUPPLY0:
        return WP_FSDB_SIGNAL_KIND_SUPPLY0;
    case FSDB_VT_VCD_SUPPLY1:
        return WP_FSDB_SIGNAL_KIND_SUPPLY1;
    case FSDB_VT_VCD_TIME:
        return WP_FSDB_SIGNAL_KIND_TIME;
    case FSDB_VT_VCD_TRI:
        return WP_FSDB_SIGNAL_KIND_TRI;
    case FSDB_VT_VCD_TRIAND:
        return WP_FSDB_SIGNAL_KIND_TRIAND;
    case FSDB_VT_VCD_TRIOR:
        return WP_FSDB_SIGNAL_KIND_TRIOR;
    case FSDB_VT_VCD_TRIREG:
        return WP_FSDB_SIGNAL_KIND_TRIREG;
    case FSDB_VT_VCD_TRI0:
        return WP_FSDB_SIGNAL_KIND_TRI0;
    case FSDB_VT_VCD_TRI1:
        return WP_FSDB_SIGNAL_KIND_TRI1;
    case FSDB_VT_VCD_WAND:
        return WP_FSDB_SIGNAL_KIND_WAND;
    case FSDB_VT_VCD_WIRE:
        return WP_FSDB_SIGNAL_KIND_WIRE;
    case FSDB_VT_VCD_WOR:
        return WP_FSDB_SIGNAL_KIND_WOR;
    case FSDB_VT_STRING:
        return WP_FSDB_SIGNAL_KIND_STRING;
    case FSDB_VT_VCD_PORT:
        return WP_FSDB_SIGNAL_KIND_PORT;
    case FSDB_VT_VCD_MEMORY:
    case FSDB_VT_VHDL_MEMORY:
        return WP_FSDB_SIGNAL_KIND_SPARSE_ARRAY;
    case FSDB_VT_AMS_SIGNAL:
        return WP_FSDB_SIGNAL_KIND_REAL;
    case FSDB_VT_VHDL_SIGNAL:
    case FSDB_VT_VHDL_VARIABLE:
    case FSDB_VT_VHDL_CONSTANT:
    case FSDB_VT_SV_VARIABLE:
        return WP_FSDB_SIGNAL_KIND_LOGIC;
    default:
        return WP_FSDB_SIGNAL_KIND_UNKNOWN;
    }
}

bool is_known_non_vector_signal(wp_fsdb_signal_kind kind) {
    switch (kind) {
    case WP_FSDB_SIGNAL_KIND_EVENT:
    case WP_FSDB_SIGNAL_KIND_REAL:
    case WP_FSDB_SIGNAL_KIND_STRING:
    case WP_FSDB_SIGNAL_KIND_SPARSE_ARRAY:
    case WP_FSDB_SIGNAL_KIND_REAL_TIME:
    case WP_FSDB_SIGNAL_KIND_REAL_PARAMETER:
    case WP_FSDB_SIGNAL_KIND_SHORT_REAL:
        return true;
    default:
        return false;
    }
}

wp_fsdb_value_encoding classify_value_encoding(
    const fsdbTreeCBDataVar *var,
    wp_fsdb_signal_kind kind
) {
    if (var == nullptr || is_known_non_vector_signal(kind)) {
        return WP_FSDB_VALUE_ENCODING_UNSUPPORTED;
    }
    if (var->is_dummy_var || var->is_class_in_obj || var->is_void || var->is_unexpanded_mem_var) {
        return WP_FSDB_VALUE_ENCODING_UNSUPPORTED;
    }
    if (kind == WP_FSDB_SIGNAL_KIND_UNKNOWN) {
        return WP_FSDB_VALUE_ENCODING_DATATYPE_CANDIDATE;
    }
    return WP_FSDB_VALUE_ENCODING_BIT_VECTOR;
}

wp_fsdb_datatype_kind map_datatype_kind(fsdbTreeCBType type) {
    switch (type) {
    case FSDB_TREE_CBT_DT_ENUM:
    case FSDB_TREE_CBT_DT_ENUM2:
    case FSDB_TREE_CBT_DT_ENUM3:
    case FSDB_TREE_CBT_DT_ATTR_ENUM:
    case FSDB_TREE_CBT_DT_ATTR_SV_ENUM:
        return WP_FSDB_DATATYPE_KIND_ENUM;
    case FSDB_TREE_CBT_DT_INT:
    case FSDB_TREE_CBT_DT_INT_H_N_L:
        return WP_FSDB_DATATYPE_KIND_INT;
    case FSDB_TREE_CBT_DT_ATTR_LOGIC:
    case FSDB_TREE_CBT_DT_ATTR_SV_LOGIC:
    case FSDB_TREE_CBT_DT_ATTR_SV_REG:
        return WP_FSDB_DATATYPE_KIND_LOGIC;
    case FSDB_TREE_CBT_DT_ATTR_BOOL:
    case FSDB_TREE_CBT_DT_ATTR_SV_BIT:
        return WP_FSDB_DATATYPE_KIND_BIT;
    case FSDB_TREE_CBT_DT_ATTR_INT32:
    case FSDB_TREE_CBT_DT_ATTR_SV_INT:
    case FSDB_TREE_CBT_DT_ATTR_SV_INTEGER:
        return WP_FSDB_DATATYPE_KIND_INT;
    case FSDB_TREE_CBT_DT_ATTR_UINT32:
    case FSDB_TREE_CBT_DT_ATTR_SV_UINT:
    case FSDB_TREE_CBT_DT_ATTR_SV_UINTEGER:
        return WP_FSDB_DATATYPE_KIND_UINT;
    case FSDB_TREE_CBT_DT_ATTR_INT64:
    case FSDB_TREE_CBT_DT_ATTR_SV_LONG_INT:
        return WP_FSDB_DATATYPE_KIND_LONG_INT;
    case FSDB_TREE_CBT_DT_ATTR_UINT64:
    case FSDB_TREE_CBT_DT_ATTR_SV_LONG_UINT:
        return WP_FSDB_DATATYPE_KIND_LONG_UINT;
    case FSDB_TREE_CBT_DT_ATTR_SV_SHORT_INT:
        return WP_FSDB_DATATYPE_KIND_SHORT_INT;
    case FSDB_TREE_CBT_DT_ATTR_SV_SHORT_UINT:
        return WP_FSDB_DATATYPE_KIND_SHORT_UINT;
    case FSDB_TREE_CBT_DT_ATTR_SV_BYTE_INT:
        return WP_FSDB_DATATYPE_KIND_BYTE;
    case FSDB_TREE_CBT_DT_ATTR_SV_BYTE_UINT:
        return WP_FSDB_DATATYPE_KIND_UBYTE;
    case FSDB_TREE_CBT_DT_FLOAT:
    case FSDB_TREE_CBT_DT_ATTR_FLOAT:
    case FSDB_TREE_CBT_DT_ATTR_DOUBLE:
    case FSDB_TREE_CBT_DT_ATTR_SV_REAL:
        return WP_FSDB_DATATYPE_KIND_REAL;
    case FSDB_TREE_CBT_DT_ATTR_SV_SHORT_REAL:
        return WP_FSDB_DATATYPE_KIND_SHORT_REAL;
    case FSDB_TREE_CBT_DT_ATTR_SV_TIME:
        return WP_FSDB_DATATYPE_KIND_TIME;
    case FSDB_TREE_CBT_DT_ATTR_STRING:
    case FSDB_TREE_CBT_DT_ATTR_SV_STRING:
    case FSDB_TREE_CBT_DT_ATTR_RAW_STRING:
        return WP_FSDB_DATATYPE_KIND_STRING;
    case FSDB_TREE_CBT_DT_ATTR_EVENT:
    case FSDB_TREE_CBT_DT_ATTR_SV_EVENT:
        return WP_FSDB_DATATYPE_KIND_EVENT;
    default:
        return WP_FSDB_DATATYPE_KIND_UNKNOWN;
    }
}

bool bit_value_to_char(byte_T value, char *out);

uint32_t bit_width_from_bounds(int left, int right) {
    const int64_t left64 = static_cast<int64_t>(left);
    const int64_t right64 = static_cast<int64_t>(right);
    const uint64_t diff = left64 >= right64
        ? static_cast<uint64_t>(left64 - right64)
        : static_cast<uint64_t>(right64 - left64);
    if (diff >= static_cast<uint64_t>(std::numeric_limits<uint32_t>::max())) {
        return 0;
    }
    return static_cast<uint32_t>(diff + 1);
}

uint32_t datatype_default_bit_width(wp_fsdb_datatype_kind kind) {
    switch (kind) {
    case WP_FSDB_DATATYPE_KIND_BYTE:
    case WP_FSDB_DATATYPE_KIND_UBYTE:
        return 8;
    case WP_FSDB_DATATYPE_KIND_SHORT_INT:
    case WP_FSDB_DATATYPE_KIND_SHORT_UINT:
        return 16;
    case WP_FSDB_DATATYPE_KIND_INT:
    case WP_FSDB_DATATYPE_KIND_UINT:
        return 32;
    case WP_FSDB_DATATYPE_KIND_LONG_INT:
    case WP_FSDB_DATATYPE_KIND_LONG_UINT:
    case WP_FSDB_DATATYPE_KIND_TIME:
        return 64;
    default:
        return 0;
    }
}

bool datatype_kind_signedness(wp_fsdb_datatype_kind kind, bool *out) {
    if (out == nullptr) {
        return false;
    }
    switch (kind) {
    case WP_FSDB_DATATYPE_KIND_INT:
    case WP_FSDB_DATATYPE_KIND_SHORT_INT:
    case WP_FSDB_DATATYPE_KIND_LONG_INT:
    case WP_FSDB_DATATYPE_KIND_BYTE:
        *out = true;
        return true;
    case WP_FSDB_DATATYPE_KIND_UINT:
    case WP_FSDB_DATATYPE_KIND_SHORT_UINT:
    case WP_FSDB_DATATYPE_KIND_LONG_UINT:
    case WP_FSDB_DATATYPE_KIND_UBYTE:
    case WP_FSDB_DATATYPE_KIND_TIME:
        *out = false;
        return true;
    default:
        return false;
    }
}

bool datatype_kind_uses_radix_signedness(wp_fsdb_datatype_kind kind) {
    return kind == WP_FSDB_DATATYPE_KIND_LOGIC || kind == WP_FSDB_DATATYPE_KIND_BIT;
}

bool attr_radix_signedness(fsdbAttrRadix radix, bool *out) {
    if (out == nullptr) {
        return false;
    }
    switch (radix) {
    case FSDB_ATTR_RADIX_DEC:
        *out = true;
        return true;
    case FSDB_ATTR_RADIX_UNSIGNED:
        *out = false;
        return true;
    default:
        return false;
    }
}

void set_record_bit_width(wp_fsdb_datatype_record *record, uint32_t width) {
    if (record == nullptr || width == 0) {
        return;
    }
    record->has_bit_width = 1;
    record->bit_width = width;
}

void set_record_signedness(wp_fsdb_datatype_record *record, bool is_signed) {
    if (record == nullptr) {
        return;
    }
    record->has_is_signed = 1;
    record->is_signed = is_signed ? 1 : 0;
}

bool enum_value_type_is_logic(byte_T val_type) {
    switch (val_type) {
    case FSDB_ENUM_VALUE_TYPE_LOGIC:
    case FSDB_ENUM_VALUE_TYPE_VERILOG_LOGIC:
    case FSDB_ENUM_VALUE_TYPE_VHDL_LOGIC:
        return true;
    default:
        return false;
    }
}

bool enum_value_type_signedness(byte_T val_type, bool *out) {
    if (out == nullptr) {
        return false;
    }
    switch (val_type) {
    case FSDB_ENUM_VALUE_TYPE_INTEGER:
    case FSDB_ENUM_VALUE_TYPE_LONG:
    case FSDB_ENUM_VALUE_TYPE_SHORT:
    case FSDB_ENUM_VALUE_TYPE_BYTE:
    case FSDB_ENUM_VALUE_TYPE_SV_LONG:
    case FSDB_ENUM_VALUE_TYPE_SV_INTEGER:
    case FSDB_ENUM_VALUE_TYPE_SV_SHORT:
    case FSDB_ENUM_VALUE_TYPE_SV_BYTE:
        *out = true;
        return true;
    case FSDB_ENUM_VALUE_TYPE_UNSIGN_LONG:
    case FSDB_ENUM_VALUE_TYPE_UNSIGN_INTEGER:
    case FSDB_ENUM_VALUE_TYPE_UNSIGN_SHORT:
    case FSDB_ENUM_VALUE_TYPE_UNSIGN_BYTE:
    case FSDB_ENUM_VALUE_TYPE_SV_UNSIGN_LONG:
    case FSDB_ENUM_VALUE_TYPE_SV_UNSIGN_INTEGER:
    case FSDB_ENUM_VALUE_TYPE_SV_UNSIGN_SHORT:
    case FSDB_ENUM_VALUE_TYPE_SV_UNSIGN_BYTE:
        *out = false;
        return true;
    default:
        return false;
    }
}

bool enum_attr_signedness(byte_T val_type, fsdbAttrRadix radix, bool *out) {
    if (enum_value_type_signedness(val_type, out)) {
        return true;
    }
    if (enum_value_type_is_logic(val_type)) {
        return attr_radix_signedness(radix, out);
    }
    return false;
}

uint32_t enum_integral_default_bit_width(byte_T val_type) {
    switch (val_type) {
    case FSDB_ENUM_VALUE_TYPE_LONG:
    case FSDB_ENUM_VALUE_TYPE_UNSIGN_LONG:
    case FSDB_ENUM_VALUE_TYPE_SV_LONG:
    case FSDB_ENUM_VALUE_TYPE_SV_UNSIGN_LONG:
        return 64;
    case FSDB_ENUM_VALUE_TYPE_SHORT:
    case FSDB_ENUM_VALUE_TYPE_UNSIGN_SHORT:
    case FSDB_ENUM_VALUE_TYPE_SV_SHORT:
    case FSDB_ENUM_VALUE_TYPE_SV_UNSIGN_SHORT:
        return 16;
    case FSDB_ENUM_VALUE_TYPE_BYTE:
    case FSDB_ENUM_VALUE_TYPE_UNSIGN_BYTE:
    case FSDB_ENUM_VALUE_TYPE_SV_BYTE:
    case FSDB_ENUM_VALUE_TYPE_SV_UNSIGN_BYTE:
        return 8;
    case FSDB_ENUM_VALUE_TYPE_INTEGER:
    case FSDB_ENUM_VALUE_TYPE_UNSIGN_INTEGER:
    case FSDB_ENUM_VALUE_TYPE_SV_INTEGER:
    case FSDB_ENUM_VALUE_TYPE_SV_UNSIGN_INTEGER:
        return 32;
    default:
        return 0;
    }
}

enum class enum_value_len_mode {
    bit_width,
    byte_count,
};

uint32_t enum_value_bit_width(
    byte_T val_type,
    uint_T val_len,
    uint32_t bit_width_hint,
    enum_value_len_mode len_mode
) {
    if (bit_width_hint != 0) {
        return bit_width_hint;
    }
    if (enum_value_type_is_logic(val_type) || len_mode == enum_value_len_mode::bit_width) {
        return static_cast<uint32_t>(val_len);
    }
    if (val_len != 0 && val_len <= std::numeric_limits<uint32_t>::max() / 8) {
        return static_cast<uint32_t>(val_len * 8);
    }
    return enum_integral_default_bit_width(val_type);
}

std::size_t enum_integral_value_byte_count(
    byte_T val_type,
    uint_T val_len,
    uint32_t bit_width,
    enum_value_len_mode len_mode
) {
    if (len_mode == enum_value_len_mode::byte_count && val_len != 0) {
        return static_cast<std::size_t>(val_len);
    }
    if (len_mode == enum_value_len_mode::bit_width && val_len != 0) {
        return static_cast<std::size_t>((val_len + 7) / 8);
    }
    const uint32_t default_width = enum_integral_default_bit_width(val_type);
    if (default_width != 0) {
        return static_cast<std::size_t>((default_width + 7) / 8);
    }
    return static_cast<std::size_t>((bit_width + 7) / 8);
}

bool enum_logic_value_to_char(byte_T val_type, byte_T value, char *out) {
    if (val_type == FSDB_ENUM_VALUE_TYPE_VHDL_LOGIC) {
        if (out == nullptr) {
            return false;
        }
        switch (value) {
        case FSDB_BT_VHDL_STD_LOGIC_0:
        case FSDB_BT_VHDL_STD_LOGIC_L:
            *out = '0';
            return true;
        case FSDB_BT_VHDL_STD_LOGIC_1:
        case FSDB_BT_VHDL_STD_LOGIC_H:
            *out = '1';
            return true;
        case FSDB_BT_VHDL_STD_LOGIC_Z:
            *out = 'z';
            return true;
        case FSDB_BT_VHDL_STD_LOGIC_U:
        case FSDB_BT_VHDL_STD_LOGIC_X:
        case FSDB_BT_VHDL_STD_LOGIC_W:
        case FSDB_BT_VHDL_STD_LOGIC_DASH:
            *out = 'x';
            return true;
        default:
            return false;
        }
    }
    return bit_value_to_char(value, out);
}

bool decode_logic_enum_bits(
    const byte_T *value,
    byte_T val_type,
    uint32_t bit_width,
    std::string *bits
) {
    if (value == nullptr || bits == nullptr || bit_width == 0) {
        return false;
    }
    bits->assign(static_cast<std::size_t>(bit_width), '\0');
    for (uint32_t bit_index = 0; bit_index < bit_width; ++bit_index) {
        if (!enum_logic_value_to_char(val_type, value[bit_index], &(*bits)[bit_index])) {
            return false;
        }
    }
    return true;
}

bool decode_integral_enum_bits(
    const byte_T *value,
    byte_T val_type,
    uint_T val_len,
    uint32_t bit_width_hint,
    enum_value_len_mode len_mode,
    std::string *bits
) {
    const uint32_t bit_width = enum_value_bit_width(val_type, val_len, bit_width_hint, len_mode);
    if (value == nullptr || bits == nullptr || bit_width == 0 || bit_width > 64) {
        return false;
    }
    const std::size_t byte_count =
        enum_integral_value_byte_count(val_type, val_len, bit_width, len_mode);
    if (byte_count == 0 || byte_count > sizeof(uint64_t)) {
        return false;
    }

    uint64_t raw_value = 0;
    for (std::size_t byte_index = 0; byte_index < byte_count; ++byte_index) {
        raw_value |= static_cast<uint64_t>(value[byte_index]) << (byte_index * 8);
    }

    bits->assign(static_cast<std::size_t>(bit_width), '0');
    for (uint32_t bit_index = 0; bit_index < bit_width; ++bit_index) {
        const uint32_t shift = bit_width - bit_index - 1;
        (*bits)[bit_index] = ((raw_value >> shift) & 1u) != 0 ? '1' : '0';
    }
    return true;
}

bool decode_enum_value_bits(
    const byte_T *value,
    byte_T val_type,
    uint_T val_len,
    uint32_t bit_width_hint,
    enum_value_len_mode len_mode,
    std::string *bits
) {
    if (enum_value_type_is_logic(val_type)) {
        const uint32_t bit_width =
            enum_value_bit_width(val_type, val_len, bit_width_hint, len_mode);
        return decode_logic_enum_bits(value, val_type, bit_width, bits);
    }
    return decode_integral_enum_bits(value, val_type, val_len, bit_width_hint, len_mode, bits);
}

uint32_t enum_ordinal_bit_width(uint_T literal_count) {
    if (literal_count <= 1) {
        return 1;
    }
    uint_T largest_ordinal = literal_count - 1;
    uint32_t width = 0;
    while (largest_ordinal != 0) {
        ++width;
        largest_ordinal >>= 1;
    }
    return width;
}

std::string ordinal_enum_bits(uint_T ordinal, uint32_t bit_width) {
    std::string bits(static_cast<std::size_t>(bit_width), '0');
    for (uint32_t bit_index = 0; bit_index < bit_width; ++bit_index) {
        const uint32_t shift = bit_width - bit_index - 1;
        bits[bit_index] = ((ordinal >> shift) & 1u) != 0 ? '1' : '0';
    }
    return bits;
}

void copy_ordinal_enum_labels(
    uint_T literal_count,
    char **literal_arr,
    uint32_t bit_width,
    std::vector<std::string> *label_bits,
    std::vector<wp_fsdb_enum_label_record> *labels
) {
    if (literal_count == 0 || literal_arr == nullptr || label_bits == nullptr || labels == nullptr) {
        return;
    }

    label_bits->reserve(literal_count);
    labels->reserve(literal_count);
    for (uint_T index = 0; index < literal_count; ++index) {
        if (literal_arr[index] == nullptr) {
            continue;
        }
        label_bits->push_back(ordinal_enum_bits(index, bit_width));
        wp_fsdb_enum_label_record label{};
        label.name = literal_arr[index];
        label.bits = label_bits->back().c_str();
        labels->push_back(label);
    }
}

void copy_enum_labels(
    uint_T literal_count,
    char **literal_arr,
    byte_T **val_arr,
    byte_T val_type,
    uint_T val_len,
    uint32_t bit_width_hint,
    enum_value_len_mode len_mode,
    std::vector<std::string> *label_bits,
    std::vector<wp_fsdb_enum_label_record> *labels
) {
    if (literal_count == 0 || literal_arr == nullptr || val_arr == nullptr ||
        label_bits == nullptr || labels == nullptr) {
        return;
    }

    label_bits->reserve(literal_count);
    labels->reserve(literal_count);
    for (uint_T index = 0; index < literal_count; ++index) {
        if (literal_arr[index] == nullptr || val_arr[index] == nullptr) {
            continue;
        }
        std::string decoded_bits;
        if (!decode_enum_value_bits(
                val_arr[index],
                val_type,
                val_len,
                bit_width_hint,
                len_mode,
                &decoded_bits
            )) {
            continue;
        }
        label_bits->push_back(std::move(decoded_bits));
        wp_fsdb_enum_label_record label{};
        label.name = literal_arr[index];
        label.bits = label_bits->back().c_str();
        labels->push_back(label);
    }
}

bool populate_datatype_record(
    fsdbTreeCBType type,
    void *tree_cb_data,
    wp_fsdb_datatype_record *out,
    std::vector<std::string> *label_bits,
    std::vector<wp_fsdb_enum_label_record> *labels
) {
    if (out == nullptr || tree_cb_data == nullptr) {
        return false;
    }

    *out = wp_fsdb_datatype_record{};
    const auto kind = map_datatype_kind(type);
    out->kind = static_cast<uint32_t>(kind);
    bool is_signed = false;
    if (datatype_kind_signedness(kind, &is_signed)) {
        set_record_signedness(out, is_signed);
    }
    set_record_bit_width(out, datatype_default_bit_width(kind));

    switch (type) {
    case FSDB_TREE_CBT_DT_ENUM: {
        auto *record = static_cast<fsdbTreeCBDataEnum *>(tree_cb_data);
        out->idcode = static_cast<uint32_t>(record->idcode);
        const uint32_t bit_width = enum_ordinal_bit_width(record->numLiteral);
        set_record_bit_width(out, bit_width);
        copy_ordinal_enum_labels(
            record->numLiteral,
            record->arrLiteral,
            bit_width,
            label_bits,
            labels
        );
        break;
    }
    case FSDB_TREE_CBT_DT_ENUM2: {
        auto *record = static_cast<fsdbTreeCBDataEnum2 *>(tree_cb_data);
        out->idcode = static_cast<uint32_t>(record->idcode);
        out->name = record->name;
        const uint32_t bit_width = enum_value_bit_width(
            record->val_type,
            record->val_len,
            0,
            enum_value_len_mode::byte_count
        );
        set_record_bit_width(out, bit_width);
        if (enum_value_type_signedness(record->val_type, &is_signed)) {
            set_record_signedness(out, is_signed);
        }
        copy_enum_labels(
            record->literal_count,
            record->literal_arr,
            record->val_arr,
            record->val_type,
            record->val_len,
            bit_width,
            enum_value_len_mode::byte_count,
            label_bits,
            labels
        );
        break;
    }
    case FSDB_TREE_CBT_DT_ENUM3: {
        auto *record = static_cast<fsdbTreeCBDataEnum3 *>(tree_cb_data);
        out->idcode = static_cast<uint32_t>(record->idcode);
        out->name = record->name;
        const uint32_t bit_width = bit_width_from_bounds(record->lbitnum, record->rbitnum);
        set_record_bit_width(out, bit_width);
        if (enum_value_type_signedness(record->val_type, &is_signed)) {
            set_record_signedness(out, is_signed);
        }
        copy_enum_labels(
            record->literal_count,
            record->literal_arr,
            record->val_arr,
            record->val_type,
            record->val_len,
            bit_width,
            enum_value_len_mode::bit_width,
            label_bits,
            labels
        );
        break;
    }
    case FSDB_TREE_CBT_DT_INT: {
        auto *record = static_cast<fsdbTreeCBDataInt *>(tree_cb_data);
        out->idcode = static_cast<uint32_t>(record->idcode);
        return true;
    }
    case FSDB_TREE_CBT_DT_INT_H_N_L: {
        auto *record = static_cast<fsdbTreeCBDataIntHnL *>(tree_cb_data);
        out->idcode = static_cast<uint32_t>(record->idcode);
        return true;
    }
    case FSDB_TREE_CBT_DT_FLOAT: {
        auto *record = static_cast<fsdbTreeCBDataFloating *>(tree_cb_data);
        out->idcode = static_cast<uint32_t>(record->idcode);
        return true;
    }
    case FSDB_TREE_CBT_DT_ATTR_ENUM: {
        auto *record = static_cast<fsdbTreeCBDataEnumAttr *>(tree_cb_data);
        out->idcode = static_cast<uint32_t>(record->idcode);
        out->name = record->name;
        const uint32_t bit_width = enum_value_bit_width(
            record->val_type,
            record->val_len,
            0,
            enum_value_len_mode::byte_count
        );
        set_record_bit_width(out, bit_width);
        if (enum_attr_signedness(record->val_type, record->radix, &is_signed)) {
            set_record_signedness(out, is_signed);
        }
        copy_enum_labels(
            record->literal_count,
            record->literal_arr,
            record->val_arr,
            record->val_type,
            record->val_len,
            bit_width,
            enum_value_len_mode::byte_count,
            label_bits,
            labels
        );
        break;
    }
    case FSDB_TREE_CBT_DT_ATTR_SV_ENUM: {
        auto *record = static_cast<fsdbTreeCBDataSVEnumAttr *>(tree_cb_data);
        out->idcode = static_cast<uint32_t>(record->idcode);
        out->name = record->name;
        const uint32_t bit_width = bit_width_from_bounds(record->lbitnum, record->rbitnum);
        set_record_bit_width(out, bit_width);
        if (enum_attr_signedness(record->val_type, record->radix, &is_signed)) {
            set_record_signedness(out, is_signed);
        }
        copy_enum_labels(
            record->literal_count,
            record->literal_arr,
            record->val_arr,
            record->val_type,
            record->val_len,
            bit_width,
            enum_value_len_mode::bit_width,
            label_bits,
            labels
        );
        break;
    }
    case FSDB_TREE_CBT_DT_ATTR_LOGIC:
    case FSDB_TREE_CBT_DT_ATTR_BOOL:
    case FSDB_TREE_CBT_DT_ATTR_STRING:
    case FSDB_TREE_CBT_DT_ATTR_INT32:
    case FSDB_TREE_CBT_DT_ATTR_INT64:
    case FSDB_TREE_CBT_DT_ATTR_UINT32:
    case FSDB_TREE_CBT_DT_ATTR_UINT64:
    case FSDB_TREE_CBT_DT_ATTR_FLOAT:
    case FSDB_TREE_CBT_DT_ATTR_DOUBLE:
    case FSDB_TREE_CBT_DT_ATTR_EVENT:
    case FSDB_TREE_CBT_DT_ATTR_SV_LOGIC:
    case FSDB_TREE_CBT_DT_ATTR_SV_REG:
    case FSDB_TREE_CBT_DT_ATTR_SV_BIT:
    case FSDB_TREE_CBT_DT_ATTR_SV_LONG_INT:
    case FSDB_TREE_CBT_DT_ATTR_SV_LONG_UINT:
    case FSDB_TREE_CBT_DT_ATTR_SV_INT:
    case FSDB_TREE_CBT_DT_ATTR_SV_UINT:
    case FSDB_TREE_CBT_DT_ATTR_SV_INTEGER:
    case FSDB_TREE_CBT_DT_ATTR_SV_UINTEGER:
    case FSDB_TREE_CBT_DT_ATTR_SV_SHORT_INT:
    case FSDB_TREE_CBT_DT_ATTR_SV_SHORT_UINT:
    case FSDB_TREE_CBT_DT_ATTR_SV_BYTE_INT:
    case FSDB_TREE_CBT_DT_ATTR_SV_BYTE_UINT:
    case FSDB_TREE_CBT_DT_ATTR_SV_REAL:
    case FSDB_TREE_CBT_DT_ATTR_SV_SHORT_REAL:
    case FSDB_TREE_CBT_DT_ATTR_SV_TIME:
    case FSDB_TREE_CBT_DT_ATTR_SV_STRING:
    case FSDB_TREE_CBT_DT_ATTR_SV_EVENT:
    case FSDB_TREE_CBT_DT_ATTR_RAW_STRING: {
        auto *record = static_cast<fsdbTreeCBDataAttr *>(tree_cb_data);
        out->idcode = static_cast<uint32_t>(record->idcode);
        out->name = record->name;
        if (datatype_kind_uses_radix_signedness(kind) &&
            attr_radix_signedness(record->radix, &is_signed)) {
            set_record_signedness(out, is_signed);
        }
        return true;
    }
    default:
        return false;
    }

    if (labels != nullptr && !labels->empty()) {
        out->enum_label_count = labels->size();
        out->enum_labels = labels->data();
    }
    return true;
}

struct tree_callback_context {
    wp_fsdb_tree_callback callback;
    void *user;
    bool aborted;
    std::size_t datatype_callbacks;
};

bool_T emit_tree_event(
    tree_callback_context *context,
    wp_fsdb_tree_event event,
    const wp_fsdb_scope_record *scope,
    const wp_fsdb_signal_record *signal,
    const wp_fsdb_datatype_record *datatype
) {
    if (context == nullptr || context->callback == nullptr) {
        return static_cast<bool_T>(1);
    }
    const int rc = context->callback(
        static_cast<uint32_t>(event),
        scope,
        signal,
        datatype,
        context->user
    );
    if (rc != 0) {
        context->aborted = true;
        return static_cast<bool_T>(0);
    }
    return static_cast<bool_T>(1);
}

bool_T datatype_tree_callback(fsdbTreeCBType cb_type, void *client_data, void *tree_cb_data) {
    auto *context = static_cast<tree_callback_context *>(client_data);
    if (context != nullptr) {
        ++context->datatype_callbacks;
    }

    std::vector<std::string> label_bits;
    std::vector<wp_fsdb_enum_label_record> labels;
    wp_fsdb_datatype_record record{};
    if (!populate_datatype_record(cb_type, tree_cb_data, &record, &label_bits, &labels)) {
        return static_cast<bool_T>(1);
    }

    return emit_tree_event(context, WP_FSDB_TREE_EVENT_DATATYPE, nullptr, nullptr, &record);
}

wp_fsdb_status read_datatype_definitions(
    ffrObject *object,
    tree_callback_context *context,
    char **error_message
) {
    if (object == nullptr || context == nullptr) {
        return fail(error_message, "FSDB Reader: datatype traversal received a null argument");
    }
    if (!object->ffrHasDataTypeDef()) {
        return WP_FSDB_STATUS_OK;
    }

    uint_T next_block_index = 0;
    while (true) {
        const uint_T requested_block_index = next_block_index;
        const std::size_t callbacks_before = context->datatype_callbacks;
        uint_T last_block_index = requested_block_index;
        if (object->ffrReadDataTypeDefByBlkIdx2(
                datatype_tree_callback,
                context,
                last_block_index
            ) != FSDB_RC_SUCCESS) {
            if (context->aborted) {
                return fail(error_message, "FSDB Reader: hierarchy traversal aborted by callback");
            }
            return fail(error_message, "FSDB Reader: failed to read FSDB datatype definitions");
        }
        if (context->aborted) {
            return fail(error_message, "FSDB Reader: hierarchy traversal aborted by callback");
        }
        if (context->datatype_callbacks == callbacks_before) {
            return WP_FSDB_STATUS_OK;
        }
        if (last_block_index < requested_block_index) {
            return fail(
                error_message,
                "FSDB Reader: datatype traversal returned a lower block index"
            );
        }
        // The Reader reports the greatest datatype block traversed. If one
        // call advanced beyond the requested block, it covered the intervening
        // blocks too; otherwise advance explicitly instead of rereading block 0.
        if (last_block_index > requested_block_index) {
            return WP_FSDB_STATUS_OK;
        }
        if (next_block_index == std::numeric_limits<uint_T>::max()) {
            return fail(error_message, "FSDB Reader: datatype block index overflow");
        }
        next_block_index += 1;
    }
}

bool_T scope_var_tree_callback(fsdbTreeCBType cb_type, void *client_data, void *tree_cb_data) {
    auto *context = static_cast<tree_callback_context *>(client_data);
    switch (cb_type) {
    case FSDB_TREE_CBT_BEGIN_TREE:
        return emit_tree_event(context, WP_FSDB_TREE_EVENT_BEGIN_TREE, nullptr, nullptr, nullptr);
    case FSDB_TREE_CBT_SCOPE:
    case FSDB_TREE_CBT_EVENT_SCOPE:
    case FSDB_TREE_CBT_MDF_SCOPE: {
        auto *scope = static_cast<fsdbTreeCBDataScope *>(tree_cb_data);
        wp_fsdb_scope_record record{};
        record.name = scope == nullptr ? nullptr : scope->name;
        record.kind = static_cast<uint32_t>(scope == nullptr ? WP_FSDB_SCOPE_KIND_UNKNOWN : map_scope_kind(scope->type));
        record.hidden = scope != nullptr && scope->is_hidden_scope ? 1 : 0;
        return emit_tree_event(context, WP_FSDB_TREE_EVENT_SCOPE, &record, nullptr, nullptr);
    }
    case FSDB_TREE_CBT_VAR:
    case FSDB_TREE_CBT_SV_VAR:
    case FSDB_TREE_CBT_ENUM_VAR:
    case FSDB_TREE_CBT_EVENT_VAR:
    case FSDB_TREE_CBT_MDF_VAR:
    case FSDB_TREE_CBT_PACKED_VAR:
    case FSDB_TREE_CBT_PACKED_COMP_VAR: {
        auto *var = static_cast<fsdbTreeCBDataVar *>(tree_cb_data);
        wp_fsdb_signal_record record{};
        record.name = var == nullptr ? nullptr : var->name;
        record.idcode = var == nullptr ? 0 : static_cast<uint64_t>(var->u.idcode);
        record.has_bit_range = var != nullptr && var->lbitnum >= 0 && var->rbitnum >= 0 ? 1 : 0;
        record.left = var == nullptr ? 0 : static_cast<int32_t>(var->lbitnum);
        record.right = var == nullptr ? 0 : static_cast<int32_t>(var->rbitnum);
        record.has_datatype_id = var != nullptr && var->dtidcode != 0 ? 1 : 0;
        record.datatype_id = var == nullptr ? 0 : static_cast<uint32_t>(var->dtidcode);
        const wp_fsdb_signal_kind signal_kind = var == nullptr ? WP_FSDB_SIGNAL_KIND_UNKNOWN : map_signal_kind(var->type);
        record.kind = static_cast<uint32_t>(signal_kind);
        record.packed_component = cb_type == FSDB_TREE_CBT_PACKED_COMP_VAR ? 1 : 0;
        record.value_encoding = static_cast<uint32_t>(classify_value_encoding(var, signal_kind));
        return emit_tree_event(context, WP_FSDB_TREE_EVENT_SIGNAL, nullptr, &record, nullptr);
    }
    case FSDB_TREE_CBT_UPSCOPE:
    case FSDB_TREE_CBT_EVENT_UPSCOPE:
        return emit_tree_event(context, WP_FSDB_TREE_EVENT_UPSCOPE, nullptr, nullptr, nullptr);
    case FSDB_TREE_CBT_END_TREE:
    case FSDB_TREE_CBT_END_EVENT_TREE:
        return emit_tree_event(context, WP_FSDB_TREE_EVENT_END_TREE, nullptr, nullptr, nullptr);
    case FSDB_TREE_CBT_END_ALL_TREE:
        return emit_tree_event(context, WP_FSDB_TREE_EVENT_END_ALL_TREE, nullptr, nullptr, nullptr);
    default:
        return static_cast<bool_T>(1);
    }
}

void free_sample_records(wp_fsdb_sample_record *samples, std::size_t count) {
    if (samples == nullptr) {
        return;
    }
    for (std::size_t index = 0; index < count; ++index) {
        std::free(samples[index].bits);
        samples[index].bits = nullptr;
    }
    std::free(samples);
}

struct sample_records_deleter {
    std::size_t count = 0;

    void operator()(wp_fsdb_sample_record *samples) const {
        free_sample_records(samples, count);
    }
};

using owned_sample_records = std::unique_ptr<wp_fsdb_sample_record, sample_records_deleter>;

class signal_list_guard {
  public:
    explicit signal_list_guard(ffrObject *object) : object_(object) {}

    signal_list_guard(const signal_list_guard &) = delete;
    signal_list_guard &operator=(const signal_list_guard &) = delete;

    ~signal_list_guard() {
        if (object_ == nullptr) {
            return;
        }
        if (loaded_) {
            object_->ffrUnloadSignals();
        }
        if (reset_) {
            object_->ffrResetSignalList();
        }
    }

    wp_fsdb_status load(const uint64_t *idcodes, std::size_t count, char **error_message) {
        if (object_->ffrResetSignalList() != FSDB_RC_SUCCESS) {
            return fail(error_message, "FSDB Reader: failed to reset signal list before sampling");
        }
        reset_ = true;

        std::unordered_set<fsdbVarIdcode> loaded_idcodes;
        loaded_idcodes.reserve(count);
        for (std::size_t index = 0; index < count; ++index) {
            const fsdbVarIdcode idcode = static_cast<fsdbVarIdcode>(idcodes[index]);
            if (!loaded_idcodes.insert(idcode).second) {
                continue;
            }
            if (object_->ffrAddToSignalList(idcode) != FSDB_RC_SUCCESS) {
                return fail(error_message, "FSDB Reader: failed to add signal to sample list");
            }
        }

        if (object_->ffrLoadSignals() != FSDB_RC_SUCCESS) {
            return fail(error_message, "FSDB Reader: failed to load signal values");
        }
        loaded_ = true;
        return WP_FSDB_STATUS_OK;
    }

  private:
    ffrObject *object_ = nullptr;
    bool reset_ = false;
    bool loaded_ = false;
};

class vc_handle_guard {
  public:
    explicit vc_handle_guard(ffrVCTrvsHdl handle) : handle_(handle) {}

    vc_handle_guard(const vc_handle_guard &) = delete;
    vc_handle_guard &operator=(const vc_handle_guard &) = delete;

    ~vc_handle_guard() {
        if (handle_ != nullptr) {
            handle_->ffrFree();
        }
    }

    ffrVCTrvsHdl get() const {
        return handle_;
    }

    ffrVCTrvsHdl release() {
        ffrVCTrvsHdl handle = handle_;
        handle_ = nullptr;
        return handle;
    }

  private:
    ffrVCTrvsHdl handle_ = nullptr;
};

bool bit_value_to_char(byte_T value, char *out) {
    if (out == nullptr) {
        return false;
    }
    switch (value) {
    case FSDB_BT_VCD_0:
        *out = '0';
        return true;
    case FSDB_BT_VCD_1:
        *out = '1';
        return true;
    case FSDB_BT_VCD_X:
        *out = 'x';
        return true;
    case FSDB_BT_VCD_Z:
        *out = 'z';
        return true;
    default:
        return false;
    }
}

struct vc_position {
    uint64_t time_raw = 0;
    fsdbSeqNum seq_num = FSDB_EMPTY_SEQ_NUM;
};

struct sampled_bit_vector {
    bool has_value = false;
    uint64_t time_raw = 0;
    fsdbSeqNum seq_num = FSDB_EMPTY_SEQ_NUM;
    std::string bits;
};

wp_fsdb_status read_current_vc_position(
    ffrVCTrvsHdl handle,
    vc_position *position,
    char **error_message
) {
    if (handle == nullptr || position == nullptr) {
        return fail(error_message, "FSDB Reader: value-change position read received a null argument");
    }

    fsdbTag64 tag{};
    if (handle->ffrGetXTag(static_cast<void *>(&tag)) != FSDB_RC_SUCCESS) {
        return fail(error_message, "FSDB Reader: failed to read value-change time tag");
    }

    fsdbSeqNum seq_num = FSDB_EMPTY_SEQ_NUM;
    if (handle->ffrGetSeqNum(&seq_num) != FSDB_RC_SUCCESS) {
        seq_num = FSDB_EMPTY_SEQ_NUM;
    }

    position->time_raw = tag64_to_u64(tag);
    position->seq_num = seq_num;
    return WP_FSDB_STATUS_OK;
}

wp_fsdb_status decode_current_vc_bits(
    ffrVCTrvsHdl handle,
    uint_T bit_width,
    std::string *bits,
    char **error_message
) {
    if (handle == nullptr || bits == nullptr) {
        return fail(error_message, "FSDB Reader: value-change decode received a null argument");
    }

    byte_T *value_change = nullptr;
    if (handle->ffrGetVC(&value_change) != FSDB_RC_SUCCESS || value_change == nullptr) {
        return fail(error_message, "FSDB Reader: failed to read value-change data");
    }

    bits->assign(static_cast<std::size_t>(bit_width), '\0');
    for (uint_T bit_index = 0; bit_index < bit_width; ++bit_index) {
        if (!bit_value_to_char(value_change[bit_index], &(*bits)[bit_index])) {
            return fail(error_message, "FSDB Reader: signal has unsupported bit value encoding");
        }
    }
    return WP_FSDB_STATUS_OK;
}

wp_fsdb_status capture_current_bit_vector_sample(
    ffrVCTrvsHdl handle,
    uint_T bit_width,
    const vc_position &position,
    sampled_bit_vector *sample,
    char **error_message
) {
    if (sample == nullptr) {
        return fail(error_message, "FSDB Reader: sample capture received a null output");
    }

    std::string bits;
    if (decode_current_vc_bits(handle, bit_width, &bits, error_message) != WP_FSDB_STATUS_OK) {
        return WP_FSDB_STATUS_ERROR;
    }

    sample->has_value = true;
    sample->time_raw = position.time_raw;
    sample->seq_num = position.seq_num;
    sample->bits.swap(bits);
    return WP_FSDB_STATUS_OK;
}

bool position_is_not_before_selected(
    const vc_position &candidate,
    const sampled_bit_vector &selected
) {
    if (!selected.has_value) {
        return true;
    }
    if (candidate.time_raw != selected.time_raw) {
        return candidate.time_raw > selected.time_raw;
    }
    if (candidate.seq_num != FSDB_EMPTY_SEQ_NUM && selected.seq_num != FSDB_EMPTY_SEQ_NUM) {
        return candidate.seq_num >= selected.seq_num;
    }
    return true;
}

wp_fsdb_status read_final_sample_at_or_before(
    ffrVCTrvsHdl handle,
    uint64_t query_time_raw,
    uint_T bit_width,
    sampled_bit_vector *sample,
    char **error_message
) {
    if (handle == nullptr || sample == nullptr) {
        return fail(error_message, "FSDB Reader: final sample read received a null argument");
    }

    sample->has_value = false;
    sample->bits.clear();

    if (!handle->ffrHasIncoreVC()) {
        return WP_FSDB_STATUS_OK;
    }

    fsdbTag64 aligned_tag = u64_to_tag64(query_time_raw);
    int glitch_num = 0;
    if (handle->ffrGotoXTag(static_cast<void *>(&aligned_tag), &glitch_num) != FSDB_RC_SUCCESS) {
        return WP_FSDB_STATUS_OK;
    }

    vc_position position;
    if (read_current_vc_position(handle, &position, error_message) != WP_FSDB_STATUS_OK) {
        return WP_FSDB_STATUS_ERROR;
    }
    if (position.time_raw > query_time_raw) {
        return WP_FSDB_STATUS_OK;
    }

    // Ask the Reader to expose glitch metadata, then drain only records at the
    // aligned timestamp. Some dumps surface equal-time updates as separate
    // positions; sequence numbers break ties when present, and traversal order
    // is the fallback for older files. Stop as soon as time advances so normal
    // sampling stays one-position work after ffrGotoXTag().
    const uint64_t aligned_time_raw = position.time_raw;
    sampled_bit_vector selected;
    while (position.time_raw == aligned_time_raw) {
        if (position_is_not_before_selected(position, selected)) {
            sampled_bit_vector candidate;
            if (capture_current_bit_vector_sample(
                    handle,
                    bit_width,
                    position,
                    &candidate,
                    error_message
                ) != WP_FSDB_STATUS_OK) {
                return WP_FSDB_STATUS_ERROR;
            }
            selected = std::move(candidate);
        }

        if (handle->ffrGotoNextVC() != FSDB_RC_SUCCESS) {
            break;
        }
        if (read_current_vc_position(handle, &position, error_message) != WP_FSDB_STATUS_OK) {
            return WP_FSDB_STATUS_ERROR;
        }
    }

    if (selected.has_value) {
        *sample = std::move(selected);
    }
    return WP_FSDB_STATUS_OK;
}

wp_fsdb_status fill_sample_record_from_handle(
    ffrVCTrvsHdl handle,
    uint64_t idcode,
    uint64_t query_time_raw,
    wp_fsdb_sample_record *record,
    char **error_message
) {
    if (handle == nullptr || record == nullptr) {
        return fail(error_message, "FSDB Reader: sample fill received a null argument");
    }

    record->idcode = idcode;
    record->has_value = 0;
    record->bit_width = 0;
    record->value_time_raw = 0;
    record->bits = nullptr;

    const uint_T bit_width = handle->ffrGetBitSize();
    if (bit_width == 0) {
        return fail(error_message, "FSDB Reader: signal has unsupported zero-width value encoding");
    }
    record->bit_width = static_cast<uint32_t>(bit_width);

    if (handle->ffrGetBytesPerBit() != FSDB_BYTES_PER_BIT_1B) {
        return fail(error_message, "FSDB Reader: signal has unsupported non-bit-vector encoding");
    }

    sampled_bit_vector sample;
    if (read_final_sample_at_or_before(
            handle,
            query_time_raw,
            bit_width,
            &sample,
            error_message
        ) != WP_FSDB_STATUS_OK) {
        return WP_FSDB_STATUS_ERROR;
    }
    if (!sample.has_value) {
        return WP_FSDB_STATUS_OK;
    }

    char *bits = static_cast<char *>(std::malloc(sample.bits.size() + 1));
    if (bits == nullptr) {
        return fail(error_message, "FSDB Reader: failed to allocate sampled bit string");
    }
    std::memcpy(bits, sample.bits.data(), sample.bits.size());
    bits[sample.bits.size()] = '\0';

    record->has_value = 1;
    record->value_time_raw = sample.time_raw;
    record->bits = bits;
    return WP_FSDB_STATUS_OK;
}

wp_fsdb_status fill_sample_record(
    ffrObject *object,
    uint64_t idcode,
    uint64_t query_time_raw,
    wp_fsdb_sample_record *record,
    char **error_message
) {
    if (object == nullptr) {
        return fail(error_message, "FSDB Reader: sample fill received a null reader");
    }
    vc_handle_guard handle(object->ffrCreateVCTrvsHdl(static_cast<fsdbVarIdcode>(idcode)));
    if (handle.get() == nullptr) {
        return fail(error_message, "FSDB Reader: failed to create value-change traverse handle");
    }
    return fill_sample_record_from_handle(
        handle.get(),
        idcode,
        query_time_raw,
        record,
        error_message
    );
}

wp_fsdb_status append_change_times_for_handle(
    ffrVCTrvsHdl handle,
    uint64_t from_raw,
    uint64_t to_raw,
    std::vector<uint64_t> &times,
    std::unordered_set<uint64_t> &seen_times,
    char **error_message
) {
    if (handle == nullptr) {
        return fail(error_message, "FSDB Reader: change-time traversal received a null handle");
    }

    if (!handle->ffrHasIncoreVC()) {
        return WP_FSDB_STATUS_OK;
    }

    fsdbTag64 tag = u64_to_tag64(from_raw);
    if (handle->ffrGotoXTag(static_cast<void *>(&tag)) != FSDB_RC_SUCCESS) {
        if (handle->ffrGetMinXTag(static_cast<void *>(&tag)) != FSDB_RC_SUCCESS) {
            return WP_FSDB_STATUS_OK;
        }
    }

    uint64_t current = tag64_to_u64(tag);
    if (current < from_raw) {
        if (handle->ffrGotoNextVC() != FSDB_RC_SUCCESS) {
            return WP_FSDB_STATUS_OK;
        }
        if (handle->ffrGetXTag(static_cast<void *>(&tag)) != FSDB_RC_SUCCESS) {
            return fail(error_message, "FSDB Reader: failed to read value-change time tag");
        }
        current = tag64_to_u64(tag);
    }

    while (current <= to_raw) {
        if (seen_times.insert(current).second) {
            times.push_back(current);
        }
        if (handle->ffrGotoNextVC() != FSDB_RC_SUCCESS) {
            break;
        }
        if (handle->ffrGetXTag(static_cast<void *>(&tag)) != FSDB_RC_SUCCESS) {
            return fail(error_message, "FSDB Reader: failed to read next value-change time tag");
        }
        current = tag64_to_u64(tag);
    }

    return WP_FSDB_STATUS_OK;
}

wp_fsdb_status append_change_times_for_signal(
    ffrObject *object,
    uint64_t idcode,
    uint64_t from_raw,
    uint64_t to_raw,
    std::vector<uint64_t> &times,
    std::unordered_set<uint64_t> &seen_times,
    char **error_message
) {
    vc_handle_guard handle(object->ffrCreateVCTrvsHdl(static_cast<fsdbVarIdcode>(idcode)));
    if (handle.get() == nullptr) {
        return fail(error_message, "FSDB Reader: failed to create value-change traverse handle");
    }

    return append_change_times_for_handle(
        handle.get(),
        from_raw,
        to_raw,
        times,
        seen_times,
        error_message
    );
}

wp_fsdb_status copy_sorted_unique_times(
    std::vector<uint64_t> &times,
    wp_fsdb_time_list *out,
    char **error_message
) {
    std::sort(times.begin(), times.end());
    times.erase(std::unique(times.begin(), times.end()), times.end());

    out->times = nullptr;
    out->count = times.size();
    if (times.empty()) {
        return WP_FSDB_STATUS_OK;
    }

    out->times = static_cast<uint64_t *>(std::malloc(times.size() * sizeof(uint64_t)));
    if (out->times == nullptr) {
        out->count = 0;
        return fail(error_message, "FSDB Reader: failed to allocate candidate time list");
    }

    std::copy(times.begin(), times.end(), out->times);
    return WP_FSDB_STATUS_OK;
}

wp_fsdb_status read_exact_event_occurrence_from_handle(
    ffrVCTrvsHdl handle,
    uint64_t query_time_raw,
    bool &occurred,
    char **error_message
) {
    occurred = false;
    if (handle == nullptr) {
        return fail(error_message, "FSDB Reader: event traversal received a null handle");
    }

    if (!handle->ffrHasIncoreVC()) {
        return WP_FSDB_STATUS_OK;
    }

    fsdbTag64 tag = u64_to_tag64(query_time_raw);
    if (handle->ffrGotoXTag(static_cast<void *>(&tag)) != FSDB_RC_SUCCESS) {
        return WP_FSDB_STATUS_OK;
    }
    occurred = tag64_to_u64(tag) == query_time_raw;
    return WP_FSDB_STATUS_OK;
}

wp_fsdb_status read_exact_event_occurrence(
    ffrObject *object,
    uint64_t idcode,
    uint64_t query_time_raw,
    bool &occurred,
    char **error_message
) {
    vc_handle_guard handle(object->ffrCreateVCTrvsHdl(static_cast<fsdbVarIdcode>(idcode)));
    if (handle.get() == nullptr) {
        return fail(error_message, "FSDB Reader: failed to create value-change traverse handle");
    }

    return read_exact_event_occurrence_from_handle(
        handle.get(),
        query_time_raw,
        occurred,
        error_message
    );
}

constexpr std::size_t MAX_CACHED_TRAVERSE_HANDLES = 64;

struct cached_vc_handle {
    explicit cached_vc_handle(ffrVCTrvsHdl raw_handle) : handle(raw_handle) {}

    cached_vc_handle(const cached_vc_handle &) = delete;
    cached_vc_handle &operator=(const cached_vc_handle &) = delete;

    ~cached_vc_handle() {
        if (handle != nullptr) {
            handle->ffrFree();
            handle = nullptr;
        }
    }

    ffrVCTrvsHdl handle = nullptr;
    uint64_t last_used = 0;
};

}  // namespace

struct wp_fsdb_signal_session {
    explicit wp_fsdb_signal_session(wp_fsdb_reader *owner)
        : reader(owner), object(owner == nullptr ? nullptr : owner->object) {}

    wp_fsdb_signal_session(const wp_fsdb_signal_session &) = delete;
    wp_fsdb_signal_session &operator=(const wp_fsdb_signal_session &) = delete;

    ~wp_fsdb_signal_session() {
        close_noexcept();
    }

    wp_fsdb_status load(const uint64_t *idcodes, std::size_t count, char **error_message) {
        if (object == nullptr) {
            return fail(error_message, "FSDB Reader: signal session received a null reader");
        }
        if (object->ffrResetSignalList() != FSDB_RC_SUCCESS) {
            return fail(error_message, "FSDB Reader: failed to reset signal list for signal session");
        }
        reset = true;

        loaded_idcodes.reserve(count);
        for (std::size_t index = 0; index < count; ++index) {
            const fsdbVarIdcode idcode = static_cast<fsdbVarIdcode>(idcodes[index]);
            if (!loaded_idcodes.insert(idcode).second) {
                continue;
            }
            if (object->ffrAddToSignalList(idcode) != FSDB_RC_SUCCESS) {
                return fail(error_message, "FSDB Reader: failed to add signal to session list");
            }
        }

        if (!loaded_idcodes.empty()) {
            if (object->ffrLoadSignals() != FSDB_RC_SUCCESS) {
                return fail(error_message, "FSDB Reader: failed to load signal session values");
            }
            loaded = true;
        }
        return WP_FSDB_STATUS_OK;
    }

    bool has_idcode(uint64_t raw_idcode) const {
        return loaded_idcodes.find(static_cast<fsdbVarIdcode>(raw_idcode)) !=
               loaded_idcodes.end();
    }

    wp_fsdb_status require_open(char **error_message) const {
        if (object != nullptr) {
            return WP_FSDB_STATUS_OK;
        }
        return fail(error_message, "FSDB Reader: signal session is closed");
    }

    wp_fsdb_status require_idcode(uint64_t raw_idcode, char **error_message) const {
        if (has_idcode(raw_idcode)) {
            return WP_FSDB_STATUS_OK;
        }
        return fail(
            error_message,
            "FSDB Reader: idcode " + std::to_string(raw_idcode) +
                " is not loaded in the FSDB signal session"
        );
    }

    wp_fsdb_status cached_handle_for(
        uint64_t raw_idcode,
        ffrVCTrvsHdl *out,
        char **error_message
    ) {
        if (out == nullptr) {
            return fail(error_message, "FSDB Reader: cached traversal requested a null output");
        }
        *out = nullptr;
        if (require_open(error_message) != WP_FSDB_STATUS_OK) {
            return WP_FSDB_STATUS_ERROR;
        }
        if (require_idcode(raw_idcode, error_message) != WP_FSDB_STATUS_OK) {
            return WP_FSDB_STATUS_ERROR;
        }

        const fsdbVarIdcode idcode = static_cast<fsdbVarIdcode>(raw_idcode);
        const uint64_t use = ++use_counter;
        auto found = cached_handles.find(idcode);
        if (found != cached_handles.end()) {
            found->second->last_used = use;
            *out = found->second->handle;
            return WP_FSDB_STATUS_OK;
        }

        if (cached_handles.size() >= MAX_CACHED_TRAVERSE_HANDLES && !cached_handles.empty()) {
            auto evict = cached_handles.begin();
            for (auto iter = cached_handles.begin(); iter != cached_handles.end(); ++iter) {
                if (iter->second->last_used < evict->second->last_used) {
                    evict = iter;
                }
            }
            cached_handles.erase(evict);
        }

        vc_handle_guard handle(object->ffrCreateVCTrvsHdl(idcode));
        if (handle.get() == nullptr) {
            return fail(error_message, "FSDB Reader: failed to create value-change traverse handle");
        }

        auto cached = std::make_unique<cached_vc_handle>(handle.get());
        handle.release();
        cached->last_used = use;
        auto inserted = cached_handles.emplace(idcode, std::move(cached));
        *out = inserted.first->second->handle;
        return WP_FSDB_STATUS_OK;
    }

    void close_noexcept() noexcept {
        try {
            cached_handles.clear();
            if (object != nullptr) {
                if (loaded) {
                    object->ffrUnloadSignals();
                    loaded = false;
                }
                if (reset) {
                    object->ffrResetSignalList();
                    reset = false;
                }
            }
            loaded_idcodes.clear();
            if (reader != nullptr && reader->active_signal_session == this) {
                reader->active_signal_session = nullptr;
            }
            reader = nullptr;
            object = nullptr;
        } catch (...) {
            // Native close paths are best-effort; C ABI close cannot return errors.
        }
    }

    wp_fsdb_reader *reader = nullptr;
    ffrObject *object = nullptr;
    bool reset = false;
    bool loaded = false;
    uint64_t use_counter = 0;
    std::unordered_set<fsdbVarIdcode> loaded_idcodes;
    std::unordered_map<fsdbVarIdcode, std::unique_ptr<cached_vc_handle>> cached_handles;
};

extern "C" wp_fsdb_status wp_fsdb_probe(
    const char *path,
    int *is_fsdb,
    char **error_message
) {
    clear_error(error_message);
    if (path == nullptr || is_fsdb == nullptr) {
        return fail(error_message, "FSDB Reader: probe received a null argument");
    }

    try {
        std::lock_guard<std::recursive_mutex> lock(reader_mutex());
        scoped_output_suppressor output_suppressor;
        suppress_reader_messages();
        *is_fsdb = ffrObject::ffrIsFSDB(const_cast<char *>(path)) ? 1 : 0;
        return WP_FSDB_STATUS_OK;
    } catch (const std::exception &error) {
        return fail(error_message, std::string("FSDB Reader: probe failed: ") + error.what());
    } catch (...) {
        return fail_unknown_exception(error_message);
    }
}

extern "C" wp_fsdb_status wp_fsdb_open(
    const char *path,
    wp_fsdb_reader **out,
    char **error_message
) {
    clear_error(error_message);
    if (path == nullptr || out == nullptr) {
        return fail(error_message, "FSDB Reader: open received a null argument");
    }
    *out = nullptr;

    try {
        std::lock_guard<std::recursive_mutex> lock(reader_mutex());
        scoped_output_suppressor output_suppressor;
        suppress_reader_messages();
        if (!ffrObject::ffrIsFSDB(const_cast<char *>(path))) {
            return fail(error_message, "FSDB Reader: input is not an FSDB file");
        }

        ffrObject *object = ffrObject::ffrOpen3(const_cast<char *>(path));
        if (object == nullptr) {
            return fail(error_message, "FSDB Reader: ffrOpen3 failed");
        }

        wp_fsdb_reader *reader = new (std::nothrow) wp_fsdb_reader{object, nullptr};
        if (reader == nullptr) {
            object->ffrClose();
            return fail(error_message, "FSDB Reader: failed to allocate reader handle");
        }

        *out = reader;
        return WP_FSDB_STATUS_OK;
    } catch (const std::exception &error) {
        return fail(error_message, std::string("FSDB Reader: open failed: ") + error.what());
    } catch (...) {
        return fail_unknown_exception(error_message);
    }
}

extern "C" void wp_fsdb_close(wp_fsdb_reader *reader) {
    if (reader == nullptr) {
        return;
    }

    try {
        std::lock_guard<std::recursive_mutex> lock(reader_mutex());
        scoped_output_suppressor output_suppressor;
        if (reader->active_signal_session != nullptr) {
            reader->active_signal_session->close_noexcept();
        }
        if (reader->object != nullptr) {
            reader->object->ffrClose();
            reader->object = nullptr;
        }
    } catch (...) {
        // Destructors and C ABI close functions cannot report errors safely here.
    }

    delete reader;
}

extern "C" wp_fsdb_status wp_fsdb_read_metadata(
    wp_fsdb_reader *reader,
    wp_fsdb_metadata *out,
    char **error_message
) {
    clear_error(error_message);
    if (reader == nullptr || reader->object == nullptr || out == nullptr) {
        return fail(error_message, "FSDB Reader: metadata read received a null argument");
    }

    out->scale_unit = nullptr;
    out->time_start_raw = 0;
    out->time_end_raw = 0;
    out->xtag_type = 0;

    try {
        std::lock_guard<std::recursive_mutex> lock(reader_mutex());
        scoped_output_suppressor output_suppressor;
        suppress_reader_messages();

        const char *scale_unit = reader->object->ffrGetScaleUnit();
        if (scale_unit == nullptr || scale_unit[0] == '\0') {
            return fail(error_message, "FSDB Reader: scale unit metadata is empty");
        }

        owned_c_string scale_unit_copy(copy_string(scale_unit));
        if (scale_unit_copy == nullptr) {
            return fail(error_message, "FSDB Reader: failed to allocate scale unit string");
        }

        const fsdbXTagType xtag_type = reader->object->ffrGetXTagType();
        if (require_integer_time_tags(reader->object, error_message) != WP_FSDB_STATUS_OK) {
            return WP_FSDB_STATUS_ERROR;
        }

        fsdbTag64 min_tag{};
        fsdbTag64 max_tag{};
        if (reader->object->ffrGetMinFsdbTag64(&min_tag) != FSDB_RC_SUCCESS) {
            return fail(error_message, "FSDB Reader: failed to read minimum FSDB time tag");
        }
        if (reader->object->ffrGetMaxFsdbTag64(&max_tag) != FSDB_RC_SUCCESS) {
            return fail(error_message, "FSDB Reader: failed to read maximum FSDB time tag");
        }

        out->scale_unit = scale_unit_copy.release();
        out->time_start_raw = tag64_to_u64(min_tag);
        out->time_end_raw = tag64_to_u64(max_tag);
        out->xtag_type = static_cast<uint32_t>(xtag_type);
        return WP_FSDB_STATUS_OK;
    } catch (const std::exception &error) {
        return fail(
            error_message,
            std::string("FSDB Reader: metadata read failed: ") + error.what()
        );
    } catch (...) {
        return fail_unknown_exception(error_message);
    }
}

extern "C" wp_fsdb_status wp_fsdb_read_scope_var_tree(
    wp_fsdb_reader *reader,
    wp_fsdb_tree_callback callback,
    void *user,
    char **error_message
) {
    clear_error(error_message);
    if (reader == nullptr || reader->object == nullptr || callback == nullptr) {
        return fail(error_message, "FSDB Reader: hierarchy traversal received a null argument");
    }

    try {
        std::lock_guard<std::recursive_mutex> lock(reader_mutex());
        scoped_output_suppressor output_suppressor;
        suppress_reader_messages();

        tree_callback_context context{callback, user, false, 0};
        // The Reader invokes tree callbacks synchronously while stdout/stderr are
        // suppressed process-wide. Keep the native lock held for the whole call;
        // it is recursive so a future callback-side Reader helper cannot
        // deadlock the same thread, but callback bodies should still stay small.
        if (read_datatype_definitions(reader->object, &context, error_message) !=
            WP_FSDB_STATUS_OK) {
            return WP_FSDB_STATUS_ERROR;
        }

        if (reader->object->ffrReadScopeVarTree2(scope_var_tree_callback, &context) != FSDB_RC_SUCCESS) {
            if (context.aborted) {
                return fail(error_message, "FSDB Reader: hierarchy traversal aborted by callback");
            }
            return fail(error_message, "FSDB Reader: failed to read FSDB scope/variable tree");
        }
        if (context.aborted) {
            return fail(error_message, "FSDB Reader: hierarchy traversal aborted by callback");
        }

        return WP_FSDB_STATUS_OK;
    } catch (const std::exception &error) {
        return fail(
            error_message,
            std::string("FSDB Reader: hierarchy traversal failed: ") + error.what()
        );
    } catch (...) {
        return fail_unknown_exception(error_message);
    }
}

extern "C" wp_fsdb_status wp_fsdb_sample_signal_values(
    wp_fsdb_reader *reader,
    const uint64_t *idcodes,
    std::size_t count,
    uint64_t query_time_raw,
    wp_fsdb_sample_record **out,
    char **error_message
) {
    clear_error(error_message);
    if (reader == nullptr || reader->object == nullptr || out == nullptr || (count > 0 && idcodes == nullptr)) {
        return fail(error_message, "FSDB Reader: value sampling received a null argument");
    }
    *out = nullptr;

    try {
        std::lock_guard<std::recursive_mutex> lock(reader_mutex());
        scoped_output_suppressor output_suppressor;
        suppress_reader_messages();
        if (reject_active_signal_session(reader, "value sampling", error_message) !=
            WP_FSDB_STATUS_OK) {
            return WP_FSDB_STATUS_ERROR;
        }

        wp_fsdb_sample_record *raw_samples = static_cast<wp_fsdb_sample_record *>(
            std::calloc(count == 0 ? 1 : count, sizeof(wp_fsdb_sample_record))
        );
        if (raw_samples == nullptr) {
            return fail(error_message, "FSDB Reader: failed to allocate sample records");
        }
        owned_sample_records samples(raw_samples, sample_records_deleter{count});

        signal_list_guard signal_list(reader->object);
        if (signal_list.load(idcodes, count, error_message) != WP_FSDB_STATUS_OK) {
            return WP_FSDB_STATUS_ERROR;
        }

        for (std::size_t index = 0; index < count; ++index) {
            if (fill_sample_record(
                    reader->object,
                    idcodes[index],
                    query_time_raw,
                    &samples.get()[index],
                    error_message
                ) != WP_FSDB_STATUS_OK) {
                return WP_FSDB_STATUS_ERROR;
            }
        }

        *out = samples.release();
        return WP_FSDB_STATUS_OK;
    } catch (const std::exception &error) {
        return fail(
            error_message,
            std::string("FSDB Reader: value sampling failed: ") + error.what()
        );
    } catch (...) {
        return fail_unknown_exception(error_message);
    }
}

extern "C" wp_fsdb_status wp_fsdb_collect_signal_change_times(
    wp_fsdb_reader *reader,
    const uint64_t *idcodes,
    std::size_t count,
    uint64_t from_raw,
    uint64_t to_raw,
    wp_fsdb_time_list *out,
    char **error_message
) {
    clear_error(error_message);
    if (reader == nullptr || reader->object == nullptr || out == nullptr || (count > 0 && idcodes == nullptr)) {
        return fail(error_message, "FSDB Reader: candidate time collection received a null argument");
    }
    out->times = nullptr;
    out->count = 0;
    if (from_raw > to_raw || count == 0) {
        return WP_FSDB_STATUS_OK;
    }

    try {
        std::lock_guard<std::recursive_mutex> lock(reader_mutex());
        scoped_output_suppressor output_suppressor;
        suppress_reader_messages();
        if (reject_active_signal_session(reader, "candidate time collection", error_message) !=
            WP_FSDB_STATUS_OK) {
            return WP_FSDB_STATUS_ERROR;
        }

        if (require_integer_time_tags(reader->object, error_message) != WP_FSDB_STATUS_OK) {
            return WP_FSDB_STATUS_ERROR;
        }

        signal_list_guard signal_list(reader->object);
        if (signal_list.load(idcodes, count, error_message) != WP_FSDB_STATUS_OK) {
            return WP_FSDB_STATUS_ERROR;
        }

        std::vector<uint64_t> times;
        times.reserve(count);
        std::unordered_set<uint64_t> seen_times;
        seen_times.reserve(count);
        std::unordered_set<fsdbVarIdcode> visited;
        visited.reserve(count);
        for (std::size_t index = 0; index < count; ++index) {
            const fsdbVarIdcode idcode = static_cast<fsdbVarIdcode>(idcodes[index]);
            if (!visited.insert(idcode).second) {
                continue;
            }
            if (append_change_times_for_signal(
                    reader->object,
                    static_cast<uint64_t>(idcode),
                    from_raw,
                    to_raw,
                    times,
                    seen_times,
                    error_message
                ) != WP_FSDB_STATUS_OK) {
                return WP_FSDB_STATUS_ERROR;
            }
        }

        return copy_sorted_unique_times(times, out, error_message);
    } catch (const std::exception &error) {
        return fail(
            error_message,
            std::string("FSDB Reader: candidate time collection failed: ") + error.what()
        );
    } catch (...) {
        return fail_unknown_exception(error_message);
    }
}

extern "C" wp_fsdb_status wp_fsdb_signal_event_occurred(
    wp_fsdb_reader *reader,
    uint64_t idcode,
    uint64_t query_time_raw,
    int *occurred,
    char **error_message
) {
    clear_error(error_message);
    if (reader == nullptr || reader->object == nullptr || occurred == nullptr) {
        return fail(error_message, "FSDB Reader: event occurrence query received a null argument");
    }
    *occurred = 0;

    try {
        std::lock_guard<std::recursive_mutex> lock(reader_mutex());
        scoped_output_suppressor output_suppressor;
        suppress_reader_messages();
        if (reject_active_signal_session(reader, "event occurrence query", error_message) !=
            WP_FSDB_STATUS_OK) {
            return WP_FSDB_STATUS_ERROR;
        }

        if (require_integer_time_tags(reader->object, error_message) != WP_FSDB_STATUS_OK) {
            return WP_FSDB_STATUS_ERROR;
        }

        const uint64_t idcodes[] = {idcode};
        signal_list_guard signal_list(reader->object);
        if (signal_list.load(idcodes, 1, error_message) != WP_FSDB_STATUS_OK) {
            return WP_FSDB_STATUS_ERROR;
        }

        bool hit = false;
        if (read_exact_event_occurrence(
                reader->object,
                idcode,
                query_time_raw,
                hit,
                error_message
            ) != WP_FSDB_STATUS_OK) {
            return WP_FSDB_STATUS_ERROR;
        }
        *occurred = hit ? 1 : 0;
        return WP_FSDB_STATUS_OK;
    } catch (const std::exception &error) {
        return fail(
            error_message,
            std::string("FSDB Reader: event occurrence query failed: ") + error.what()
        );
    } catch (...) {
        return fail_unknown_exception(error_message);
    }
}

extern "C" wp_fsdb_status wp_fsdb_open_signal_session(
    wp_fsdb_reader *reader,
    const uint64_t *idcodes,
    std::size_t count,
    wp_fsdb_signal_session **out,
    char **error_message
) {
    clear_error(error_message);
    if (out == nullptr || reader == nullptr || reader->object == nullptr ||
        (count > 0 && idcodes == nullptr)) {
        return fail(error_message, "FSDB Reader: signal session open received a null argument");
    }
    *out = nullptr;

    try {
        std::lock_guard<std::recursive_mutex> lock(reader_mutex());
        scoped_output_suppressor output_suppressor;
        suppress_reader_messages();
        if (reader->active_signal_session != nullptr) {
            return fail(error_message, "FSDB Reader: a signal session is already active");
        }

        auto session = std::make_unique<wp_fsdb_signal_session>(reader);
        if (session->load(idcodes, count, error_message) != WP_FSDB_STATUS_OK) {
            return WP_FSDB_STATUS_ERROR;
        }

        reader->active_signal_session = session.get();
        *out = session.release();
        return WP_FSDB_STATUS_OK;
    } catch (const std::exception &error) {
        return fail(
            error_message,
            std::string("FSDB Reader: signal session open failed: ") + error.what()
        );
    } catch (...) {
        return fail_unknown_exception(error_message);
    }
}

extern "C" wp_fsdb_status wp_fsdb_signal_session_sample(
    wp_fsdb_signal_session *session,
    const uint64_t *idcodes,
    std::size_t count,
    uint64_t query_time_raw,
    wp_fsdb_sample_record **out,
    char **error_message
) {
    clear_error(error_message);
    if (session == nullptr || out == nullptr || (count > 0 && idcodes == nullptr)) {
        return fail(error_message, "FSDB Reader: signal session sampling received a null argument");
    }
    *out = nullptr;

    try {
        std::lock_guard<std::recursive_mutex> lock(reader_mutex());
        scoped_output_suppressor output_suppressor;
        suppress_reader_messages();

        wp_fsdb_sample_record *raw_samples = static_cast<wp_fsdb_sample_record *>(
            std::calloc(count == 0 ? 1 : count, sizeof(wp_fsdb_sample_record))
        );
        if (raw_samples == nullptr) {
            return fail(error_message, "FSDB Reader: failed to allocate session sample records");
        }
        owned_sample_records samples(raw_samples, sample_records_deleter{count});

        for (std::size_t index = 0; index < count; ++index) {
            ffrVCTrvsHdl handle = nullptr;
            if (session->cached_handle_for(idcodes[index], &handle, error_message) !=
                WP_FSDB_STATUS_OK) {
                return WP_FSDB_STATUS_ERROR;
            }
            if (fill_sample_record_from_handle(
                    handle,
                    idcodes[index],
                    query_time_raw,
                    &samples.get()[index],
                    error_message
                ) != WP_FSDB_STATUS_OK) {
                return WP_FSDB_STATUS_ERROR;
            }
        }

        *out = samples.release();
        return WP_FSDB_STATUS_OK;
    } catch (const std::exception &error) {
        return fail(
            error_message,
            std::string("FSDB Reader: signal session sampling failed: ") + error.what()
        );
    } catch (...) {
        return fail_unknown_exception(error_message);
    }
}

extern "C" wp_fsdb_status wp_fsdb_signal_session_collect_change_times(
    wp_fsdb_signal_session *session,
    const uint64_t *idcodes,
    std::size_t count,
    uint64_t from_raw,
    uint64_t to_raw,
    wp_fsdb_time_list *out,
    char **error_message
) {
    clear_error(error_message);
    if (session == nullptr || out == nullptr || (count > 0 && idcodes == nullptr)) {
        return fail(
            error_message,
            "FSDB Reader: signal session candidate collection received a null argument"
        );
    }
    out->times = nullptr;
    out->count = 0;
    if (from_raw > to_raw || count == 0) {
        return WP_FSDB_STATUS_OK;
    }

    try {
        std::lock_guard<std::recursive_mutex> lock(reader_mutex());
        scoped_output_suppressor output_suppressor;
        suppress_reader_messages();

        if (session->require_open(error_message) != WP_FSDB_STATUS_OK) {
            return WP_FSDB_STATUS_ERROR;
        }
        if (require_integer_time_tags(session->object, error_message) != WP_FSDB_STATUS_OK) {
            return WP_FSDB_STATUS_ERROR;
        }

        std::vector<uint64_t> times;
        times.reserve(count);
        std::unordered_set<uint64_t> seen_times;
        seen_times.reserve(count);
        std::unordered_set<fsdbVarIdcode> visited;
        visited.reserve(count);
        for (std::size_t index = 0; index < count; ++index) {
            if (session->require_idcode(idcodes[index], error_message) != WP_FSDB_STATUS_OK) {
                return WP_FSDB_STATUS_ERROR;
            }
            const fsdbVarIdcode idcode = static_cast<fsdbVarIdcode>(idcodes[index]);
            if (!visited.insert(idcode).second) {
                continue;
            }

            vc_handle_guard handle(session->object->ffrCreateVCTrvsHdl(idcode));
            if (handle.get() == nullptr) {
                return fail(error_message, "FSDB Reader: failed to create value-change traverse handle");
            }
            if (append_change_times_for_handle(
                    handle.get(),
                    from_raw,
                    to_raw,
                    times,
                    seen_times,
                    error_message
                ) != WP_FSDB_STATUS_OK) {
                return WP_FSDB_STATUS_ERROR;
            }
        }

        return copy_sorted_unique_times(times, out, error_message);
    } catch (const std::exception &error) {
        return fail(
            error_message,
            std::string("FSDB Reader: signal session candidate collection failed: ") +
                error.what()
        );
    } catch (...) {
        return fail_unknown_exception(error_message);
    }
}

extern "C" wp_fsdb_status wp_fsdb_signal_session_event_occurred(
    wp_fsdb_signal_session *session,
    uint64_t idcode,
    uint64_t query_time_raw,
    int *occurred,
    char **error_message
) {
    clear_error(error_message);
    if (session == nullptr || occurred == nullptr) {
        return fail(error_message, "FSDB Reader: signal session event query received a null argument");
    }
    *occurred = 0;

    try {
        std::lock_guard<std::recursive_mutex> lock(reader_mutex());
        scoped_output_suppressor output_suppressor;
        suppress_reader_messages();

        if (session->require_open(error_message) != WP_FSDB_STATUS_OK) {
            return WP_FSDB_STATUS_ERROR;
        }
        if (require_integer_time_tags(session->object, error_message) != WP_FSDB_STATUS_OK) {
            return WP_FSDB_STATUS_ERROR;
        }

        ffrVCTrvsHdl handle = nullptr;
        if (session->cached_handle_for(idcode, &handle, error_message) != WP_FSDB_STATUS_OK) {
            return WP_FSDB_STATUS_ERROR;
        }

        bool hit = false;
        if (read_exact_event_occurrence_from_handle(
                handle,
                query_time_raw,
                hit,
                error_message
            ) != WP_FSDB_STATUS_OK) {
            return WP_FSDB_STATUS_ERROR;
        }
        *occurred = hit ? 1 : 0;
        return WP_FSDB_STATUS_OK;
    } catch (const std::exception &error) {
        return fail(
            error_message,
            std::string("FSDB Reader: signal session event query failed: ") + error.what()
        );
    } catch (...) {
        return fail_unknown_exception(error_message);
    }
}

extern "C" void wp_fsdb_close_signal_session(wp_fsdb_signal_session *session) {
    if (session == nullptr) {
        return;
    }

    try {
        std::lock_guard<std::recursive_mutex> lock(reader_mutex());
        scoped_output_suppressor output_suppressor;
        delete session;
    } catch (...) {
        // C ABI close functions cannot report errors safely.
    }
}

extern "C" void wp_fsdb_free_samples(wp_fsdb_sample_record *samples, std::size_t count) {
    free_sample_records(samples, count);
}

extern "C" void wp_fsdb_free_time_list(wp_fsdb_time_list *list) {
    if (list == nullptr) {
        return;
    }
    std::free(list->times);
    list->times = nullptr;
    list->count = 0;
}

extern "C" void wp_fsdb_free_string(char *value) {
    std::free(value);
}

extern "C" void wp_fsdb_free_error(char *value) {
    std::free(value);
}