ondas 2.1.0

Read-only, format-independent waveform analysis library
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
//! Private file-only adapter. Vendor calls and destruction use the same lock.
use crate::{
    BitRange, BitsRef, Direction, Encoding, Error, Format, Hierarchy, LogicDomain, Metadata,
    Packing, Result, Signal, Time, TimeSpan, TimeUnit, Timescale, ValueRef,
    hierarchy::{EnumerationData, ScopeData, VariableData},
};
use sha2::{Digest, Sha256};
use std::{
    ffi::{CStr, CString, c_char, c_int, c_void},
    io::{Read, Seek, SeekFrom},
    ops::ControlFlow,
    os::unix::ffi::OsStrExt,
    os::unix::fs::{MetadataExt, OpenOptionsExt},
    path::Path,
    ptr::NonNull,
    sync::{
        Arc, Mutex, OnceLock,
        atomic::{AtomicBool, Ordering},
    },
};
const BACKEND: &str = "wdb-lib";
static SDK: Mutex<()> = Mutex::new(());
fn lock() -> std::sync::MutexGuard<'static, ()> {
    SDK.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
}
#[repr(C)]
#[derive(Clone, Copy, Default)]
struct Meta {
    last: u64,
    precision: i32,
    has_variables: u32,
}
#[repr(C)]
#[derive(Default)]
struct Declaration {
    id: u64,
    parent: usize,
    scope: u32,
    encoding: u32,
    width: u32,
    has_range: u32,
    is_constant: u32,
    direction: u32,
    signedness: u32,
    logic_domain: u32,
    packing: u32,
    name_syntax: u32,
    msb: i64,
    lsb: i64,
    name: *const c_char,
    reader_name: *const c_char,
    kind: *const c_char,
    type_name: *const c_char,
    definition: *const c_char,
    variants: usize,
    base_len: usize,
}
#[repr(C)]
#[derive(Default)]
struct Record {
    tick: u64,
    id: u64,
    encoding: u32,
    data: *const u8,
    len: usize,
}
const _: () = {
    assert!(std::mem::size_of::<Meta>() == 16);
    assert!(std::mem::offset_of!(Meta, precision) == 8);
    assert!(std::mem::size_of::<Declaration>() == 128);
    assert!(std::mem::offset_of!(Declaration, msb) == 56);
    assert!(std::mem::offset_of!(Declaration, reader_name) == 80);
    assert!(std::mem::offset_of!(Declaration, base_len) == 120);
    assert!(std::mem::size_of::<Record>() == 40);
    assert!(std::mem::offset_of!(Record, data) == 24);
    assert!(std::mem::offset_of!(Record, len) == 32);
};
unsafe extern "C" {
    fn ondas_wdb_open(
        path: *const c_char,
        metadata_only: c_int,
        out: *mut *mut c_void,
        error: *mut c_char,
        cap: usize,
    ) -> c_int;
    fn ondas_wdb_validate_runtime(error: *mut c_char, cap: usize) -> c_int;
    fn ondas_wdb_release_indexes(reader: *mut c_void, error: *mut c_char, cap: usize) -> c_int;
    fn ondas_wdb_release_storage(reader: *mut c_void, error: *mut c_char, cap: usize) -> c_int;
    fn ondas_wdb_close(reader: *mut c_void);
    fn ondas_wdb_metadata(reader: *mut c_void, out: *mut Meta);
    fn ondas_wdb_decl_count(reader: *mut c_void) -> usize;
    fn ondas_wdb_scope_count(reader: *mut c_void) -> usize;
    fn ondas_wdb_declaration(reader: *mut c_void, index: usize, out: *mut Declaration) -> c_int;
    fn ondas_wdb_enum_variant(
        reader: *mut c_void,
        declaration: usize,
        variant: usize,
        bits: *mut *const c_char,
        label: *mut *const c_char,
    ) -> c_int;
    fn ondas_wdb_begin(
        reader: *mut c_void,
        ids: *const u64,
        count: usize,
        start: u64,
        end: u64,
        error: *mut c_char,
        cap: usize,
    ) -> c_int;
    fn ondas_wdb_begin_points(
        handle: *mut c_void,
        ids: *const u64,
        count: usize,
        error: *mut c_char,
        cap: usize,
    ) -> i32;
    fn ondas_wdb_sample_bits(
        reader: *mut c_void,
        id: u64,
        time: u64,
        lsb: u32,
        width: u32,
        out: *mut Record,
        changed: *mut c_int,
        error: *mut c_char,
        cap: usize,
    ) -> c_int;
    fn ondas_wdb_next(
        reader: *mut c_void,
        out: *mut Record,
        error: *mut c_char,
        cap: usize,
    ) -> c_int;
    fn ondas_wdb_end(reader: *mut c_void);
}
fn backend_error(message: impl Into<String>) -> Error {
    Error::Backend {
        backend: BACKEND.into(),
        operation: "decode",
        message: message.into(),
    }
}
fn status(code: c_int, error: &[c_char; 512], operation: &'static str) -> Result<()> {
    if code >= 0 {
        return Ok(());
    }
    // SAFETY: the shim terminates every error buffer with NUL.
    let message = unsafe { CStr::from_ptr(error.as_ptr()) }
        .to_string_lossy()
        .into_owned();
    Err(if code == -4 {
        Error::UnsupportedFeature {
            format: Format::Wdb,
            backend: BACKEND.into(),
            operation,
            message,
        }
    } else {
        Error::Backend {
            backend: BACKEND.into(),
            operation,
            message,
        }
    })
}

fn dbg_version(file: &mut (impl Read + Seek), length: u64) -> std::io::Result<Option<u16>> {
    let mut header = [0; 0xc8];
    if length < header.len() as u64 {
        return Ok(None);
    }
    file.seek(SeekFrom::Start(0))?;
    file.read_exact(&mut header)?;
    if header[..24] != *b"Xilinx WAVE DATABASE 01\0" {
        return Ok(None);
    }
    let word = |bytes: &[u8]| u64::from_le_bytes(bytes.try_into().unwrap());
    let in_bounds = |offset: u64, size: u64| {
        offset >= header.len() as u64 && offset <= length && size <= length - offset
    };
    let mut seen = 0;
    let mut debug = None;
    let mut ranges = vec![(0, header.len() as u64)];
    for pointer in header[0x48..0x60].as_chunks::<8>().0 {
        let pointer = word(pointer);
        if !in_bounds(pointer, 48) {
            return Ok(None);
        }
        ranges.push((pointer, pointer + 48));
        file.seek(SeekFrom::Start(pointer))?;
        let mut entry = [0; 48];
        file.read_exact(&mut entry)?;
        let Some(end) = entry[..24].iter().position(|byte| *byte == 0) else {
            return Ok(None);
        };
        let flag = match &entry[..end] {
            b"WDB.Event" => 1,
            b"Xilinx RTTI" => 2,
            b"Xilinx DBG" => 4,
            _ => return Ok(None),
        };
        let start = word(&entry[32..40]);
        let size = word(&entry[40..48]);
        if seen & flag != 0 || word(&entry[24..32]) != 1 || !in_bounds(start, size) {
            return Ok(None);
        }
        if (flag == 1 && size != 72) || (flag == 2 && size < 40) || (flag == 4 && size < 184) {
            return Ok(None);
        }
        ranges.push((start, start + size));
        seen |= flag;
        if flag == 4 {
            debug = Some((start, size));
        }
    }
    ranges.sort_unstable();
    if ranges.windows(2).any(|pair| pair[0].1 > pair[1].0) {
        return Ok(None);
    }
    let Some((start, _)) = debug else {
        return Ok(None);
    };
    file.seek(SeekFrom::Start(start))?;
    let mut signature = [0; 20];
    file.read_exact(&mut signature)?;
    if !signature.starts_with(b"Xilinx ISim DBG ")
        || !signature[16..19].iter().all(u8::is_ascii_digit)
        || signature[19] != 0
    {
        return Ok(None);
    }
    Ok(std::str::from_utf8(&signature[16..19])
        .ok()
        .and_then(|version| version.parse().ok()))
}
// SAFETY: used only for shim-owned immutable strings while their owner is alive.
unsafe fn string(pointer: *const c_char) -> Result<Option<String>> {
    if pointer.is_null() {
        return Ok(None);
    }
    unsafe { CStr::from_ptr(pointer) }
        .to_str()
        .map(|s| Some(s.to_owned()))
        .map_err(|_| backend_error("non-UTF-8 native metadata"))
}
struct Handle(NonNull<c_void>);
// SAFETY: the supported reader owns its native session. Vendor calls, mutable
// traversal and destruction are serialized. Declaration tables stay immutable
// until close. No native pointer or callback escapes.
unsafe impl Send for Handle {}
unsafe impl Sync for Handle {}
impl Drop for Handle {
    fn drop(&mut self) {
        let _lock = lock();
        // A destroyed owner may still hold loaded histories when its session was tainted, unwound
        // or could not park. Release them best-effort; the close must run even when the release
        // reports a failure.
        let mut error = [0; 512];
        // SAFETY: sole owner; the shim deletes only adapter-created SDK indexes.
        unsafe { ondas_wdb_release_indexes(self.0.as_ptr(), error.as_mut_ptr(), error.len()) };
        // SAFETY: sole owner; the shim drops traversal state before the reader.
        unsafe { ondas_wdb_close(self.0.as_ptr()) };
    }
}
// File-only container preflight. Runs on every logical open, including a reuse hit.
fn preflight(path: &Path, operation: &'static str) -> Result<(CString, std::fs::File, u64)> {
    let malformed = || Error::Malformed {
        format: Format::Wdb,
        backend: BACKEND.into(),
        message: "invalid or truncated WDB container header".into(),
    };
    let mut file = std::fs::File::open(path)?;
    let length = file.metadata()?.len();
    if length < 0xc8 {
        return Err(malformed());
    }
    let mut header = [0; 24];
    file.read_exact(&mut header)?;
    if !header.starts_with(b"Xilinx WAVE DATABASE ") {
        return Err(malformed());
    }
    if header != *b"Xilinx WAVE DATABASE 01\0" {
        return Err(Error::UnsupportedFeature {
            format: Format::Wdb,
            backend: BACKEND.into(),
            operation,
            message: "unsupported WDB container version".into(),
        });
    }
    let path = CString::new(path.as_os_str().as_bytes()).map_err(|_| {
        Error::Io(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            "NUL in WDB path",
        ))
    })?;
    Ok((path, file, length))
}
// A failed preflight must not keep an idle owner alive for the old path: the caller may have
// truncated, replaced or deleted the file. The original error is returned unchanged.
fn preflight_evicting(
    path: &Path,
    operation: &'static str,
) -> Result<(CString, std::fs::File, u64)> {
    match preflight(path, operation) {
        Ok(opened) => Ok(opened),
        Err(error) => {
            evict_idle();
            Err(error)
        }
    }
}
// The identity frame must still describe the file after the native open that an owner is bound to.
fn identity_holds(path: &[u8], file: &std::fs::File, identity: &NativeIdentity) -> bool {
    let Some(from_path) = file_metadata(path) else {
        return false;
    };
    let Ok(from_descriptor) = file.metadata() else {
        return false;
    };
    from_path == identity.metadata
        && metadata_key(&from_descriptor) == Some(identity.metadata.clone())
}
// SDK selection guards without creating a reader; used when a retained owner is reused.
fn validate_runtime() -> Result<()> {
    let mut error = [0; 512];
    let _lock = lock();
    // SAFETY: caller-owned error storage; the shim performs no reader work.
    let code = unsafe { ondas_wdb_validate_runtime(error.as_mut_ptr(), error.len()) };
    status(code, &error, "open")
}
fn native_open(
    path: &CString,
    metadata_only: bool,
    file: &mut std::fs::File,
    length: u64,
) -> Result<Handle> {
    let operation = if metadata_only {
        "read metadata"
    } else {
        "open"
    };
    let mut raw = std::ptr::null_mut();
    let mut error = [0; 512];
    {
        let _lock = lock();
        // SAFETY: caller-owned buffers and C string; the shim copies retained state.
        let code = unsafe {
            ondas_wdb_open(
                path.as_ptr(),
                metadata_only.into(),
                &mut raw,
                error.as_mut_ptr(),
                error.len(),
            )
        };
        if let Err(error) = status(code, &error, operation) {
            // Diagnose only a failed SDK open, as with FSDB. Unknown framing or
            // reader capability must preserve the original failure.
            let reader_version = env!("ONDAS_WDB_DBG_VERSION").parse::<u16>().unwrap();
            if code == -1
                && reader_version != 0
                && let Ok(Some(version)) = dbg_version(file, length)
                && version > reader_version
            {
                return Err(Error::UnsupportedFeature {
                    format: Format::Wdb,
                    backend: BACKEND.into(),
                    operation,
                    message: format!(
                        "WDB DBG version {version:03} is newer than Reader DBG {reader_version:03}"
                    ),
                });
            }
            return Err(error);
        }
    }
    Ok(Handle(
        NonNull::new(raw).ok_or_else(|| backend_error("null native reader"))?,
    ))
}
fn metadata(meta: Meta, source_name: String) -> Result<Metadata> {
    let exponent = meta.precision;
    if !(-21..=2).contains(&exponent) {
        return Err(backend_error("unsupported native timescale exponent"));
    }
    let unit = match exponent.div_euclid(3) * 3 {
        0 => TimeUnit::Second,
        -3 => TimeUnit::Millisecond,
        -6 => TimeUnit::Microsecond,
        -9 => TimeUnit::Nanosecond,
        -12 => TimeUnit::Picosecond,
        -15 => TimeUnit::Femtosecond,
        -18 => TimeUnit::Attosecond,
        -21 => TimeUnit::Zeptosecond,
        _ => return Err(backend_error("unsupported native timescale exponent")),
    };
    Ok(Metadata {
        source_name,
        timescale: Some(Timescale::new(
            10u32.pow(exponent.rem_euclid(3) as u32),
            unit,
        )),
        time_span: (meta.has_variables != 0)
            .then(|| TimeSpan::new(Time::ZERO, Time::from_ticks(meta.last))),
        writer: None,
        date: None,
        comments: Vec::new(),
    })
}
pub(crate) fn read_metadata(path: &Path, name: String) -> Result<Metadata> {
    let (path, mut file, length) = preflight_evicting(path, "read metadata")?;
    evict_idle();
    let handle = native_open(&path, true, &mut file, length)?;
    let mut meta = Meta::default();
    // SAFETY: live owner; this reads only the immutable shim-owned descriptor.
    unsafe { ondas_wdb_metadata(handle.0.as_ptr(), &mut meta) };
    metadata(meta, name)
}
struct Traversal<'a>(&'a mut Handle);
impl Drop for Traversal<'_> {
    fn drop(&mut self) {
        let _lock = lock();
        // SAFETY: live borrowed owner, also on a stop, error or Rust callback panic.
        unsafe { ondas_wdb_end(self.0.0.as_ptr()) };
    }
}
// Metadata of a regular file. Coarse timestamps alone are not a freshness proof.
#[derive(Clone, PartialEq, Eq)]
struct NativeMetadata {
    dev: u64,
    ino: u64,
    size: u64,
    mtime: i64,
    mtime_nsec: i64,
    ctime: i64,
    ctime_nsec: i64,
}
// Full identity of the file that a native open was created from.
#[derive(Clone, PartialEq, Eq)]
struct NativeIdentity {
    metadata: NativeMetadata,
    digest: [u8; 32],
}
fn metadata_key(meta: &std::fs::Metadata) -> Option<NativeMetadata> {
    meta.file_type().is_file().then(|| NativeMetadata {
        dev: meta.dev(),
        ino: meta.ino(),
        size: meta.size(),
        mtime: meta.mtime(),
        mtime_nsec: meta.mtime_nsec(),
        ctime: meta.ctime(),
        ctime_nsec: meta.ctime_nsec(),
    })
}
fn file_metadata(path: &[u8]) -> Option<NativeMetadata> {
    metadata_key(&std::fs::metadata(std::ffi::OsStr::from_bytes(path)).ok()?)
}
// Streamed content identity. Any stat, access, type or IO failure is an optional miss, and
// no bytes are retained. O_NONBLOCK keeps a replacement FIFO from blocking this optional open.
fn content_identity(path: &[u8]) -> Option<NativeIdentity> {
    let before = file_metadata(path)?;
    let mut file = std::fs::OpenOptions::new()
        .read(true)
        .custom_flags(libc::O_NONBLOCK)
        .open(std::ffi::OsStr::from_bytes(path))
        .ok()?;
    // The descriptor must still be the regular file named by the path metadata.
    if metadata_key(&file.metadata().ok()?)? != before {
        return None;
    }
    let mut hasher = Sha256::new();
    let mut buffer = [0u8; 64 * 1024];
    let mut remaining = before.size;
    while remaining > 0 {
        let want = remaining.min(buffer.len() as u64) as usize;
        let read = file.read(&mut buffer[..want]).ok()?;
        if read == 0 {
            return None;
        }
        hasher.update(&buffer[..read]);
        remaining -= read as u64;
    }
    // One extra byte proves that the content did not grow past the recorded size.
    let mut extra = [0u8; 1];
    if file.read(&mut extra).ok()? != 0 {
        return None;
    }
    if metadata_key(&file.metadata().ok()?)? != before
        || file_metadata(path) != Some(before.clone())
    {
        return None;
    }
    let mut digest = [0u8; 32];
    digest.copy_from_slice(&hasher.finalize());
    Some(NativeIdentity {
        metadata: before,
        digest,
    })
}
// Immutable Rust presentation of one imported native declaration table.
struct Presentation {
    ids: Vec<u64>,
    indices: Vec<usize>,
    encodings: Vec<Encoding>,
    hierarchy: Hierarchy,
    meta: Meta,
}
struct Idle {
    path: Vec<u8>,
    identity: NativeIdentity,
    handle: Handle,
    presentation: Presentation,
}
// At most one closed, fully validated owner waits for the next logical open.
static IDLE: Mutex<Option<Idle>> = Mutex::new(None);
fn take_idle(path: &[u8], identity: &NativeIdentity) -> Option<Idle> {
    let _lock = lock();
    let mut idle = IDLE.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
    let candidate = idle.as_ref()?;
    if candidate.path.as_slice() == path && &candidate.identity == identity {
        idle.take()
    } else {
        None
    }
}
// Releases the retained owner. The public layer calls this when a request fails before the WDB
// adapter is entered, for example for a missing, unreadable or unrecognised path.
pub(crate) fn release_idle() {
    evict_idle();
}
// A static is never dropped by the Rust runtime, so a parked owner needs a normal-exit cleanup;
// otherwise its native reader and vendor temporary backing file outlive a normal process exit,
// unlike a reader that is dropped inside the process.
static IDLE_CLEANUP: OnceLock<bool> = OnceLock::new();
// True only when the cleanup handler is actually registered. A failed registration must not be
// recorded as success, or every later park would leak again.
fn idle_cleanup_available() -> bool {
    *IDLE_CLEANUP.get_or_init(|| {
        // SAFETY: the handler never unwinds and never blocks on the SDK mutex.
        unsafe { libc::atexit(release_idle_at_exit) == 0 }
    })
}
// A reader may leave its owner to the next logical open only when the session is clean, the
// identity is known and the process-exit cleanup exists.
fn parkable(tainted: bool, unwinding: bool, has_identity: bool, cleanup_available: bool) -> bool {
    !tainted && !unwinding && has_identity && cleanup_available
}
extern "C" fn release_idle_at_exit() {
    // Another thread may still be using the SDK while the process exits: skip instead of blocking.
    let Ok(_lock) = SDK.try_lock() else {
        return;
    };
    let Some(idle) = IDLE.try_lock().ok().and_then(|mut slot| slot.take()) else {
        return;
    };
    let Idle {
        handle,
        presentation,
        ..
    } = idle;
    let handle = std::mem::ManuallyDrop::new(handle);
    // Release any indexes this owner still holds before the close; a failure must not skip it. The
    // handle is never dropped afterwards, so no second close can run.
    let mut error = [0; 512];
    // SAFETY: sole owner of the native reader, under the SDK lock; the shim deletes only
    // adapter-created SDK indexes.
    unsafe { ondas_wdb_release_indexes(handle.0.as_ptr(), error.as_mut_ptr(), error.len()) };
    // SAFETY: sole owner of the native reader, closed under the SDK lock like Handle::drop.
    unsafe { ondas_wdb_close(handle.0.as_ptr()) };
    drop(presentation);
}
// Destroys the idle owner before any SDK activity. The handle is dropped after the lock.
fn evict_idle() {
    let stale = {
        let _lock = lock();
        IDLE.lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .take()
    };
    drop(stale);
}
pub(crate) struct Reader {
    handle: Option<Handle>,
    ids: Vec<u64>,
    indices: Vec<usize>,
    encodings: Vec<Encoding>,
    // Retained immutable hierarchy data for the next logical open.
    hierarchy: Option<Hierarchy>,
    meta: Meta,
    path: Vec<u8>,
    identity: Option<NativeIdentity>,
    // Cleared permanently by any read or decode failure, including a caller-caught panic.
    tainted: Arc<AtomicBool>,
}
// Marks the owner unparkable if the operation unwinds, even when the caller catches the panic and
// drops the waveform later, outside the unwind.
struct TaintOnUnwind(Arc<AtomicBool>);
impl Drop for TaintOnUnwind {
    fn drop(&mut self) {
        if std::thread::panicking() {
            self.0.store(true, Ordering::Relaxed);
        }
    }
}
impl Drop for Reader {
    fn drop(&mut self) {
        let Some(handle) = self.handle.take() else {
            return;
        };
        let Some(identity) = self.identity.take() else {
            return;
        };
        // A tainted or unwinding logical reader never becomes the idle owner. Without exit cleanup
        // a parked owner would survive the process, so refuse the park and destroy it here. The
        // identity is already known at this point, otherwise the reader would have returned above.
        if !parkable(
            self.tainted.load(Ordering::Relaxed),
            std::thread::panicking(),
            true,
            idle_cleanup_available(),
        ) {
            return;
        }
        let mut replaced = None;
        {
            let _lock = lock();
            // SAFETY: exclusive live owner; traversal goes before the indexes it references.
            unsafe { ondas_wdb_end(handle.0.as_ptr()) };
            let mut error = [0; 512];
            // The documented lifetime ends with this waveform: release every SDK history index
            // before the clean owner can wait for another logical open. A failed release keeps the
            // owner out of the idle slot, so the ordinary close path handles it instead.
            // SAFETY: live owner; the shim deletes only adapter-created SDK indexes.
            let code = unsafe {
                ondas_wdb_release_indexes(handle.0.as_ptr(), error.as_mut_ptr(), error.len())
            };
            // Reuse also requires the optional backing-storage cleanup. A reader kernel without
            // that entry point, or a failed cleanup, closes the owner instead of parking it; a
            // user query keeps its ordinary behaviour and only the reuse opportunity is lost.
            let storage = if code >= 0 {
                // SAFETY: live owner; the shim only resets this owner's manager storage.
                unsafe {
                    ondas_wdb_release_storage(handle.0.as_ptr(), error.as_mut_ptr(), error.len())
                }
            } else {
                -1
            };
            if code >= 0 && storage == 0 {
                let idle = Idle {
                    path: std::mem::take(&mut self.path),
                    identity,
                    handle,
                    presentation: Presentation {
                        ids: std::mem::take(&mut self.ids),
                        indices: std::mem::take(&mut self.indices),
                        encodings: std::mem::take(&mut self.encodings),
                        hierarchy: self
                            .hierarchy
                            .take()
                            .expect("live reader retains its hierarchy"),
                        meta: self.meta,
                    },
                };
                replaced = IDLE
                    .lock()
                    .unwrap_or_else(|poisoned| poisoned.into_inner())
                    .replace(idle);
            }
        }
        drop(replaced);
    }
}
impl Reader {
    pub(crate) fn open(path: &Path, name: String) -> Result<(Self, Hierarchy, Metadata)> {
        let (path, mut file, length) = preflight_evicting(path, "open")?;
        let path_bytes = path.as_bytes().to_vec();
        let identity = content_identity(&path_bytes);
        let hit = match identity.as_ref() {
            Some(identity) => take_idle(&path_bytes, identity),
            None => None,
        };
        let (handle, presentation) = match hit {
            Some(idle) => {
                // The guards must hold for a retained owner exactly as for a fresh open.
                validate_runtime()?;
                (idle.handle, idle.presentation)
            }
            None => {
                // A different path, a failed identity or a metadata-only request invalidates
                // the idle owner before any SDK activity.
                evict_idle();
                let handle = native_open(&path, false, &mut file, length)?;
                let presentation = build_presentation(&handle)?;
                (handle, presentation)
            }
        };
        // The file must still match the frame captured before the identity and the native open.
        // A mismatch only makes the owner non-reusable; it does not hide the successful open.
        let identity = identity.filter(|identity| identity_holds(&path_bytes, &file, identity));
        Self::retained(handle, presentation, path_bytes, identity, name)
    }

    // Builds a new logical reader over already imported immutable declarations.
    fn retained(
        handle: Handle,
        presentation: Presentation,
        path: Vec<u8>,
        identity: Option<NativeIdentity>,
        name: String,
    ) -> Result<(Self, Hierarchy, Metadata)> {
        let Presentation {
            ids,
            indices,
            encodings,
            hierarchy,
            meta,
        } = presentation;
        let metadata = metadata(meta, name)?;
        Ok((
            Self {
                handle: Some(handle),
                ids,
                indices,
                encodings,
                hierarchy: Some(hierarchy.clone()),
                meta,
                path,
                identity,
                tainted: Arc::new(AtomicBool::new(false)),
            },
            hierarchy.reopened(),
            metadata,
        ))
    }
}

fn build_presentation(handle: &Handle) -> Result<Presentation> {
    {
        let mut scopes = Vec::new();
        let mut variables = Vec::new();
        let mut ids = Vec::new();
        let mut indices;
        let mut encodings = Vec::new();
        let raw = handle.0.as_ptr();
        let mut meta = Meta::default();
        // SAFETY: all indices come from this immutable shim declaration table.
        // These getters read only shim-owned immutable data; no vendor call runs.
        // The owner stays alive while the strings are copied into Rust storage.
        unsafe {
            ondas_wdb_metadata(raw, &mut meta);
            let count = ondas_wdb_decl_count(raw);
            let scope_count = ondas_wdb_scope_count(raw);
            if scope_count > count {
                return Err(backend_error("invalid native scope count"));
            }
            indices = vec![usize::MAX; count];
            let mut parents = vec![None; count];
            scopes.reserve(scope_count);
            variables.reserve(count - scope_count);
            for (index, scope_index) in parents.iter_mut().enumerate() {
                let mut d = Declaration::default();
                if ondas_wdb_declaration(raw, index, &mut d) != 0 {
                    return Err(backend_error("invalid native declaration index"));
                }
                let parent = (d.parent != usize::MAX).then_some(d.parent);
                let declaration_name_text =
                    string(d.name)?.ok_or_else(|| backend_error("missing native name"))?;
                let (name, name_was_escaped) =
                    declaration_name(declaration_name_text, d.name_syntax, d.base_len)?;
                let reader_name = string(d.reader_name)?;
                let kind = declaration_kind(string(d.kind)?.unwrap_or_default(), d.encoding);
                if d.scope != 0 {
                    *scope_index = Some(scopes.len());
                    scopes.push(ScopeData {
                        name,
                        name_was_escaped,
                        parent,
                        kind,
                        definition_name: string(d.definition)?,
                        packing: match d.packing {
                            1 => Some(Packing::Packed),
                            2 => Some(Packing::Unpacked),
                            _ => None,
                        },
                        is_hidden: false,
                    });
                    continue;
                }
                let encoding = match d.encoding {
                    1 => Encoding::Bits { width: d.width },
                    2 => Encoding::Real,
                    3 => Encoding::String,
                    _ => Encoding::Unsupported,
                };
                let encoding_index = usize::try_from(d.id)
                    .ok()
                    .and_then(|id| indices.get_mut(id))
                    .ok_or_else(|| backend_error("invalid native history identity"))?;
                if *encoding_index == usize::MAX {
                    *encoding_index = encodings.len();
                    encodings.push(encoding);
                    ids.push(d.id);
                }
                let signal = *encoding_index;
                if encodings[signal] != encoding {
                    return Err(backend_error("incompatible native alias encodings"));
                }
                let type_name = string(d.type_name)?;
                let mut variants = Vec::with_capacity(d.variants);
                for variant in 0..d.variants {
                    let (mut bits, mut label) = (std::ptr::null(), std::ptr::null());
                    if ondas_wdb_enum_variant(raw, index, variant, &mut bits, &mut label) != 0 {
                        return Err(backend_error("invalid native enum index"));
                    }
                    variants.push((
                        string(bits)?.ok_or_else(|| backend_error("missing enum code"))?,
                        string(label)?.ok_or_else(|| backend_error("missing enum label"))?,
                    ));
                }
                let enumeration = if variants.is_empty() {
                    None
                } else {
                    EnumerationData::for_encoding(type_name.clone(), variants, encoding)
                };
                variables.push(VariableData {
                    reader_name,
                    name,
                    name_was_escaped,
                    parent,
                    kind,
                    direction: match d.direction {
                        1 => Direction::Input,
                        2 => Direction::Output,
                        3 => Direction::InOut,
                        4 => Direction::Buffer,
                        5 => Direction::Linkage,
                        _ => Direction::Unknown,
                    },
                    range: (d.has_range != 0).then(|| BitRange::new(d.msb, d.lsb)),
                    is_constant: d.is_constant != 0,
                    type_name,
                    signedness: None,
                    logic_domain: match d.logic_domain {
                        1 => Some(LogicDomain::TwoState),
                        2 => Some(LogicDomain::FourState),
                        3 => Some(LogicDomain::NineState),
                        _ => None,
                    },
                    enumeration,
                    signal: Some(signal),
                });
            }
            if scopes.len() != scope_count {
                return Err(backend_error("inconsistent native scope count"));
            }
            for parent in scopes
                .iter_mut()
                .map(|scope| &mut scope.parent)
                .chain(variables.iter_mut().map(|variable| &mut variable.parent))
            {
                if let Some(index) = *parent {
                    *parent = Some(
                        parents
                            .get(index)
                            .copied()
                            .flatten()
                            .ok_or_else(|| backend_error("native parent is not a scope"))?,
                    );
                }
            }
        }
        Ok(Presentation {
            ids,
            indices,
            hierarchy: Hierarchy::new(scopes, variables, encodings.clone()),
            encodings,
            meta,
        })
    }
}
impl Reader {
    // Any error from a read or decode keeps the owner unparkable for the rest of the session, and
    // an unwinding operation does the same even if the caller catches the panic. A clean return,
    // including a deliberate stop, leaves it parkable.
    fn attempt<T>(&mut self, run: impl FnOnce(&mut Self) -> Result<T>) -> Result<T> {
        let guard = TaintOnUnwind(Arc::clone(&self.tainted));
        let result = run(self);
        if result.is_err() {
            self.tainted.store(true, Ordering::Relaxed);
        }
        drop(guard);
        result
    }
    pub(crate) fn sample_bits(
        &mut self,
        bases: &[Signal],
        signals: &[Signal],
        time: Time,
    ) -> Result<Vec<crate::Sample>> {
        self.attempt(|reader| reader.sample_bits_inner(bases, signals, time))
    }
    fn sample_bits_inner(
        &mut self,
        bases: &[Signal],
        signals: &[Signal],
        time: Time,
    ) -> Result<Vec<crate::Sample>> {
        let ids: Vec<_> = bases
            .iter()
            .map(|signal| self.ids[signal.index()])
            .collect();
        let handle = self
            .handle
            .as_mut()
            .ok_or_else(|| backend_error("WDB reader is closed"))?;
        let traversal = Traversal(handle);
        let mut error = [0; 512];
        let _lock = lock();
        // SAFETY: live exclusive owner; validated IDs and caller-owned error storage.
        let code = unsafe {
            ondas_wdb_begin_points(
                traversal.0.0.as_ptr(),
                ids.as_ptr(),
                ids.len(),
                error.as_mut_ptr(),
                error.len(),
            )
        };
        status(code, &error, "begin read")?;
        let mut samples = Vec::with_capacity(signals.len());
        for &signal in signals {
            let width = signal
                .width()
                .ok_or_else(|| backend_error("point sample requires bits"))?;
            let mut record = Record::default();
            let mut changed = 0;
            // SAFETY: selected validated signal/projection; the shim owns the
            // result until its next operation. Copy before unlocking or reentry.
            let code = unsafe {
                ondas_wdb_sample_bits(
                    traversal.0.0.as_ptr(),
                    self.ids[signal.index()],
                    time.ticks(),
                    signal.lsb(),
                    width,
                    &mut record,
                    &mut changed,
                    error.as_mut_ptr(),
                    error.len(),
                )
            };
            status(code, &error, "sample")?;
            samples.push(if code == 0 {
                crate::Sample::Missing { signal }
            } else {
                if record.encoding != 1
                    || record.len != width as usize
                    || record.data.is_null()
                    || record.tick > time.ticks()
                {
                    return Err(backend_error("invalid native point bit buffer"));
                }
                // SAFETY: exactly width native-validated ASCII bits, copied
                // while the SDK lock and live owner protect the borrowed buffer.
                let bytes = unsafe { std::slice::from_raw_parts(record.data, record.len) };
                crate::Sample::Value {
                    signal,
                    value: crate::Value::Bits(BitsRef::from_validated_ascii(bytes).to_owned()),
                    changed_at: (changed != 0).then_some(Time::from_ticks(record.tick)),
                }
            });
        }
        Ok(samples)
    }

    pub(crate) fn read<B>(
        &mut self,
        signals: &[Signal],
        end: Time,
        visitor: impl for<'v> FnMut(usize, Time, ValueRef<'v>) -> ControlFlow<B>,
    ) -> Result<ControlFlow<B>> {
        self.read_from(signals, Time::ZERO, end, visitor)
    }

    // Nonzero starts use the query engine's normalized entering state.
    pub(crate) fn read_from<B>(
        &mut self,
        signals: &[Signal],
        start: Time,
        end: Time,
        visitor: impl for<'v> FnMut(usize, Time, ValueRef<'v>) -> ControlFlow<B>,
    ) -> Result<ControlFlow<B>> {
        self.attempt(|reader| reader.read_from_inner(signals, start, end, visitor))
    }
    fn read_from_inner<B>(
        &mut self,
        signals: &[Signal],
        start: Time,
        end: Time,
        mut visitor: impl for<'v> FnMut(usize, Time, ValueRef<'v>) -> ControlFlow<B>,
    ) -> Result<ControlFlow<B>> {
        if signals.is_empty() || start > end {
            return Ok(ControlFlow::Continue(()));
        }
        let ids: Vec<_> = signals
            .iter()
            .map(|signal| self.ids[signal.index()])
            .collect();
        let handle = self
            .handle
            .as_mut()
            .ok_or_else(|| backend_error("WDB reader is closed"))?;
        let traversal = Traversal(handle);
        let mut error = [0; 512];
        {
            let _lock = lock();
            // SAFETY: live exclusive owner; the shim copies the validated selection.
            let code = unsafe {
                ondas_wdb_begin(
                    traversal.0.0.as_ptr(),
                    ids.as_ptr(),
                    ids.len(),
                    start.ticks(),
                    end.ticks(),
                    error.as_mut_ptr(),
                    error.len(),
                )
            };
            status(code, &error, "begin read")?;
        }
        let mut bytes = Vec::new();
        let mut previous = 0;
        loop {
            let mut record = Record::default();
            {
                let _lock = lock();
                // SAFETY: live traversal and caller-owned descriptors. Copy borrowed
                // bytes before any further SDK operation or callback.
                let code = unsafe {
                    ondas_wdb_next(
                        traversal.0.0.as_ptr(),
                        &mut record,
                        error.as_mut_ptr(),
                        error.len(),
                    )
                };
                status(code, &error, "read")?;
                if code == 0 {
                    break;
                }
                if record.len > isize::MAX as usize || (record.len != 0 && record.data.is_null()) {
                    return Err(backend_error("invalid native value buffer"));
                }
                bytes.clear();
                if record.len != 0 {
                    bytes.extend_from_slice(unsafe {
                        std::slice::from_raw_parts(record.data, record.len)
                    });
                }
            }
            if record.tick < previous || record.tick > end.ticks() {
                return Err(backend_error("invalid native chronology"));
            }
            previous = record.tick;
            let index = usize::try_from(record.id)
                .ok()
                .and_then(|id| self.indices.get(id))
                .copied()
                .filter(|index| *index != usize::MAX)
                .ok_or_else(|| backend_error("unknown native history"))?;
            let value = match (self.encodings[index], record.encoding) {
                (Encoding::Bits { width }, 1) if bytes.len() == width as usize => {
                    ValueRef::Bits(BitsRef::from_validated_ascii(&bytes))
                }
                (Encoding::Real, 2) if bytes.len() == 8 => {
                    ValueRef::Real(f64::from_ne_bytes(bytes.as_slice().try_into().unwrap()))
                }
                (Encoding::String, 3) => ValueRef::String(crate::value::ascii_string(
                    &bytes,
                    Format::Wdb,
                    BACKEND,
                    Time::from_ticks(record.tick),
                )?),
                _ => return Err(backend_error("native value disagrees with declaration")),
            };
            if let ControlFlow::Break(value) = visitor(index, Time::from_ticks(record.tick), value)
            {
                return Ok(ControlFlow::Break(value));
            }
        }
        Ok(ControlFlow::Continue(()))
    }
}

fn declaration_kind(mut kind: String, encoding: u32) -> String {
    if encoding == 3 {
        return "string".into();
    }
    kind.make_ascii_lowercase();
    match kind.as_str() {
        "enumeration" => "enum".into(),
        "float" => "real".into(),
        "scope" | "logic" | "bit" | "integer" | "real" | "array" | "record" | "string"
        | "event" => kind,
        _ => format!("wdb:{kind}"),
    }
}

fn declaration_name(mut name: String, syntax: u32, base_len: usize) -> Result<(String, bool)> {
    let boundary = if base_len == 0 { name.len() } else { base_len };
    let base = name
        .get(..boundary)
        .ok_or_else(|| backend_error("invalid native array name boundary"))?;
    if syntax == 2 && base.len() >= 2 && base.starts_with('\\') && base.ends_with('\\') {
        let logical = base[1..base.len() - 1].replace("\\\\", "\\");
        name.replace_range(..boundary, &logical);
        return Ok((name, false));
    }
    if syntax != 1 || !base.starts_with('\\') || !base.ends_with(|c: char| c.is_ascii_whitespace())
    {
        return Ok((name, false));
    }
    let end = base
        .trim_end_matches(|c: char| c.is_ascii_whitespace())
        .len();
    name.replace_range(end..boundary, "");
    name.remove(0);
    Ok((name, true))
}

#[cfg(test)]
mod tests {
    use super::*;

    unsafe extern "C" {
        fn ondas_wdb_index_count(reader: *mut c_void) -> usize;
    }

    fn first_queryable(wave: &crate::Waveform) -> crate::Signal {
        wave.hierarchy()
            .variables()
            .filter_map(|variable| variable.signal())
            .find(|signal| !matches!(signal.encoding(), crate::Encoding::Unsupported))
            .expect("published fixture must expose a queryable signal")
    }

    fn scan_once(wave: &mut crate::Waveform) {
        let signal = first_queryable(wave);
        let outcome = wave
            .scan(&[signal], crate::TimeRange::all(), |_| {
                std::ops::ControlFlow::<()>::Continue(())
            })
            .expect("scan published fixture");
        assert!(outcome.is_continue());
    }

    /// SDK history indexes tracked by the live WDB owner of this waveform.
    fn live_indexes(wave: &crate::Waveform) -> usize {
        let crate::backends::Reader::Wdb(reader) = &wave.reader else {
            panic!("expected a wdb-lib waveform");
        };
        let handle = reader.handle.as_ref().expect("live WDB owner");
        let _lock = lock();
        // SAFETY: the live owner is locked and outlives this call.
        unsafe { ondas_wdb_index_count(handle.0.as_ptr()) }
    }

    /// SDK history indexes kept by the parked owner, if any. Takes the adapter lock first, in the
    /// same order as every park, eviction and exit path.
    fn idle_indexes() -> Option<usize> {
        let _lock = lock();
        let idle = IDLE.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
        let idle = idle.as_ref()?;
        // SAFETY: the parked owner is alive under the SDK and idle locks.
        Some(unsafe { ondas_wdb_index_count(idle.handle.0.as_ptr()) })
    }

    /// The released contract ends SDK history indexes with `Waveform::drop`. A parked owner that
    /// keeps them fails here, and the live counts keep the check from passing vacuously.
    #[test]
    #[ignore = "requires the selected WDB reader and installed OPB fixtures; run just conformance-wdb"]
    fn wdb_drop_releases_every_history_index() {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("fixtures/wdb/wdb0301-opb-m/waveform.wdb");
        assert!(
            path.is_file(),
            "missing published fixture {}",
            path.display()
        );

        let mut wave = crate::open_with(&path, BACKEND).expect("open published WDB fixture");
        scan_once(&mut wave);
        assert!(
            live_indexes(&wave) > 0,
            "the query built no SDK history index"
        );
        drop(wave);
        // A parked owner must keep no history index. A kernel without the optional storage
        // cleanup legitimately closes the owner instead of parking it, so no idle owner is fine.
        match idle_indexes() {
            Some(0) | None => {}
            Some(kept) => panic!("Drop parked {kept} retained SDK history indexes"),
        }

        // The reopen reuses the idle owner, so its first access must build the histories again.
        let mut wave = crate::open_with(&path, BACKEND).expect("reopen published WDB fixture");
        scan_once(&mut wave);
        assert!(
            live_indexes(&wave) > 0,
            "the reused owner built no fresh SDK history index"
        );
        drop(wave);
        match idle_indexes() {
            Some(0) | None => {}
            Some(kept) => panic!("the second Drop parked {kept} retained SDK history indexes"),
        }
        evict_idle();
    }

    fn container(version: &[u8; 3]) -> Vec<u8> {
        let mut bytes = vec![0; 640];
        bytes[..24].copy_from_slice(b"Xilinx WAVE DATABASE 01\0");
        for (index, (name, start, size)) in [
            ("WDB.Event", 344_u64, 72_u64),
            ("Xilinx RTTI", 416, 40),
            ("Xilinx DBG", 456, 184),
        ]
        .into_iter()
        .enumerate()
        {
            let entry = 200 + index * 48;
            bytes[0x48 + index * 8..0x50 + index * 8]
                .copy_from_slice(&(entry as u64).to_le_bytes());
            bytes[entry..entry + name.len()].copy_from_slice(name.as_bytes());
            bytes[entry + 24..entry + 32].copy_from_slice(&1_u64.to_le_bytes());
            bytes[entry + 32..entry + 40].copy_from_slice(&start.to_le_bytes());
            bytes[entry + 40..entry + 48].copy_from_slice(&size.to_le_bytes());
        }
        bytes[456..476].copy_from_slice(b"Xilinx ISim DBG 000\0");
        bytes[472..475].copy_from_slice(version);
        bytes
    }

    #[test]
    fn dbg_version_uses_the_directory_instead_of_embedded_strings() {
        let mut bytes = container(b"004");
        bytes.extend_from_slice(b"Xilinx ISim DBG 999\0");
        let debug = bytes[456..640].to_vec();
        bytes.resize(2 * 1024 * 1024, 0);
        let start = bytes.len() as u64;
        bytes.extend_from_slice(&debug);
        bytes[328..336].copy_from_slice(&start.to_le_bytes());
        let length = bytes.len() as u64;
        assert_eq!(
            dbg_version(&mut std::io::Cursor::new(bytes), length).unwrap(),
            Some(4)
        );
        for (signature, expected) in [(b"005", 5), (b"006", 6)] {
            let bytes = container(signature);
            let length = bytes.len() as u64;
            assert_eq!(
                dbg_version(&mut std::io::Cursor::new(bytes), length).unwrap(),
                Some(expected)
            );
        }
    }

    #[test]
    fn dbg_version_does_not_classify_invalid_framing() {
        let original = container(b"006");
        let mut cases = vec![Vec::new(), original[..199].to_vec()];
        let mut invalid = original.clone();
        invalid[0] = b'!';
        cases.push(invalid);
        let mut invalid = original.clone();
        invalid[0x48..0x50].copy_from_slice(&u64::MAX.to_le_bytes());
        cases.push(invalid);
        let mut invalid = original.clone();
        invalid[328..336].copy_from_slice(&u64::MAX.to_le_bytes());
        cases.push(invalid);
        let mut invalid = original.clone();
        invalid[320..328].copy_from_slice(&2_u64.to_le_bytes());
        cases.push(invalid);
        let mut invalid = original.clone();
        invalid[296..320].copy_from_slice(&original[200..224]);
        cases.push(invalid);
        let mut invalid = original.clone();
        invalid[240..248].copy_from_slice(&8_u64.to_le_bytes());
        cases.push(invalid);
        let mut invalid = original.clone();
        invalid[328..336].copy_from_slice(&200_u64.to_le_bytes());
        cases.push(invalid);
        let mut invalid = original;
        invalid[472] = b'?';
        cases.push(invalid);
        for bytes in cases {
            let length = bytes.len() as u64;
            assert_eq!(
                dbg_version(&mut std::io::Cursor::new(bytes), length).unwrap(),
                None
            );
        }
    }

    #[test]
    fn invalid_native_precision_returns_an_error() {
        for precision in [i32::MIN, -22, 3, i32::MAX] {
            assert!(
                metadata(
                    Meta {
                        precision,
                        ..Meta::default()
                    },
                    String::new()
                )
                .is_err()
            );
        }
    }

    #[test]
    fn wdb_park_requires_exit_cleanup_and_a_clean_session() {
        // Everything is clean and known, but the process-exit cleanup is unavailable: the owner is
        // destroyed instead of parked, so a normal exit cannot leak it.
        assert!(!super::parkable(false, false, true, false));
        assert!(super::parkable(false, false, true, true));
        // A tainted session, an unwinding caller or an unknown identity is never parked.
        assert!(!super::parkable(true, false, true, true));
        assert!(!super::parkable(false, true, true, true));
        assert!(!super::parkable(false, false, false, true));
    }

    #[test]
    #[ignore = "requires the selected reader and installed WDB fixture"]
    fn wdb_invalid_native_metadata_indices() {
        let path = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("fixtures/wdb/wdb0091-tesbench-behav/waveform.wdb");
        let (path, mut file, length) = preflight(&path, "open").unwrap();
        let handle = native_open(&path, false, &mut file, length).unwrap();
        let raw = handle.0.as_ptr();
        let mut declaration = Declaration::default();
        let (mut bits, mut label) = (std::ptr::null(), std::ptr::null());
        // SAFETY: a live immutable table and valid output buffers. The invalid
        // indices must return status without a C++ exception crossing the ABI.
        unsafe {
            let count = ondas_wdb_decl_count(raw);
            assert!(count > 0);
            assert_eq!(ondas_wdb_declaration(raw, count, &mut declaration), -1);
            assert_eq!(ondas_wdb_declaration(raw, usize::MAX, &mut declaration), -1);
            assert_eq!(
                ondas_wdb_enum_variant(raw, usize::MAX, 0, &mut bits, &mut label),
                -1
            );
            assert_eq!(
                ondas_wdb_enum_variant(raw, 0, usize::MAX, &mut bits, &mut label),
                -1
            );
            assert_eq!(ondas_wdb_declaration(raw, 0, &mut declaration), 0);
            assert!(!declaration.name.is_null());
        }
    }
}