ondas 2.0.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
//! 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 std::{
    ffi::{CStr, CString, c_char, c_int, c_void},
    io::{Read, Seek, SeekFrom},
    ops::ControlFlow,
    os::unix::ffi::OsStrExt,
    path::Path,
    ptr::NonNull,
    sync::Mutex,
};
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(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_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_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();
        // SAFETY: sole owner; the shim drops traversal state before the reader.
        unsafe { ondas_wdb_close(self.0.as_ptr()) };
    }
}
fn open_handle(path: &Path, metadata_only: bool) -> Result<Handle> {
    let operation = if metadata_only {
        "read metadata"
    } else {
        "open"
    };
    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",
        ))
    })?;
    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(&mut 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 handle = open_handle(path, true)?;
    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()) };
    }
}
pub(crate) struct Reader {
    handle: Handle,
    ids: Vec<u64>,
    indices: Vec<usize>,
    encodings: Vec<Encoding>,
}
impl Reader {
    pub(crate) fn open(path: &Path, name: String) -> Result<(Self, Hierarchy, Metadata)> {
        let handle = open_handle(path, false)?;
        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"))?,
                    );
                }
            }
        }
        let metadata = metadata(meta, name)?;
        let hierarchy = Hierarchy::new(scopes, variables, encodings.clone());
        Ok((
            Self {
                handle,
                ids,
                indices,
                encodings,
            },
            hierarchy,
            metadata,
        ))
    }
    pub(crate) fn sample_bits(
        &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 traversal = Traversal(&mut self.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(
                traversal.0.0.as_ptr(),
                ids.as_ptr(),
                ids.len(),
                0,
                time.ticks(),
                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,
        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 traversal = Traversal(&mut self.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::*;

    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]
    #[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 handle = open_handle(&path, false).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());
        }
    }
}