udf-core 0.2.0

From-scratch UDF (ECMA-167 / OSTA) reader — volume recognition, partition maps (physical/virtual/sparable/metadata), File Entry and directory (FID) traversal, file data, over any Read + Seek source. No findings; the udf-forensic crate grades over this.
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
//! `impl FileSystem for UdfVfs` — the forensic-vfs adapter (behind the `vfs`
//! feature) so a UDF volume composes as `Arc<dyn FileSystem>` in the forensic-vfs
//! engine.
//!
//! [`UdfVfs`] wraps a parsed [`UdfState`] plus its backing `Read + Seek` source in
//! a `Mutex`, so every read is `&self` over interior mutability and one mounted
//! handle serves N workers (matching the iso9660/ext4/NTFS adapters). Nodes are
//! addressed by [`FileId::Opaque`] carrying the File Entry's physical LBA
//! (`fe_lba`) — UDF's node identity primitive. `forensic-vfs`'s `FileId` has no
//! dedicated UDF variant (it is `#[non_exhaustive]`, and this crate must not add
//! one), so `Opaque(fe_lba)` is the closest honest mapping.
//!
//! ## Mapping notes / known limits
//! - **No inode table ⇒ a per-FE record cache.** UDF carries a node's `is_dir`
//!   flag in its parent's File Identifier Descriptor, not at the node's own File
//!   Entry. [`FileSystem::read_dir`]/[`FileSystem::lookup`] cache each child by
//!   `fe_lba`; the root FE is seeded as a directory at [`UdfVfs::open`].
//!   [`FileSystem::meta`] consults that cache — the normal
//!   root→`read_dir`→`lookup`→`stat` flow always populates it. An *untraversed file*
//!   FE cannot be classified as file-vs-dir (a loud [`VfsError::Decode`], never a
//!   guess); the *root* FE is always resolvable (seeded).
//! - **Times.** The UDF reader's public traversal API surfaces only
//!   `name`/`is_dir`/`size`/`fe_lba` per child, not the per-File-Entry recording times,
//!   so [`FsMeta::times`] is all-`None` (honestly absent, not epoch-0). Wiring
//!   the FE modification/creation times through is future work.
//!   [`FileSystem::timestamp_zone`] is [`TimeZonePolicy::Utc`] — UDF ECMA-167
//!   timestamps carry an explicit UTC offset.
//! - **Single stream.** UDF has no alternate data streams; a non-`Default`
//!   [`StreamId`] is refused loud.
//! - **Extents (first cut).** The reader does not expose a File Entry's
//!   allocation descriptors through its public API, so [`FileSystem::extents`]
//!   yields a single logical run (`image_offset` = 0, `len` = file size) rather
//!   than the true on-disk runs. Surfacing the real short/long allocation
//!   descriptors is future work.
//! - **Deleted/unallocated.** Orphan/deleted File Entry recovery and
//!   free-space enumeration are not yet surfaced, so
//!   [`FileSystem::deleted`]/[`FileSystem::unallocated`] are empty streams.
//!   Both are future work, not fabricated data.

use std::collections::HashMap;
use std::io::{Read, Seek};
use std::sync::{Mutex, MutexGuard, PoisonError};

use forensic_vfs::{
    Allocation, ByteRun, DirEntry as VfsDirEntry, DirStream, ExtentStream, FileId, FileSystem,
    FsKind, FsMeta, MacbTimes, NodeKind, NodeStream, ResidencyKind, RunAlloc, RunFlags, RunInfo,
    SectorSizes, SmallHex, StreamId, StreamInfo, StreamKind, TimeZonePolicy, VfsError, VfsResult,
};

use crate::{
    read_dir_at_lba, read_fe_data, read_fe_file_type, UdfState, FILE_TYPE_BLOCK_DEVICE,
    FILE_TYPE_CHAR_DEVICE, FILE_TYPE_DIRECTORY, FILE_TYPE_FIFO, FILE_TYPE_LINK, FILE_TYPE_SOCKET,
};

/// The node kind an ECMA-167 ICB Tag File Type denotes (4/14.6.6).
///
/// A type this reader does not recognize is [`NodeKind::Other`] rather than
/// [`NodeKind::File`]: "the format said something we do not model" and "the
/// format said regular file" are different observations, and collapsing them
/// would fabricate the second.
#[cfg(feature = "vfs")]
fn kind_of_file_type(file_type: u8) -> NodeKind {
    match file_type {
        FILE_TYPE_DIRECTORY => NodeKind::Dir,
        crate::FILE_TYPE_REGULAR => NodeKind::File,
        FILE_TYPE_LINK => NodeKind::Symlink,
        FILE_TYPE_CHAR_DEVICE => NodeKind::CharDevice,
        FILE_TYPE_BLOCK_DEVICE => NodeKind::BlockDevice,
        FILE_TYPE_FIFO => NodeKind::Fifo,
        FILE_TYPE_SOCKET => NodeKind::Socket,
        _ => NodeKind::Other,
    }
}

/// The most a File Identifier Descriptor alone can say about a child's kind.
///
/// A FID records only a directory characteristic bit, so a non-directory child
/// whose own File Entry could not be read is genuinely **unclassified** — it is
/// not evidence of a regular file. Reporting [`NodeKind::Other`] keeps "we could
/// not read the record" distinct from "the record said regular file".
#[cfg(feature = "vfs")]
fn kind_from_fid_only(is_dir: bool) -> NodeKind {
    if is_dir {
        NodeKind::Dir
    } else {
        NodeKind::Other
    }
}

/// Per-node metadata harvested from a parent File Identifier Descriptor and
/// cached by File Entry LBA.
#[derive(Clone, Copy)]
struct FeMeta {
    is_dir: bool,
    kind: NodeKind,
    size: u64,
}

/// Reader plus its per-FE record cache, guarded by one mutex.
struct Inner<R> {
    reader: R,
    cache: HashMap<u32, FeMeta>,
}

/// A mounted UDF volume exposed through the forensic-vfs `FileSystem` contract.
/// Reads are `&self` over an interior `Mutex`, so one handle serves N workers.
pub struct UdfVfs<R: Read + Seek> {
    inner: Mutex<Inner<R>>,
    state: UdfState,
}

impl<R: Read + Seek + Send> UdfVfs<R> {
    /// Open a UDF volume over a `Read + Seek` cursor.
    ///
    /// Parses the AVDP → VDS → FSD bootstrap chain; the root directory's File
    /// Entry LBA (from the File Set Descriptor) seeds the per-FE cache as a
    /// directory so `meta(root())` resolves without a directory read.
    pub fn open(mut reader: R) -> VfsResult<Self> {
        let state = crate::parse_udf_state_checked(&mut reader)
            .map_err(|source| VfsError::Io {
                op: "udf bootstrap",
                source,
            })?
            .ok_or(VfsError::Bootstrap {
                stage: "udf mount",
                detail: "no valid UDF AVDP/VDS/FSD chain".to_string(),
            })?;
        let mut cache = HashMap::new();
        cache.insert(
            state.root_fe_lba,
            FeMeta {
                is_dir: true,
                kind: NodeKind::Dir,
                size: 0,
            },
        );
        Ok(Self {
            inner: Mutex::new(Inner { reader, cache }),
            state,
        })
    }

    /// Lock the interior state, recovering from a poisoned mutex rather than
    /// panicking (Paranoid Gatekeeper).
    fn lock(&self) -> MutexGuard<'_, Inner<R>> {
        self.inner.lock().unwrap_or_else(PoisonError::into_inner)
    }
}

/// The File Entry LBA carried by a [`FileId`]; any other identity domain is a
/// caller error surfaced loud.
fn fe_lba_of(id: FileId) -> VfsResult<u32> {
    match id {
        FileId::Opaque(n) => u32::try_from(n).map_err(|_| VfsError::Unsupported {
            layer: "udf file-id",
            scheme: format!("Opaque({n})"),
        }),
        other => Err(VfsError::Unsupported {
            layer: "udf file-id",
            scheme: format!("{other:?}"),
        }),
    }
}

/// UDF exposes a single unnamed data stream; a named-stream id is refused loud.
fn require_default_stream(stream: StreamId) -> VfsResult<()> {
    match stream {
        StreamId::Default => Ok(()),
        other => Err(VfsError::Unsupported {
            layer: "udf stream",
            scheme: format!("{other:?}"),
        }),
    }
}

/// The File Entry's extended attributes. `read_fe_extended_attributes` gives
/// an empty list for a File Entry with no attribute space and `None` when the
/// space is present but cannot be read or parsed; that `None` is an error here,
/// never "no attributes", which would hide the damage.
fn extended_attributes<R: Read + Seek>(
    reader: &mut R,
    block_size: u32,
    fe_lba: u32,
) -> VfsResult<Vec<crate::xattr::UdfExtendedAttribute>> {
    crate::read_fe_extended_attributes(reader, block_size, fe_lba).ok_or_else(|| VfsError::Decode {
        layer: "udf",
        offset: u64::from(fe_lba) * u64::from(block_size),
        detail: format!(
            "File Entry at LBA {fe_lba} has an extended-attribute space that cannot be \
                 read or parsed: L_EA overruns the {block_size}-byte block, or the space does \
                 not begin with an Extended Attribute Header Descriptor (tag 262)"
        ),
        bytes: SmallHex::new(&[]),
    })
}

impl<R: Read + Seek + Send> UdfVfs<R> {
    /// Resolve the cached `FeMeta` for `fe_lba`, or — for an uncached FE — read
    /// its File Entry, classify it from the ICB Tag File Type, and cache it. A
    /// sector that does not parse as a File Entry is a loud [`VfsError::Decode`]
    /// (an untraversed *file* extent has no cached record and no self-classifiable
    /// directory tag; UDF has no inode table, so it cannot be resolved).
    fn resolve(inner: &mut Inner<R>, fe_lba: u32, block_size: u32) -> VfsResult<FeMeta> {
        if let Some(m) = inner.cache.get(&fe_lba) {
            return Ok(*m);
        }
        match read_fe_file_type(&mut inner.reader, block_size, fe_lba) {
            Some(ft) => {
                let is_dir = ft == FILE_TYPE_DIRECTORY;
                let size =
                    crate::read_fe_info_len(&mut inner.reader, block_size, fe_lba).unwrap_or(0);
                let m = FeMeta {
                    is_dir,
                    kind: kind_of_file_type(ft),
                    size,
                };
                inner.cache.insert(fe_lba, m);
                Ok(m)
            }
            None => Err(VfsError::Decode {
                layer: "udf",
                offset: u64::from(fe_lba) * u64::from(block_size),
                detail: format!(
                    "no File Entry at LBA {fe_lba}; enumerate its parent directory first"
                ),
                bytes: SmallHex::new(&[]),
            }),
        }
    }

    /// Read a directory's children, caching each child's `FeMeta`. A loud error
    /// if `fe_lba` is not a directory File Entry.
    fn dir_children(&self, fe_lba: u32) -> VfsResult<(Vec<crate::UdfFileEntry>, Vec<FeMeta>)> {
        let block_size = self.state.block_size;
        let partition_start = self.state.partition_start;
        let mut inner = self.lock();
        // Classify first so a file (or a non-FE LBA) fails loud rather than
        // yielding an empty listing.
        let meta = Self::resolve(&mut inner, fe_lba, block_size)?;
        if !meta.is_dir {
            return Err(VfsError::Decode {
                layer: "udf",
                offset: u64::from(fe_lba) * u64::from(block_size),
                detail: format!("File Entry at LBA {fe_lba} is not a directory"),
                bytes: SmallHex::new(&[]),
            });
        }
        let children = read_dir_at_lba(&mut inner.reader, block_size, partition_start, fe_lba)
            .ok_or_else(|| VfsError::Decode {
                layer: "udf",
                offset: u64::from(fe_lba) * u64::from(block_size),
                detail: format!("directory File Entry at LBA {fe_lba} could not be read"),
                bytes: SmallHex::new(&[]),
            })?;
        // Classify each child from its own File Entry's ICB Tag File Type
        // (the FID carries only the directory characteristic bit, so a
        // symlink is invisible without the per-child FE read); fall back to
        // the FID's is_dir when the child FE sector is missing.
        let mut metas = Vec::with_capacity(children.len());
        for c in &children {
            let meta = match read_fe_file_type(&mut inner.reader, block_size, c.fe_lba) {
                Some(ft) => FeMeta {
                    is_dir: ft == FILE_TYPE_DIRECTORY,
                    kind: kind_of_file_type(ft),
                    size: c.size,
                },
                // The child's File Entry sector could not be read: fall back to
                // the FID's directory bit, which is all the parent records.
                None => FeMeta {
                    is_dir: c.is_dir,
                    kind: kind_from_fid_only(c.is_dir),
                    size: c.size,
                },
            };
            inner.cache.insert(c.fe_lba, meta);
            metas.push(meta);
        }
        Ok((children, metas))
    }
}

impl<R: Read + Seek + Send> FileSystem for UdfVfs<R> {
    fn kind(&self) -> FsKind {
        FsKind::UDF
    }

    fn root(&self) -> FileId {
        FileId::Opaque(u64::from(self.state.root_fe_lba))
    }

    fn sector_sizes(&self) -> SectorSizes {
        SectorSizes {
            logical: self.state.block_size,
            physical: self.state.block_size,
            cluster_or_block: self.state.block_size,
        }
    }

    fn timestamp_zone(&self) -> TimeZonePolicy {
        // ECMA-167 timestamps carry an explicit type/timezone; UDF's canonical
        // interchange time is UTC-anchored.
        TimeZonePolicy::Utc
    }

    fn read_dir(&self, ino: FileId) -> VfsResult<DirStream> {
        let fe_lba = fe_lba_of(ino)?;
        let (children, metas) = self.dir_children(fe_lba)?;
        let out: Vec<VfsResult<VfsDirEntry>> = children
            .into_iter()
            .zip(metas)
            .map(|(c, meta)| {
                Ok(VfsDirEntry {
                    name: c.name.into_bytes(),
                    id: FileId::Opaque(u64::from(c.fe_lba)),
                    kind: meta.kind,
                })
            })
            .collect();
        Ok(DirStream::new(out.into_iter()))
    }

    fn extents(&self, ino: FileId, stream: StreamId) -> VfsResult<ExtentStream> {
        let fe_lba = fe_lba_of(ino)?;
        require_default_stream(stream)?;
        let block_size = self.state.block_size;
        let mut inner = self.lock();
        let meta = Self::resolve(&mut inner, fe_lba, block_size)?;
        // First cut: the reader does not surface a File Entry's allocation
        // descriptors, so a non-empty node yields one logical run (image_offset 0)
        // rather than its true on-disk runs. See the module note.
        if meta.size == 0 {
            return Ok(ExtentStream::empty());
        }
        let run = RunInfo {
            run: ByteRun {
                image_offset: 0,
                len: meta.size,
                flags: RunFlags::default(),
            },
            alloc: RunAlloc::Allocated,
        };
        Ok(ExtentStream::new(std::iter::once(Ok(run))))
    }

    fn lookup(&self, parent: FileId, name: &[u8]) -> VfsResult<Option<FileId>> {
        let fe_lba = fe_lba_of(parent)?;
        let (children, _) = self.dir_children(fe_lba)?;
        for c in &children {
            if name.eq_ignore_ascii_case(c.name.as_bytes()) {
                return Ok(Some(FileId::Opaque(u64::from(c.fe_lba))));
            }
        }
        Ok(None)
    }

    fn meta(&self, ino: FileId) -> VfsResult<FsMeta> {
        let fe_lba = fe_lba_of(ino)?;
        let block_size = self.state.block_size;
        let mut inner = self.lock();
        let m = Self::resolve(&mut inner, fe_lba, block_size)?;
        Ok(FsMeta {
            ino: u64::from(fe_lba),
            kind: m.kind,
            allocated: Allocation::Allocated,
            size: m.size,
            nlink: 1,
            uid: None,
            gid: None,
            mode: None,
            // The reader's public traversal API does not surface per-FE times;
            // honestly absent, not epoch-0 (see the module note).
            times: MacbTimes {
                modified: None,
                accessed: None,
                changed: None,
                born: None,
            },
            streams: Vec::new(),
            residency: ResidencyKind::NonResident,
            link_target: None,
        })
    }

    /// The file's contents, plus one entry per extended attribute.
    ///
    /// UDF attributes are TYPED records, not name/value pairs, so only
    /// Implementation Use and Application Use carry a name; the rest are
    /// reported with `name: None`. That is deliberate -- the format gives them
    /// no name, and a synthetic label would read as one the image contained.
    ///
    /// Every record is listed regardless of type. A consumer that cannot
    /// interpret a File Times record can still SEE it, which is what stops "no
    /// attributes" being reported for a file that has some.
    fn data_streams(&self, ino: FileId) -> VfsResult<Vec<StreamInfo>> {
        let fe_lba = fe_lba_of(ino)?;
        let block_size = self.state.block_size;
        let mut inner = self.lock();
        let meta = Self::resolve(&mut inner, fe_lba, block_size)?;
        let mut out = vec![StreamInfo {
            id: StreamId::Default,
            name: None,
            size: meta.size,
            residency: ResidencyKind::NonResident,
            kind: StreamKind::Data,
        }];
        let eas = extended_attributes(&mut inner.reader, block_size, fe_lba)?;
        for (i, ea) in eas.iter().enumerate() {
            out.push(StreamInfo {
                id: StreamId::Xattr(u16::try_from(i).unwrap_or(u16::MAX)),
                name: ea.name().map(|n| n.as_bytes().to_vec()),
                size: ea.value().len() as u64,
                residency: ResidencyKind::Resident {
                    inline_len: u32::try_from(ea.value().len()).unwrap_or(u32::MAX),
                },
                kind: StreamKind::Xattr,
            });
        }
        Ok(out)
    }

    fn read_at(&self, ino: FileId, stream: StreamId, off: u64, buf: &mut [u8]) -> VfsResult<usize> {
        let fe_lba = fe_lba_of(ino)?;
        // Attributes are dispatched BEFORE the default-stream guard: that guard
        // refuses stream kinds UDF does not have, and attributes are one it does.
        if let StreamId::Xattr(idx) = stream {
            let block_size = self.state.block_size;
            let mut inner = self.lock();
            Self::resolve(&mut inner, fe_lba, block_size)?;
            let eas = extended_attributes(&mut inner.reader, block_size, fe_lba)?;
            let ea = eas.get(idx as usize).ok_or_else(|| VfsError::Unsupported {
                layer: "udf xattr index",
                scheme: format!("attribute {idx} of {}", eas.len()),
            })?;
            let value = ea.value();
            let start = usize::try_from(off).unwrap_or(usize::MAX);
            let Some(avail) = value.get(start..) else {
                return Ok(0);
            };
            let n = avail.len().min(buf.len());
            buf[..n].copy_from_slice(&avail[..n]);
            return Ok(n);
        }
        require_default_stream(stream)?;
        let block_size = self.state.block_size;
        let partition_start = self.state.partition_start;
        let mut inner = self.lock();
        // Confirm the node resolves (loud on an untraversed file / non-FE LBA).
        Self::resolve(&mut inner, fe_lba, block_size)?;
        let Some(data) = read_fe_data(&mut inner.reader, block_size, partition_start, fe_lba)
        else {
            return Ok(0);
        };
        let Ok(start) = usize::try_from(off) else {
            return Ok(0); // cov:unreachable: off: u64 always fits usize on 64-bit targets (guard for 32-bit)
        };
        if start >= data.len() {
            return Ok(0);
        }
        let n = (data.len() - start).min(buf.len());
        if let (Some(dst), Some(src)) = (buf.get_mut(..n), data.get(start..start + n)) {
            dst.copy_from_slice(src);
        }
        Ok(n)
    }

    fn read_link(&self, ino: FileId, cap: usize) -> VfsResult<Vec<u8>> {
        let fe_lba = fe_lba_of(ino)?;
        let block_size = self.state.block_size;
        let partition_start = self.state.partition_start;
        let mut inner = self.lock();
        let meta = Self::resolve(&mut inner, fe_lba, block_size)?;
        if meta.kind != NodeKind::Symlink {
            // Not a symlink: empty target, not a per-node error (the contract
            // for non-link nodes).
            return Ok(Vec::new());
        }
        // The Information Length is image-controlled and sizes the data read, so
        // it is checked before anything is read. Linux refuses a symlink longer
        // than one logical block (fs/udf/symlink.c, -ENAMETOOLONG); so do we,
        // which keeps the read below to at most one block.
        if let Some(info_len) = crate::read_fe_info_len(&mut inner.reader, block_size, fe_lba) {
            if info_len > u64::from(block_size) {
                return Err(VfsError::Decode {
                    layer: "udf",
                    offset: u64::from(fe_lba) * u64::from(block_size) + 56,
                    detail: format!(
                        "symbolic link File Entry at LBA {fe_lba} declares {info_len} bytes \
                         of path data, more than one {block_size}-byte block (Linux \
                         refuses such a link with ENAMETOOLONG)"
                    ),
                    bytes: SmallHex::new(&info_len.to_le_bytes()),
                });
            }
        }
        let data = read_fe_data(&mut inner.reader, block_size, partition_start, fe_lba)
            .ok_or_else(|| VfsError::Decode {
                layer: "udf",
                offset: u64::from(fe_lba) * u64::from(block_size),
                detail: format!("symbolic link File Entry at LBA {fe_lba} could not be read"),
                bytes: SmallHex::new(&[]),
            })?;
        // The decoded target is at most a few times one block (a CS0 byte can
        // decode to a 3-byte replacement character); `cap` bounds what is returned.
        let mut target = crate::decode_symlink_target(&data).into_bytes();
        target.truncate(cap);
        Ok(target)
    }

    fn deleted(&self) -> VfsResult<NodeStream> {
        // Orphan/deleted File Entry recovery is not yet surfaced.
        Ok(NodeStream::empty())
    }

    fn unallocated(&self) -> VfsResult<ExtentStream> {
        Ok(ExtentStream::empty())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use forensic_vfs::{Allocation, NodeKind, RunAlloc};
    use std::fs::File;
    use std::io::Cursor;

    /// The committed real `mkudffs` fixture: a Type-1 physical partition with a
    /// 512-byte logical block. It is the only fixture whose partition kind the
    /// reader fully resolves for data reads. See `tests/data/README.md`.
    const PLAIN: &str = "udf_plain.img";

    /// The synthetic image with an extended-attribute space on `inline.txt`: a
    /// header descriptor carrying `header_tag` (262 is the real one), a named
    /// Implementation Use record whose value is `hello`, and an unnamed File
    /// Times record (type 5), laid out as ECMA-167 4/14.10 and `xattr.rs` read it.
    fn image_with_eas(header_tag: u16) -> Vec<u8> {
        use crate::test_support::{BS, INLINE_FILE_FE};
        let mut ea = vec![0u8; 24];
        ea[0..2].copy_from_slice(&header_tag.to_le_bytes());
        let mut imp = vec![0u8; 53]; // 16 header + 32 EntityID + 5 value
        imp[0..4].copy_from_slice(&2048u32.to_le_bytes());
        imp[4] = 1;
        imp[8..12].copy_from_slice(&53u32.to_le_bytes());
        imp[12..16].copy_from_slice(&5u32.to_le_bytes()); // ImplementationUseLength
        imp[17..26].copy_from_slice(b"*UDF Test"); // EntityID identifier, past flags
        imp[48..53].copy_from_slice(b"hello");
        ea.extend_from_slice(&imp);
        let mut times = vec![0u8; 16];
        times[0..4].copy_from_slice(&5u32.to_le_bytes());
        times[4] = 1;
        times[8..12].copy_from_slice(&16u32.to_le_bytes());
        ea.extend_from_slice(&times);

        let mut img = crate::test_support::image();
        let o = INLINE_FILE_FE as usize * BS;
        let area = o + 176;
        img[o + 168..o + 172].copy_from_slice(&(ea.len() as u32).to_le_bytes()); // L_EA
        img[o + 172..o + 176].copy_from_slice(&4u32.to_le_bytes()); // L_AD
        img[area..area + ea.len()].copy_from_slice(&ea);
        img[area + ea.len()..area + ea.len() + 4].copy_from_slice(b"abcd");
        img
    }

    fn inline_file(fs: &UdfVfs<Cursor<Vec<u8>>>) -> FileId {
        fs.read_dir(fs.root())
            .expect("root read_dir")
            .map(|e| e.expect("entry"))
            .find(|e| e.name == b"inline.txt")
            .expect("inline.txt present")
            .id
    }

    #[test]
    fn data_streams_lists_every_extended_attribute_named_or_not() {
        let fs = UdfVfs::open(Cursor::new(image_with_eas(262))).expect("open synthetic image");
        let id = inline_file(&fs);
        let streams = fs.data_streams(id).expect("data_streams");
        assert_eq!(streams.len(), 3, "contents + two attributes: {streams:?}");
        assert!(matches!(streams[0].id, StreamId::Default));
        assert_eq!(streams[0].size, 4);
        assert!(matches!(streams[1].id, StreamId::Xattr(0)));
        assert!(matches!(streams[1].kind, StreamKind::Xattr));
        assert_eq!(streams[1].name.as_deref(), Some(&b"*UDF Test"[..]));
        assert_eq!(streams[1].size, 5);
        assert!(matches!(streams[2].id, StreamId::Xattr(1)));
        assert_eq!(streams[2].name, None, "a File Times record has no name");
        assert_eq!(
            streams[2].size, 16,
            "an unnamed record's value is the whole record"
        );

        let mut buf = [0u8; 16];
        assert_eq!(
            fs.read_at(id, StreamId::Xattr(0), 0, &mut buf)
                .expect("read"),
            5
        );
        assert_eq!(&buf[..5], b"hello");
        assert_eq!(
            fs.read_at(id, StreamId::Xattr(0), 3, &mut buf)
                .expect("read"),
            2
        );
        assert_eq!(&buf[..2], b"lo");
        assert_eq!(
            fs.read_at(id, StreamId::Xattr(0), 99, &mut buf)
                .expect("past end"),
            0
        );
        assert_eq!(
            fs.read_at(id, StreamId::Xattr(1), 0, &mut buf)
                .expect("read"),
            16
        );
        let err = fs
            .read_at(id, StreamId::Xattr(7), 0, &mut buf)
            .expect_err("there is no attribute 7");
        assert!(err.to_string().contains("attribute 7 of 2"), "{err}");
        // The attribute space precedes the inline data; the contents still read.
        assert_eq!(
            fs.read_at(id, StreamId::Default, 0, &mut buf)
                .expect("read"),
            4
        );
        assert_eq!(&buf[..4], b"abcd");
    }

    #[test]
    fn a_damaged_extended_attribute_space_is_loud_not_empty() {
        // parse_extended_attributes returns None when the space is present but
        // does not begin with an Extended Attribute Header Descriptor (tag 262):
        // "reporting 'no attributes' for it would hide the damage". The adapter
        // must surface that, not list the file as having no attributes.
        let fs = UdfVfs::open(Cursor::new(image_with_eas(0))).expect("open synthetic image");
        let id = inline_file(&fs);
        let err = fs
            .data_streams(id)
            .expect_err("a damaged attribute space must not read as none");
        assert!(err.to_string().contains("extended-attribute"), "{err}");
        let mut buf = [0u8; 8];
        let err = fs
            .read_at(id, StreamId::Xattr(0), 0, &mut buf)
            .expect_err("a damaged attribute space must not read as attribute-not-found");
        assert!(err.to_string().contains("extended-attribute"), "{err}");
    }

    fn open_plain() -> Option<UdfVfs<File>> {
        let path = format!("{}/../tests/data/{}", env!("CARGO_MANIFEST_DIR"), PLAIN);
        let f = File::open(path).ok()?;
        UdfVfs::open(f).ok()
    }

    #[test]
    fn synthetic_symlink_classifies_and_reads_link() {
        // The synthetic image's root also carries a child FID whose FE cannot
        // be read (BROKEN_DIR_FE), exercising the FID-characteristics fallback
        // alongside the symlink classification.
        let fs =
            UdfVfs::open(Cursor::new(crate::test_support::image())).expect("open synthetic image");
        let children: Vec<_> = fs
            .read_dir(fs.root())
            .expect("root read_dir")
            .map(|e| e.expect("entry"))
            .collect();
        let link = children
            .iter()
            .find(|e| e.name == b"lnk")
            .expect("synthetic symlink present");
        assert_eq!(link.kind, NodeKind::Symlink);
        assert_eq!(
            fs.read_link(link.id, 4096).expect("read_link"),
            b"../README.txt"
        );
        assert_eq!(fs.meta(link.id).expect("meta").kind, NodeKind::Symlink);
    }

    #[test]
    fn a_symlink_longer_than_one_block_is_refused_loud() {
        // Linux refuses a UDF symlink whose path data exceeds one logical block
        // (fs/udf/symlink.c: "We don't support symlinks longer than one
        // block", -ENAMETOOLONG). The Information Length is image-controlled
        // and sizes the read, so honouring a larger one would let a hostile
        // link pull in far more than the caller's cap before truncation.
        use crate::test_support::{BS, SYMLINK_FE};
        let mut img = crate::test_support::image();
        let declared = BS as u64 + 1;
        let o = SYMLINK_FE as usize * BS;
        img[o + 34..o + 36].copy_from_slice(&0u16.to_le_bytes()); // short allocation
        img[o + 56..o + 64].copy_from_slice(&declared.to_le_bytes());
        img[o + 172..o + 176].copy_from_slice(&8u32.to_le_bytes()); // L_AD: one short_ad
        img[o + 176..o + 180].copy_from_slice(&(declared as u32).to_le_bytes());
        img[o + 180..o + 184].copy_from_slice(&16u32.to_le_bytes()); // data at LBA 16
        for rec in img[16 * BS..18 * BS].chunks_exact_mut(4) {
            rec.copy_from_slice(&[4, 0, 0, 0]); // "." components
        }
        let fs = UdfVfs::open(Cursor::new(img)).expect("open synthetic image");
        let children: Vec<_> = fs
            .read_dir(fs.root())
            .expect("root read_dir")
            .map(|e| e.expect("entry"))
            .collect();
        let link = children
            .iter()
            .find(|e| e.name == b"lnk")
            .expect("synthetic symlink present");
        assert_eq!(link.kind, NodeKind::Symlink);
        let err = fs
            .read_link(link.id, 4096)
            .expect_err("a symlink longer than one block must be refused");
        let msg = err.to_string();
        assert!(
            msg.contains("513") && msg.contains("512"),
            "error must name the declared length and the block size: {msg}"
        );
    }

    #[test]
    fn synthetic_symlink_with_unreadable_data_is_loud() {
        // Break the symlink File Entry's allocation descriptors (ICB flags to
        // an unknown allocation type) while leaving the file-type byte intact:
        // classification succeeds, the data read fails loud.
        let mut img = crate::test_support::image();
        let o = crate::test_support::SYMLINK_FE as usize * crate::test_support::BS;
        img[o + 34] = 0x07;
        img[o + 35] = 0x00;
        let fs = UdfVfs::open(Cursor::new(img)).expect("open synthetic image");
        let children: Vec<_> = fs
            .read_dir(fs.root())
            .expect("root read_dir")
            .map(|e| e.expect("entry"))
            .collect();
        let link = children
            .iter()
            .find(|e| e.name == b"lnk")
            .expect("synthetic symlink present");
        assert!(matches!(link.kind, NodeKind::Symlink));
        assert!(
            fs.read_link(link.id, 4096).is_err(),
            "unreadable symlink data must be loud"
        );
    }

    #[test]
    fn a_child_whose_file_entry_is_unreadable_is_unclassified_not_a_file() {
        // Truncating the image below the last two File Entries leaves the
        // directory listing intact but makes those children's own records
        // unreachable. The reader must then say Other — "we could not read the
        // record" — rather than File, which would assert something the volume
        // never stated.
        //
        // File Entry offsets in this fixture: nodes/ 137216, symlink 137728,
        // chardev 138240, blockdev 138752, fifo 139264, socket 139776.
        let path = format!(
            "{}/../tests/data/udf_all_node_types.img",
            env!("CARGO_MANIFEST_DIR")
        );
        // The fixture is committed, not gitignored, so its absence is a failure
        // rather than a reason to skip.
        let full = std::fs::read(&path).expect("udf_all_node_types.img committed");
        let fs = UdfVfs::open(Cursor::new(full[..139_000].to_vec()))
            .expect("truncated image still mounts");
        let nodes = fs
            .read_dir(fs.root())
            .expect("root read_dir")
            .filter_map(Result::ok)
            .find(|e| e.name == b"nodes")
            .map(|e| e.id)
            .expect("nodes/ still listed");
        let kinds: Vec<_> = fs
            .read_dir(nodes)
            .expect("nodes read_dir")
            .filter_map(Result::ok)
            .map(|e| (String::from_utf8_lossy(&e.name).into_owned(), e.kind))
            .collect();
        for (name, kind) in &kinds {
            if name == "fifo" || name == "socket" {
                assert_eq!(
                    *kind,
                    NodeKind::Other,
                    "{name}: File Entry past EOF must read as unclassified"
                );
            }
        }
        // The children whose File Entries survive still classify normally, so
        // the fallback is scoped to the unreadable ones rather than poisoning
        // the whole listing.
        assert!(
            kinds
                .iter()
                .any(|(n, k)| n == "chardev" && *k == NodeKind::CharDevice),
            "a readable child still classifies: {kinds:?}"
        );
    }

    #[test]
    fn a_fid_alone_cannot_classify_a_non_directory() {
        // The FID records one bit. A directory is knowable from it; anything
        // else is unclassified, and must not be reported as a regular file.
        assert_eq!(kind_from_fid_only(true), NodeKind::Dir);
        assert_eq!(kind_from_fid_only(false), NodeKind::Other);
    }

    #[test]
    fn icb_file_type_maps_to_its_node_kind() {
        // The whole ECMA-167 4/14.6.6 mapping, including the arms the fixture
        // cannot reach.
        for (ft, want) in [
            (FILE_TYPE_DIRECTORY, NodeKind::Dir),
            (crate::FILE_TYPE_REGULAR, NodeKind::File),
            (FILE_TYPE_BLOCK_DEVICE, NodeKind::BlockDevice),
            (FILE_TYPE_CHAR_DEVICE, NodeKind::CharDevice),
            (FILE_TYPE_FIFO, NodeKind::Fifo),
            (FILE_TYPE_SOCKET, NodeKind::Socket),
            (FILE_TYPE_LINK, NodeKind::Symlink),
        ] {
            assert_eq!(kind_of_file_type(ft), want, "file_type 0x{ft:02x}");
        }
        // A type this reader does not model reads as Other, never File —
        // "the format said something we do not model" and "the format said
        // regular file" are different observations. 0x00 is unspecified, 0x03
        // an indirect entry, 0x08 extended attributes, 0x0B a terminal entry
        // and 0x0D a stream directory: all real ECMA-167 types, none a node
        // kind this trait models.
        for ft in [0x00, 0x01, 0x02, 0x03, 0x08, 0x0b, 0x0d, 0xff] {
            assert_eq!(
                kind_of_file_type(ft),
                NodeKind::Other,
                "unmodelled file_type 0x{ft:02x} must not read as File"
            );
        }
    }

    #[test]
    fn every_non_regular_node_type_is_classified() {
        // UDF records the node type in one ICB byte (ECMA-167 4/14.6.6, and
        // the kernel's fs/udf/ecma_167.h):
        //
        //   0x06 BLOCK   0x07 CHAR   0x09 FIFO   0x0A SOCKET   0x0C SYMLINK
        //
        // so an adapter that collapses them into `File` is discarding a fact
        // the format states plainly. `udf_all_node_types.img` carries one of
        // each, created by the Linux UDF driver via mknod/mkfifo/bind.
        let path = format!(
            "{}/../tests/data/udf_all_node_types.img",
            env!("CARGO_MANIFEST_DIR")
        );
        let Ok(f) = File::open(&path) else {
            eprintln!("skip: udf_all_node_types.img fixture absent");
            return;
        };
        let Ok(fs) = UdfVfs::open(f) else {
            eprintln!("skip: udf_all_node_types.img did not mount");
            return;
        };
        let root = fs.root();
        let root_children: Vec<_> = fs
            .read_dir(root)
            .expect("root read_dir")
            .map(|e| e.expect("entry"))
            .collect();
        let nodes = root_children
            .iter()
            .find(|e| e.name == b"nodes")
            .expect("nodes dir present");
        assert_eq!(nodes.kind, NodeKind::Dir);

        let children: Vec<_> = fs
            .read_dir(nodes.id)
            .expect("nodes read_dir")
            .map(|e| e.expect("entry"))
            .collect();
        for (name, want) in [
            (&b"symlink"[..], NodeKind::Symlink),
            (&b"chardev"[..], NodeKind::CharDevice),
            (&b"blockdev"[..], NodeKind::BlockDevice),
            (&b"fifo"[..], NodeKind::Fifo),
            (&b"socket"[..], NodeKind::Socket),
        ] {
            let e = children
                .iter()
                .find(|e| e.name == name)
                .expect("every node type present under nodes/");
            assert_eq!(
                e.kind,
                want,
                "read_dir kind for {}",
                String::from_utf8_lossy(name)
            );
            // meta() must agree with read_dir(): the same node cannot be two
            // different kinds depending on how it was reached.
            assert_eq!(
                fs.meta(e.id).expect("meta").kind,
                want,
                "meta kind for {}",
                String::from_utf8_lossy(name)
            );
            // read_link is for link targets. Only the symlink has one; a
            // device, FIFO or socket must read as empty rather than as an
            // error or a fabricated path.
            let target = fs.read_link(e.id, 4096).expect("read_link");
            if want == NodeKind::Symlink {
                assert_eq!(
                    target, b"../README.txt",
                    "the symlink's target is the driver's own resolution"
                );
            } else {
                assert!(
                    target.is_empty(),
                    "{} carries no link target",
                    String::from_utf8_lossy(name)
                );
            }
        }
    }

    #[test]
    fn udf_symlink_surfaces_as_symlink_with_target() {
        // The committed udf_symlink.img carries a real Linux-driver-authored
        // PATH_COMPONENT symlink; the patched adapter must classify it and
        // decode the target exactly as the Linux UDF driver does.
        let path = format!(
            "{}/../tests/data/udf_symlink.img",
            env!("CARGO_MANIFEST_DIR")
        );
        let Ok(f) = File::open(&path) else {
            eprintln!("skip: udf_symlink.img fixture absent");
            return;
        };
        let Ok(fs) = UdfVfs::open(f) else {
            eprintln!("skip: udf_symlink.img did not mount");
            return;
        };
        // Recurse into nested/ and find the symlink; also confirm the regular
        // files still classify as files.
        let root = fs.root();
        let root_children: Vec<_> = fs
            .read_dir(root)
            .expect("root read_dir")
            .map(|e| e.expect("entry"))
            .collect();
        let nested = root_children
            .iter()
            .find(|e| e.name == b"nested")
            .expect("nested dir present");
        assert_eq!(nested.kind, NodeKind::Dir);

        let nested_children: Vec<_> = fs
            .read_dir(nested.id)
            .expect("nested read_dir")
            .map(|e| e.expect("entry"))
            .collect();
        let link = nested_children
            .iter()
            .find(|e| e.name == b"readme-link.txt")
            .expect("readme-link.txt present");
        assert_eq!(
            link.kind,
            NodeKind::Symlink,
            "the adapter must classify the PATH_COMPONENT record as a symlink"
        );
        assert_eq!(
            fs.read_link(link.id, 4096).expect("read_link"),
            b"../README.txt",
            "the decoded target must match the Linux UDF driver's own resolution"
        );
        // `cap` is the trait's hostile-allocation bound: "Read a symlink
        // target, capped so a hostile symlink cannot allocate without bound."
        // Every component length in the chain is image-controlled, so the
        // adapter must not return more than the caller asked for.
        assert_eq!(
            fs.read_link(link.id, 4).expect("read_link capped"),
            b"../R",
            "a cap shorter than the target must truncate it"
        );
        assert_eq!(
            fs.read_link(link.id, 0).expect("read_link zero cap"),
            b"",
            "cap == 0 must yield an empty target"
        );

        let meta = fs.meta(link.id).expect("symlink meta");
        assert_eq!(meta.kind, NodeKind::Symlink);
        // A regular file is not a link and reads an empty target, not an error.
        let readme = root_children
            .iter()
            .find(|e| e.name == b"README.txt")
            .expect("README.txt present");
        assert_eq!(readme.kind, NodeKind::File);
        assert_eq!(
            fs.read_link(readme.id, 4096)
                .expect("read_link regular file"),
            b""
        );
    }

    #[test]
    fn kind_root_and_zone() {
        let Some(fs) = open_plain() else {
            eprintln!("skip: {PLAIN} fixture absent");
            return;
        };
        assert_eq!(fs.kind(), FsKind::UDF);
        assert!(matches!(fs.root(), FileId::Opaque(_)));
        assert_eq!(fs.timestamp_zone(), TimeZonePolicy::Utc);
        let ss = fs.sector_sizes();
        assert_eq!(ss.logical, 512);
        assert_eq!(ss.cluster_or_block, 512);
        assert!(ss.physical >= 512);
        // root() is resolvable via meta without a directory read (seeded cache).
        let m = fs.meta(fs.root()).expect("root meta");
        assert_eq!(m.kind, NodeKind::Dir);
    }

    #[test]
    fn lists_root() {
        let Some(fs) = open_plain() else {
            eprintln!("skip: {PLAIN} fixture absent");
            return;
        };
        let root = fs.root();
        let entries: Vec<_> = fs
            .read_dir(root)
            .expect("read_dir")
            .map(|e| e.expect("entry"))
            .collect();
        // The mkudffs plain image has an empty root by default; the contract is
        // that read_dir on the root directory succeeds (never errors) and every
        // yielded child carries an Opaque FileId.
        for e in &entries {
            assert!(matches!(e.id, FileId::Opaque(_)));
        }
    }

    #[test]
    fn root_extents_and_meta_shape() {
        let Some(fs) = open_plain() else {
            eprintln!("skip: {PLAIN} fixture absent");
            return;
        };
        let m = fs.meta(fs.root()).expect("root meta");
        assert_eq!(m.allocated, Allocation::Allocated);
        assert_eq!(m.nlink, 1);
        assert!(m.times.modified.is_none());
        // extents on the root directory yields at most a single logical run.
        let runs: Vec<_> = fs
            .extents(fs.root(), StreamId::Default)
            .expect("extents")
            .map(|r| r.expect("run"))
            .collect();
        assert!(runs.len() <= 1);
        if let Some(r) = runs.first() {
            assert_eq!(r.alloc, RunAlloc::Allocated);
        }
    }

    #[test]
    fn read_at_with_offset() {
        let Some(fs) = open_plain() else {
            eprintln!("skip: {PLAIN} fixture absent");
            return;
        };
        // The root directory's data is readable; reading past EOF yields 0.
        let mut buf = [0u8; 32];
        let n = fs
            .read_at(fs.root(), StreamId::Default, 0, &mut buf)
            .expect("read_at");
        assert!(n <= buf.len());
        assert_eq!(
            fs.read_at(fs.root(), StreamId::Default, u64::from(u32::MAX), &mut buf)
                .expect("eof read"),
            0
        );
    }

    #[test]
    fn empty_forensic_surfaces() {
        let Some(fs) = open_plain() else {
            eprintln!("skip: {PLAIN} fixture absent");
            return;
        };
        assert_eq!(fs.deleted().unwrap().count(), 0);
        assert_eq!(fs.unallocated().unwrap().count(), 0);
        assert!(fs.read_link(fs.root(), 4096).unwrap().is_empty());
    }

    #[test]
    fn wrong_file_id_and_stream_are_loud() {
        let Some(fs) = open_plain() else {
            eprintln!("skip: {PLAIN} fixture absent");
            return;
        };
        // A non-Opaque FileId is not a UDF node id.
        assert!(fs.meta(FileId::NtfsRef { entry: 5, seq: 1 }).is_err());
        assert!(fs.read_dir(FileId::NtfsRef { entry: 5, seq: 1 }).is_err());
        assert!(fs
            .lookup(FileId::NtfsRef { entry: 5, seq: 1 }, b"x")
            .is_err());
        assert!(fs
            .read_link(FileId::NtfsRef { entry: 5, seq: 1 }, 8)
            .is_err());
        // A named stream is refused.
        assert!(fs
            .read_at(fs.root(), StreamId::Named(1), 0, &mut [0u8; 4])
            .is_err());
        assert!(fs.extents(fs.root(), StreamId::Named(1)).is_err());
    }

    #[test]
    fn read_dir_on_a_file_is_loud() {
        let Some(fs) = open_plain() else {
            eprintln!("skip: {PLAIN} fixture absent");
            return;
        };
        // An FE LBA that is not a directory (a bogus/never-traversed extent that
        // does not parse as a directory File Entry) fails loud, not silently.
        let bogus = FileId::Opaque(u64::from(u32::MAX));
        assert!(fs.read_dir(bogus).is_err());
    }

    #[test]
    fn meta_on_untraversed_file_is_loud() {
        let Some(fs) = open_plain() else {
            eprintln!("skip: {PLAIN} fixture absent");
            return;
        };
        // A file FE never surfaced by read_dir/lookup cannot be stat'd (UDF has
        // no inode table); a loud error, never a guess.
        assert!(fs.meta(FileId::Opaque(9_999_999)).is_err());
    }

    #[test]
    fn lookup_missing_is_none() {
        let Some(fs) = open_plain() else {
            eprintln!("skip: {PLAIN} fixture absent");
            return;
        };
        assert!(fs.lookup(fs.root(), b"NOPE.NOTPRESENT").unwrap().is_none());
    }

    #[test]
    fn fe_lba_of_rejects_non_opaque_and_overflow() {
        assert!(super::fe_lba_of(FileId::Opaque(42)).is_ok());
        assert!(super::fe_lba_of(FileId::Opaque(u64::from(u32::MAX) + 1)).is_err());
        assert!(super::fe_lba_of(FileId::NtfsRef { entry: 1, seq: 1 }).is_err());
    }

    // ── Over the populated synthetic image (test_support) ─────────────────────
    //
    // The committed `mkudffs` plain image has an empty root, so the child-caching,
    // lookup-hit, non-empty-extent, uncached-file-resolve, and non-directory
    // error paths are only reachable over a directory that actually holds files.

    use crate::test_support as ts;

    fn open_rich() -> UdfVfs<Cursor<Vec<u8>>> {
        UdfVfs::open(Cursor::new(ts::image())).expect("rich synthetic UDF opens")
    }

    #[test]
    fn rich_lists_and_looks_up_children() {
        let fs = open_rich();
        let root = fs.root();
        let names: Vec<String> = fs
            .read_dir(root)
            .expect("read_dir")
            .map(|e| String::from_utf8_lossy(&e.expect("entry").name).into_owned())
            .collect();
        assert!(names.iter().any(|n| n == "inline.txt"), "names: {names:?}");
        assert!(names.iter().any(|n| n == "sub"), "names: {names:?}");
        // lookup is case-insensitive and resolves to an Opaque node id.
        let id = fs
            .lookup(root, b"INLINE.TXT")
            .expect("lookup")
            .expect("inline.txt found");
        assert!(matches!(id, FileId::Opaque(_)));
        assert!(fs.lookup(root, b"NOPE").expect("lookup").is_none());
    }

    #[test]
    fn meta_and_extents_on_uncached_file() {
        let fs = open_rich();
        // Stat a file FE that read_dir has not cached — resolve reads it and
        // classifies it from the ICB Tag File Type.
        let file = FileId::Opaque(u64::from(ts::INLINE_FILE_FE));
        let m = fs.meta(file).expect("uncached file meta");
        assert_eq!(m.kind, NodeKind::File);
        assert_eq!(m.size, 4);
        let runs: Vec<_> = fs
            .extents(file, StreamId::Default)
            .expect("extents")
            .map(|r| r.expect("run"))
            .collect();
        assert_eq!(runs.len(), 1);
        assert_eq!(runs[0].run.len, 4);
        assert_eq!(runs[0].alloc, RunAlloc::Allocated);
    }

    #[test]
    fn read_at_returns_file_bytes_across_extents() {
        let fs = open_rich();
        let inline = FileId::Opaque(u64::from(ts::INLINE_FILE_FE));
        let mut buf = [0u8; 8];
        let n = fs
            .read_at(inline, StreamId::Default, 0, &mut buf)
            .expect("read inline");
        assert_eq!(&buf[..n], b"abcd");

        // The short-extent file reads its full length across two blocks.
        let short = FileId::Opaque(u64::from(ts::SHORT_FILE_FE));
        let mut big = vec![0u8; ts::SHORT_FILE_LEN as usize];
        let got = fs
            .read_at(short, StreamId::Default, 0, &mut big)
            .expect("read short");
        assert_eq!(got as u64, ts::SHORT_FILE_LEN);
        assert_eq!(big[0], 0x41);
        assert_eq!(big[599], 0x42);
    }

    #[test]
    fn read_dir_and_read_at_on_broken_dir_are_honest() {
        let fs = open_rich();
        // Populate the cache (marks the broken-dir FE as a directory).
        let _ = fs.read_dir(fs.root()).expect("read root").count();
        // A file FE is not a directory → loud error.
        assert!(fs
            .read_dir(FileId::Opaque(u64::from(ts::INLINE_FILE_FE)))
            .is_err());
        // A directory FE whose data cannot be read fails loud, not empty.
        assert!(fs
            .read_dir(FileId::Opaque(u64::from(ts::BROKEN_DIR_FE)))
            .is_err());
        // read_at on that unreadable directory yields 0 bytes (no data present).
        assert_eq!(
            fs.read_at(
                FileId::Opaque(u64::from(ts::BROKEN_DIR_FE)),
                StreamId::Default,
                0,
                &mut [0u8; 4],
            )
            .expect("read broken dir"),
            0
        );
    }

    #[test]
    fn open_surfaces_io_and_bootstrap_failures() {
        use std::io::{self, Read, Seek, SeekFrom};
        struct Faulty;
        impl Read for Faulty {
            fn read(&mut self, _b: &mut [u8]) -> io::Result<usize> {
                Err(io::Error::other("device read fault"))
            }
        }
        impl Seek for Faulty {
            fn seek(&mut self, _p: SeekFrom) -> io::Result<u64> {
                Ok(0)
            }
        }
        // A read fault during bootstrap is a loud Io error, not a silent mount.
        assert!(matches!(UdfVfs::open(Faulty), Err(VfsError::Io { .. })));
        // A readable but non-UDF source is a loud Bootstrap error.
        let non_udf = Cursor::new(vec![0u8; 257 * 2048]);
        assert!(matches!(
            UdfVfs::open(non_udf),
            Err(VfsError::Bootstrap { .. })
        ));
    }
}