refs_core/directory.rs
1//! ReFS directory object — the Ministore B+-tree of directory records that maps
2//! names to child files and directories, plus each entry's file/directory
3//! metadata (timestamps, size, attribute flags), and image-level path
4//! resolution over the object table.
5//!
6//! # Layout (reverse-engineered — libyal `libfsrefs` "Directory object")
7//!
8//! A directory is a [`MinstorePage`] whose records are keyed by a **directory
9//! record key**:
10//!
11//! ```text
12//! key +0 2 record type: 0x0010 base, 0x0020 name, 0x0030 entry
13//! Entry record (0x0030):
14//! +0 2 record type = 0x0030
15//! +2 2 directory entry type: 0 = FS-metadata file, 1 = File, 2 = Directory
16//! +4 .. name — UTF-16LE, NO end-of-string character (unpaired surrogates
17//! allowed, so it is decoded loss-tolerantly, not as strict UTF-16)
18//! ```
19//!
20//! The entry-record **value** depends on the entry type:
21//!
22//! ```text
23//! Directory values (entry type 2, 72 bytes):
24//! +0 8 directory object identifier
25//! +16 8 creation FILETIME
26//! +24 8 modification (last-written) FILETIME
27//! +32 8 metadata-change FILETIME
28//! +40 8 access FILETIME
29//! +64 4 file attribute flags
30//!
31//! File values (entry type 1, embedded Ministore node, 128-byte header):
32//! +0 8 creation FILETIME
33//! +8 8 modification (last-written) FILETIME
34//! +16 8 metadata-change FILETIME
35//! +24 8 access FILETIME
36//! +32 4 file attribute flags
37//! +64 8 data size (logical file size)
38//! +72 8 allocated (reserved) data size
39//! ```
40//!
41//! # Directory-tree descent (real v3.14 oracle, Doer-Checker)
42//!
43//! A directory is a Minstore B+-tree that may be more than one page deep.
44//! [`list_dir`] resolves an object id to its tree-root block through the object
45//! table, builds a [`ContainerResolver`] from the image's resident metadata, and
46//! **descends** the tree: a **branch** node (Minstore node-type flag `0x01`)
47//! carries in each row's value a format-v3 metadata block reference whose first
48//! block number (value `+0`) is a child page's *virtual* block — resolved
49//! virtual→physical and recursed into; a **leaf** node's `0x30` records are the
50//! directory entries. Every candidate page offset is validated by a self-block
51//! round-trip (the page there must be an `MSB+` page whose self-block equals the
52//! requested block) so a wrong-but-in-bounds base is never trusted.
53//!
54//! When the whole tree is physically resident the real listing is returned (on
55//! the v3.14 oracle the descent reads the real `System Volume Information`
56//! directory entry). When a child leaf is a non-resident virtual block — the
57//! minted user files live in a band beyond the 256 MiB slice — the walk fails
58//! loud with that block ([`RefsError::UnresolvedVirtualBlock`]) rather than
59//! fabricate or silently truncate the listing.
60//!
61//! # Robustness
62//!
63//! Every field is read through bounds-checked helpers; a lying name length or
64//! record offset (handled in the [`MinstorePage`] layer) yields only in-bounds
65//! bytes, never an over-read. Filenames decode loss-tolerantly so an unpaired
66//! surrogate or an odd trailing byte cannot panic.
67
68use crate::bytes::{le_u16, le_u32, le_u64};
69use crate::container::ContainerResolver;
70use crate::error::RefsError;
71use crate::metablock::REFS_METADATA_PAGE_SIZE;
72use crate::minstore::{MinstorePage, ObjectTable, REFS_ROOT_DIRECTORY_ID};
73
74/// Directory record key record type: an **entry** record (name → child).
75const RECORD_TYPE_ENTRY: u16 = 0x0030;
76
77/// Band size in clusters used to build the [`ContainerResolver`] when the image
78/// handed to [`list_dir`] carries no boot sector to read it from (the synthetic
79/// test images, and any caller passing a bare partition body). Derived from the
80/// documented v3.x layout — band size `67_108_864` / cluster `4096` = `16_384`
81/// clusters — and byte-verified on the real v3.14 oracle (see
82/// [`crate::ContainerResolver`] docs). A caller with the boot sector can build
83/// its own resolver with the exact band size and pass it to [`walk_directory`].
84const DEFAULT_BAND_CLUSTERS: u64 = 16_384;
85
86/// Maximum B+tree descent depth. Real directory trees are only a handful of
87/// levels deep; this cap makes a lying/cyclic branch chain (a hostile image
88/// pointing a node at an ancestor) terminate instead of recursing without
89/// bound. Paired with a visited-block set to break cycles at the same physical
90/// page (the Paranoid Gatekeeper standard).
91const MAX_DESCENT_DEPTH: usize = 64;
92
93/// Maximum number of child pages a single descent will visit, independent of
94/// depth — a second bound so a wide fan-out of lying branch rows cannot spin an
95/// unbounded walk even within the depth cap.
96const MAX_VISITED_PAGES: usize = 4096;
97
98/// Directory entry type for a **File** (has file metadata + data attributes).
99const ENTRY_TYPE_FILE: u16 = 1;
100/// Directory entry type for a **Directory** (has a child object id).
101const ENTRY_TYPE_DIRECTORY: u16 = 2;
102
103/// The largest ReFS metadata block number that maps into the physically
104/// resident low band of the minted oracle. Blocks below `RESIDENT_VIRTUAL_BASE`
105/// map to `cluster = block`; blocks at/above it map to
106/// `cluster = block - RESIDENT_VIRTUAL_BASE` (the second addressing regime seen
107/// on the real volume, where cluster 52 carries self-block 65588). Any block
108/// that does not land inside the supplied image is an unresolved virtual
109/// address (container-table territory).
110const RESIDENT_VIRTUAL_BASE: u64 = 65_536;
111
112/// The physical cluster where the object table page sits (the real-volume
113/// convention verified in P1: the `MSB+` object tree at cluster 56).
114const OBJECT_TABLE_CLUSTER: u64 = 56;
115
116/// ReFS cluster size in bytes (4 KiB — verified on the v3.14 oracle). Four
117/// clusters make one 16 KiB metadata page.
118const CLUSTER_SIZE: usize = 4096;
119
120/// File/directory metadata carried by a directory entry value.
121///
122/// FILETIME values are the raw 100-ns-since-1601 `u64` ticks (UTC), preserved
123/// verbatim so a machine consumer round-trips them losslessly; higher layers
124/// convert to a calendar time.
125#[derive(Debug, Clone, PartialEq, Eq)]
126#[non_exhaustive]
127pub struct FileMetadata {
128 /// Logical file size in bytes (`0` for a directory).
129 pub size: u64,
130 /// Allocated / reserved size in bytes (`0` for a directory).
131 pub allocated: u64,
132 /// Creation FILETIME.
133 pub created: u64,
134 /// Last-modification (last-written) FILETIME.
135 pub modified: u64,
136 /// Last-access FILETIME.
137 pub accessed: u64,
138 /// Metadata-change (entry last-modification) FILETIME.
139 pub changed: u64,
140 /// File attribute flags (`0x10` = directory, `0x20` = archive, …).
141 pub attributes: u32,
142 /// True when this entry is a directory.
143 pub is_directory: bool,
144}
145
146/// One resolved directory entry: a name, its kind, its metadata, and — for a
147/// directory — the child object id to descend into.
148#[derive(Debug, Clone, PartialEq, Eq)]
149#[non_exhaustive]
150pub struct DirEntry {
151 /// The entry name, decoded from UTF-16LE (loss-tolerant: unpaired surrogates
152 /// become U+FFFD rather than a parse failure).
153 pub name: String,
154 /// True when the entry is a directory.
155 pub is_directory: bool,
156 /// For a directory, the child directory object identifier (resolve through
157 /// the object table to reach its own B+tree). `None` for a file — a file's
158 /// record is inline in this directory, it has no separate object-table id.
159 pub object_id: Option<u64>,
160 /// The entry's file/directory metadata (timestamps, size, flags).
161 pub metadata: Option<FileMetadata>,
162}
163
164/// Decode a UTF-16LE byte run loss-tolerantly (unpaired surrogates → U+FFFD; an
165/// odd trailing byte is dropped). ReFS names are "UTF-16 with unpaired
166/// surrogates", so strict decoding would reject legitimate names.
167fn decode_utf16le(bytes: &[u8]) -> String {
168 let units: Vec<u16> = bytes
169 .chunks_exact(2)
170 .map(|c| u16::from_le_bytes([c[0], c[1]]))
171 .collect();
172 char::decode_utf16(units)
173 .map(|r| r.unwrap_or(char::REPLACEMENT_CHARACTER))
174 .collect()
175}
176
177/// Parse a directory entry-record value into [`FileMetadata`].
178fn parse_metadata(value: &[u8], is_directory: bool) -> FileMetadata {
179 if is_directory {
180 // Directory value (72 bytes): timestamps @16/24/32/40, attr @64.
181 FileMetadata {
182 size: 0,
183 allocated: 0,
184 created: le_u64(value, 16),
185 modified: le_u64(value, 24),
186 changed: le_u64(value, 32),
187 accessed: le_u64(value, 40),
188 attributes: le_u32(value, 64),
189 is_directory: true,
190 }
191 } else {
192 // File value (128-byte header): timestamps @0/8/16/24, attr @32,
193 // size @64, allocated @72.
194 FileMetadata {
195 size: le_u64(value, 64),
196 allocated: le_u64(value, 72),
197 created: le_u64(value, 0),
198 modified: le_u64(value, 8),
199 changed: le_u64(value, 16),
200 accessed: le_u64(value, 24),
201 attributes: le_u32(value, 32),
202 is_directory: false,
203 }
204 }
205}
206
207/// Parse a Ministore directory page into its directory entries.
208///
209/// Only **entry records** (key record type `0x0030`) become [`DirEntry`]s; base
210/// (`0x0010`) and name (`0x0020`) records are skipped (they are not name→child
211/// entries). Names decode from UTF-16LE loss-tolerantly.
212///
213/// # Errors
214///
215/// - Any error from [`MinstorePage::parse`] (a page too short to hold the node
216/// header). A well-formed but empty directory page yields an empty `Vec`.
217pub fn parse_directory(page: &[u8]) -> Result<Vec<DirEntry>, RefsError> {
218 let node = MinstorePage::parse(page, 0)?;
219 let mut out = Vec::new();
220 collect_entries(&node, &mut out);
221 Ok(out)
222}
223
224/// Translate a physically-resident ReFS metadata block number to its byte
225/// offset within `image`, or `None` if the block is a virtual address outside
226/// the resident region.
227///
228/// Two resident regimes are observed on the real volume: low blocks
229/// (`block < RESIDENT_VIRTUAL_BASE`) map directly to `cluster = block`; blocks
230/// in the resident high band map to `cluster = block - RESIDENT_VIRTUAL_BASE`.
231/// A resolution is accepted only when the whole 16 KiB page lies inside the
232/// image; otherwise the block is treated as unresolved (container-table needed).
233fn resident_block_offset(block: u64, image_len: usize) -> Option<usize> {
234 let candidates = if block >= RESIDENT_VIRTUAL_BASE {
235 // High-band resident mapping, then also allow the low mapping as a
236 // fallback (a small image may place a page at a low block number).
237 [Some(block - RESIDENT_VIRTUAL_BASE), Some(block)]
238 } else {
239 [Some(block), None]
240 };
241 for cluster in candidates.into_iter().flatten() {
242 let off = usize::try_from(cluster).ok()?.checked_mul(CLUSTER_SIZE)?;
243 if off.checked_add(REFS_METADATA_PAGE_SIZE)? <= image_len {
244 return Some(off);
245 }
246 }
247 None
248}
249
250/// Read the object table page from `image` (at the verified object-table
251/// cluster) and parse it.
252fn object_table(image: &[u8]) -> Result<ObjectTable<'_>, RefsError> {
253 let off = usize::try_from(OBJECT_TABLE_CLUSTER)
254 .ok()
255 .and_then(|c| c.checked_mul(CLUSTER_SIZE))
256 .ok_or(RefsError::Truncated {
257 structure: "object table (offset overflow)",
258 need: usize::MAX,
259 have: image.len(),
260 })?;
261 let page = image.get(off..).ok_or(RefsError::Truncated {
262 structure: "object table page",
263 need: off,
264 have: image.len(),
265 })?;
266 ObjectTable::parse(page, off as u64)
267}
268
269/// The `MSB+` Minstore metadata-page signature; a resolved directory page must
270/// carry it (and the requested self-block) to be trusted.
271const MSB_SIGNATURE: &[u8; 4] = b"MSB+";
272
273/// Header offset of a metadata page's self (first) block number.
274const SELF_BLOCK_OFFSET: usize = 0x20;
275
276/// True when the 16 KiB page at `off` is a Minstore page whose self-block-number
277/// equals `block` — the round-trip that proves a candidate offset really is the
278/// page for `block` (never trusts a base that resolves to the wrong page).
279fn page_answers_block(image: &[u8], off: usize, block: u64) -> bool {
280 let Some(page) = image.get(off..off + REFS_METADATA_PAGE_SIZE) else {
281 return false;
282 };
283 page.get(0..4) == Some(MSB_SIGNATURE.as_slice()) && le_u64(page, SELF_BLOCK_OFFSET) == block
284}
285
286/// Translate a directory-tree block number to its byte offset within `image`,
287/// preferring the evidence-based container resolver (the real-volume
288/// virtual→physical map) and falling back to the resident heuristic for images
289/// that carry no resolvable band metadata (the synthetic low-block placements).
290///
291/// Every candidate offset is **validated by a self-block round-trip** (the page
292/// there must be an `MSB+` page whose self-block-number equals `block`) before it
293/// is trusted — so a base that resolves to a *wrong-but-in-bounds* page is
294/// rejected and the next strategy is tried, never silently returned (the
295/// validate-the-bootstrap-before-trusting-it standard). Returns `None` only when
296/// no strategy lands the genuine page for `block` — a genuinely unresolved
297/// virtual address (the caller fails loud with the block).
298fn resolve_block_offset(image: &[u8], resolver: &ContainerResolver, block: u64) -> Option<usize> {
299 // (1) Container resolver — authoritative virtual→physical, when it maps the
300 // block AND the resolved page round-trips its self-block. `resolve_virtual`
301 // yields a byte offset that already fit the image (a usize-bounded buffer),
302 // so `usize::try_from` is infallible in practice; `.ok()` degrades a
303 // (64-bit-unreachable) overflow to "not resolvable via this path" rather than
304 // panicking, then falls through to the resident heuristic.
305 if let Some(off) = resolver
306 .resolve_virtual(block)
307 .and_then(|o| usize::try_from(o).ok())
308 {
309 if page_answers_block(image, off, block) {
310 return Some(off);
311 }
312 }
313 // (2) Resident heuristic (block==cluster, or block-RESIDENT_VIRTUAL_BASE),
314 // likewise accepted only if the page there answers the requested block.
315 if let Some(off) = resident_block_offset(block, image.len()) {
316 if page_answers_block(image, off, block) {
317 return Some(off);
318 }
319 }
320 None
321}
322
323/// Read the whole 16 KiB metadata page at directory-tree `block`, or fail loud
324/// with the offending block when it cannot be resolved to an in-bounds page.
325fn read_page<'a>(
326 image: &'a [u8],
327 resolver: &ContainerResolver,
328 block: u64,
329) -> Result<&'a [u8], RefsError> {
330 let off = resolve_block_offset(image, resolver, block)
331 .ok_or(RefsError::UnresolvedVirtualBlock { block })?;
332 image
333 .get(off..off + REFS_METADATA_PAGE_SIZE)
334 .ok_or(RefsError::Truncated {
335 structure: "directory page",
336 need: off + REFS_METADATA_PAGE_SIZE,
337 have: image.len(),
338 })
339}
340
341/// Descend the directory B+tree rooted at metadata block `block`, appending
342/// every leaf-level directory entry to `out`.
343///
344/// A **branch** node (Minstore node-type flag `0x01`) carries, in each row's
345/// value, a format-v3 metadata block reference whose first block number
346/// (value `+0`) is the *virtual* block of a child page — resolved here through
347/// the container resolver and recursed into. A **leaf** node's `0x30` records
348/// are the directory entries (parsed exactly as [`parse_directory`]).
349///
350/// Robustness: the walk is bounded by depth ([`MAX_DESCENT_DEPTH`]), by total
351/// pages visited ([`MAX_VISITED_PAGES`]), and by a `visited` set that breaks
352/// cycles at a repeated physical block — a hostile image (a node pointing at an
353/// ancestor, or a fan-out of lying branch rows) terminates without panic or
354/// unbounded recursion. An unmapped child block is surfaced loud (never a
355/// silently-truncated listing).
356fn descend(
357 image: &[u8],
358 resolver: &ContainerResolver,
359 block: u64,
360 depth: usize,
361 visited: &mut Vec<u64>,
362 out: &mut Vec<DirEntry>,
363) -> Result<(), RefsError> {
364 if depth >= MAX_DESCENT_DEPTH || visited.len() >= MAX_VISITED_PAGES {
365 return Ok(());
366 }
367 if visited.contains(&block) {
368 return Ok(());
369 }
370 visited.push(block);
371
372 let page = read_page(image, resolver, block)?;
373 let node = MinstorePage::parse(page, 0)?;
374
375 if node.is_branch() {
376 // Branch node: each row's value is a metadata block reference whose first
377 // block number (value +0) is a child page's virtual block. Recurse.
378 for row in node.rows() {
379 let Some(child_bytes) = row.value.get(0..8) else {
380 // A branch row too short to hold a block number is malformed (a
381 // real branch value is a 48-byte block reference); skip it rather
382 // than over-read a lying record the Minstore layer let through.
383 continue;
384 };
385 let child = le_u64(child_bytes, 0);
386 descend(image, resolver, child, depth + 1, visited, out)?;
387 }
388 } else {
389 // Leaf node: its 0x30 records are the directory entries.
390 collect_entries(&node, out);
391 }
392 Ok(())
393}
394
395/// Append the leaf-level `0x30` directory entries of a parsed Minstore node to
396/// `out` (the leaf half of [`parse_directory`], factored so the descent reuses
397/// it).
398fn collect_entries(node: &MinstorePage<'_>, out: &mut Vec<DirEntry>) {
399 for row in node.rows() {
400 if le_u16(row.key, 0) != RECORD_TYPE_ENTRY {
401 continue;
402 }
403 let entry_type = le_u16(row.key, 2);
404 let name = decode_utf16le(row.key.get(4..).unwrap_or(&[]));
405 let is_directory = entry_type == ENTRY_TYPE_DIRECTORY;
406 let (object_id, metadata) = match entry_type {
407 ENTRY_TYPE_DIRECTORY => (
408 Some(le_u64(row.value, 0)),
409 Some(parse_metadata(row.value, true)),
410 ),
411 ENTRY_TYPE_FILE => (None, Some(parse_metadata(row.value, false))),
412 _ => (None, None),
413 };
414 out.push(DirEntry {
415 name,
416 is_directory,
417 object_id,
418 metadata,
419 });
420 }
421}
422
423/// List the entries of the directory with object id `dir_object_id` over a whole
424/// ReFS image, **walking the directory B+tree** from its root through any branch
425/// nodes down to the leaf pages.
426///
427/// Resolves `dir_object_id` through the object table to its tree-root block,
428/// builds a [`ContainerResolver`] from the image's resident metadata, then
429/// descends: a branch node's rows point (value `+0`) at child pages resolved
430/// virtual→physical and recursed into; a leaf node's `0x30` records are the
431/// directory entries. When the whole tree is resident the real listing is
432/// returned; when a child leaf is a non-resident virtual block the walk fails
433/// loud with that block (never a fabricated or silently-truncated listing).
434///
435/// # Errors
436///
437/// - [`RefsError::ObjectIdNotFound`] if the id is absent from the object table.
438/// - [`RefsError::UnresolvedVirtualBlock`] if the tree-root — or any child page
439/// reached during the descent — is a virtual block that resolves to no
440/// in-bounds physical page (a band beyond the supplied image). A loud
441/// diagnostic naming the offending block, never a silent empty listing.
442/// - [`RefsError::Truncated`] if the image is too small to hold a referenced
443/// page or the object table.
444pub fn list_dir(image: &[u8], dir_object_id: u64) -> Result<Vec<DirEntry>, RefsError> {
445 let ot = object_table(image)?;
446 let root_block = ot
447 .lookup(dir_object_id)
448 .ok_or(RefsError::ObjectIdNotFound {
449 object_id: dir_object_id,
450 })?
451 .block_number;
452 walk_directory(image, root_block)
453}
454
455/// Walk the directory B+tree rooted at metadata block `root_block` and return
456/// its entries, building the container resolver from `image`'s resident
457/// metadata. Exposed for a caller that already has the tree-root block (e.g. a
458/// forensic walker resolving the root itself) so it need not re-enter through
459/// the object table.
460///
461/// # Errors
462///
463/// - [`RefsError::UnresolvedVirtualBlock`] if the root or any descended child is
464/// a virtual block outside the resident region.
465/// - [`RefsError::Truncated`] if a referenced page falls outside the image.
466pub fn walk_directory(image: &[u8], root_block: u64) -> Result<Vec<DirEntry>, RefsError> {
467 let resolver = ContainerResolver::from_resident_image(image, DEFAULT_BAND_CLUSTERS);
468 let mut out = Vec::new();
469 let mut visited = Vec::new();
470 descend(image, &resolver, root_block, 0, &mut visited, &mut out)?;
471 Ok(out)
472}
473
474/// Resolve an absolute path (`"/dir/file"`) to `(containing_directory_object_id,
475/// FileMetadata)` by descending the directory B+trees from the root (`0x600`).
476///
477/// Path components are matched by UTF-16-decoded name. Returns `None` if any
478/// component is missing, if the final component has no file/directory metadata,
479/// or for the bare root path `"/"` (the tree root itself has no entry record).
480/// A reachability wall en route (an unresolved virtual block) also yields `None`
481/// — the caller that needs to distinguish "absent" from "unreachable" uses
482/// [`list_dir`], which surfaces the [`RefsError`].
483#[must_use]
484pub fn find_by_path(image: &[u8], path: &str) -> Option<(u64, FileMetadata)> {
485 let components: Vec<&str> = path.split('/').filter(|c| !c.is_empty()).collect();
486 if components.is_empty() {
487 return None; // "/" — the root has no entry record.
488 }
489
490 let mut dir_id = REFS_ROOT_DIRECTORY_ID;
491 for (i, component) in components.iter().enumerate() {
492 let entries = list_dir(image, dir_id).ok()?;
493 let entry = entries.into_iter().find(|e| e.name == *component)?;
494 let is_last = i + 1 == components.len();
495 if is_last {
496 return entry.metadata.map(|md| (dir_id, md));
497 }
498 // Descend into the next directory; a non-directory mid-path fails.
499 dir_id = entry.object_id?;
500 }
501 None // cov:unreachable: components is non-empty (guarded above) so the final loop iteration always has is_last == true and returns at line 330; this fallthrough exists only to satisfy the return type.
502}
503
504#[cfg(test)]
505mod tests {
506 use super::*;
507
508 /// Build a minimal valid Minstore page carrying only a v3 header with the
509 /// given signature and self-block — enough for `page_answers_block` and the
510 /// resident-heuristic paths.
511 fn header_only_page(signature: [u8; 4], self_block: u64) -> Vec<u8> {
512 let mut page = vec![0u8; REFS_METADATA_PAGE_SIZE];
513 page[0..4].copy_from_slice(&signature);
514 page[SELF_BLOCK_OFFSET..SELF_BLOCK_OFFSET + 8].copy_from_slice(&self_block.to_le_bytes());
515 page
516 }
517
518 #[test]
519 fn page_answers_block_rejects_out_of_bounds_offset() {
520 // An offset past the end of the image cannot answer any block (no panic).
521 let image = vec![0u8; REFS_METADATA_PAGE_SIZE];
522 assert!(!page_answers_block(&image, REFS_METADATA_PAGE_SIZE, 0));
523 }
524
525 #[test]
526 fn page_answers_block_rejects_wrong_signature_and_wrong_self_block() {
527 // Wrong signature at a valid offset → not a Minstore page → false.
528 let not_msb = header_only_page(*b"SUPB", 7);
529 assert!(!page_answers_block(¬_msb, 0, 7));
530 // Right signature but a self-block that does not match the request → false.
531 let msb = header_only_page(*b"MSB+", 7);
532 assert!(!page_answers_block(&msb, 0, 8));
533 // Right signature AND matching self-block → true.
534 assert!(page_answers_block(&msb, 0, 7));
535 }
536
537 #[test]
538 fn resolve_block_offset_uses_resident_heuristic_when_resolver_cannot_map() {
539 // Place a Minstore page at cluster 8 (self-block 8) in an image whose only
540 // resident page underflows the resolver's base (so the container resolver
541 // learns NO base for band 0) — the resident heuristic must then land it.
542 let mut image = vec![0u8; 64 * CLUSTER_SIZE];
543 let page = header_only_page(*b"MSB+", 8);
544 image[8 * CLUSTER_SIZE..8 * CLUSTER_SIZE + REFS_METADATA_PAGE_SIZE].copy_from_slice(&page);
545 // A resolver with a zero band size has an empty base map, so
546 // resolve_virtual always returns None — forcing the resident-heuristic
547 // path (block 8 → cluster 8), which lands the page and round-trips.
548 let empty_resolver = ContainerResolver::from_resident_image(&[], 0);
549 let off = resolve_block_offset(&image, &empty_resolver, 8);
550 assert_eq!(
551 off,
552 Some(8 * CLUSTER_SIZE),
553 "resident heuristic lands block 8"
554 );
555 }
556
557 #[test]
558 fn resolve_block_offset_none_when_no_strategy_answers() {
559 // No page anywhere answers block 8 → both strategies reject → None.
560 let image = vec![0u8; 64 * CLUSTER_SIZE];
561 let empty_resolver = ContainerResolver::from_resident_image(&[], 0);
562 assert_eq!(resolve_block_offset(&image, &empty_resolver, 8), None);
563 }
564
565 #[test]
566 fn descend_branch_row_with_short_value_is_skipped_not_panicked() {
567 // A branch node whose row value is shorter than the 8-byte child block
568 // number must be skipped (never over-read / panic). Build a branch page at
569 // cluster 4 (self-block 4) with one row whose value is 4 bytes.
570 let mut page = vec![0u8; REFS_METADATA_PAGE_SIZE];
571 page[0..4].copy_from_slice(b"MSB+");
572 page[SELF_BLOCK_OFFSET..SELF_BLOCK_OFFSET + 8].copy_from_slice(&4u64.to_le_bytes());
573 let node_hdr = 0x100usize;
574 page[0x50..0x54].copy_from_slice(&((node_hdr - 0x50) as u32).to_le_bytes());
575 let rec = node_hdr + 32;
576 let key = [0u8; 4];
577 let value = [0u8; 4]; // < 8 bytes → the short-value guard fires
578 let key_off = 16u16;
579 let val_off = key_off + key.len() as u16;
580 let rec_size = (val_off as usize + value.len()) as u32;
581 page[rec..rec + 4].copy_from_slice(&rec_size.to_le_bytes());
582 page[rec + 4..rec + 6].copy_from_slice(&key_off.to_le_bytes());
583 page[rec + 6..rec + 8].copy_from_slice(&(key.len() as u16).to_le_bytes());
584 page[rec + 10..rec + 12].copy_from_slice(&val_off.to_le_bytes());
585 page[rec + 12..rec + 14].copy_from_slice(&(value.len() as u16).to_le_bytes());
586 let roff_abs = node_hdr + 0x2000;
587 page[roff_abs..roff_abs + 4]
588 .copy_from_slice(&(0xffff_0000u32 | ((rec - node_hdr) as u32 & 0xffff)).to_le_bytes());
589 page[node_hdr + 13] = 0x01; // branch
590 page[node_hdr + 16..node_hdr + 20].copy_from_slice(&0x2000u32.to_le_bytes());
591 page[node_hdr + 20..node_hdr + 24].copy_from_slice(&1u32.to_le_bytes());
592
593 let mut image = vec![0u8; 16 * CLUSTER_SIZE];
594 image[4 * CLUSTER_SIZE..4 * CLUSTER_SIZE + REFS_METADATA_PAGE_SIZE].copy_from_slice(&page);
595 // block 4 resolves via the resident heuristic (block==cluster); the branch
596 // has one short-value row that is skipped, yielding an empty (not panicked)
597 // listing.
598 let entries =
599 walk_directory(&image, 4).expect("walk does not panic on a short branch value");
600 assert!(entries.is_empty(), "the short-value branch row was skipped");
601 }
602}