Skip to main content

refs_core/
superblock.rs

1//! ReFS superblock (`SUPB`) — the level-0 metadata block, and the generic
2//! self-describing metadata-block header it shares with every v3 metadata block.
3//!
4//! ReFS stores metadata in fixed-size self-describing blocks. The block header
5//! (verified against a real ReFS v3.14 volume — see tests/data/README.md, and
6//! consistent with libyal `libfsrefs`) begins with a four-byte block signature,
7//! and records its own block number at offset `0x20`:
8//!
9//! ```text
10//! off  size  field                              (SUPB @ cluster 30)
11//!   0    4   block signature "SUPB"/"CHKP"/"MSB+"
12//!   4    4   header version/kind                 (2)
13//!   c    4   metadata checksum (CRC64 low word)
14//!  20    8   self-describing block number        (== 30 for this superblock)
15//! ```
16//!
17//! P0 locates the superblock at the fixed cluster [`REFS_SUPERBLOCK_CLUSTER`],
18//! validates its `SUPB` signature (fail-loud with the offending bytes), and
19//! exposes the self-describing block number. Resolving the checkpoint (`CHKP`)
20//! reference and walking the Minstore B+-tree are later phases: the v3 SUPB
21//! internal layout beyond the header is not reliably documented in the
22//! reverse-engineered references, so P0 does not guess at it.
23
24use crate::bytes::{ascii, le_u64};
25use crate::error::RefsError;
26
27/// The `SUPB` block signature for the ReFS superblock (metadata level 0).
28pub const SUPB_SIGNATURE: &[u8; 4] = b"SUPB";
29
30/// The fixed cluster at which the primary ReFS superblock lives, counted from
31/// the start of the volume. `30` is the well-known reverse-engineered
32/// convention (byte offset `30 * cluster_size`; `0x1e000` at a 4096-byte
33/// cluster), confirmed on the minted v3.14 volume.
34pub const REFS_SUPERBLOCK_CLUSTER: u64 = 30;
35
36/// Offset of the self-describing block number within a v3 metadata-block header.
37const BLOCK_NUMBER_OFFSET: usize = 0x20;
38
39/// Minimum bytes of a metadata-block header this parser reads (through the
40/// self-describing block number at `0x20`, +8 = 40).
41const BLOCK_HEADER_MIN_LEN: usize = 40;
42
43/// A ReFS v3 self-describing metadata-block header: the four-byte block
44/// signature plus the block's own block number.
45///
46/// `#[non_exhaustive]` so later phases add the checksum descriptor and the four
47/// redundancy block numbers without a breaking change.
48#[derive(Debug, Clone, PartialEq, Eq)]
49#[non_exhaustive]
50pub struct MetadataBlockRef {
51    /// The four-byte block signature (`SUPB`/`CHKP`/`MSB+`), validated against
52    /// the caller's `expected` signature.
53    pub signature: [u8; 4],
54    /// The block's own (self-describing) block number, at header offset `0x20`.
55    pub block_number: u64,
56}
57
58impl MetadataBlockRef {
59    /// Parse and validate a metadata-block header at the start of `data`.
60    ///
61    /// `expected` is the signature the caller requires (e.g. `"SUPB"`); `offset`
62    /// is the block's absolute byte position in the image, carried into the
63    /// error so a mismatch names *what* was there and *where*.
64    ///
65    /// # Errors
66    ///
67    /// - [`RefsError::BadBlockSignature`] if the first four bytes are not
68    ///   `expected` — the offending bytes and offset are carried in the error.
69    /// - [`RefsError::Truncated`] if `data` is shorter than the header fields.
70    pub fn parse(data: &[u8], expected: &'static str, offset: u64) -> Result<Self, RefsError> {
71        // Validate the signature before length so a wrong-block error names the
72        // offending bytes even on a short buffer (fail loud with the value).
73        let mut signature = [0u8; 4];
74        if let Some(s) = data.get(0..4) {
75            signature.copy_from_slice(s);
76        }
77        if signature.as_slice() != expected.as_bytes() {
78            return Err(RefsError::BadBlockSignature {
79                found: signature,
80                found_ascii: ascii(&signature),
81                expected,
82                offset,
83            });
84        }
85
86        if data.len() < BLOCK_HEADER_MIN_LEN {
87            return Err(RefsError::Truncated {
88                structure: "metadata-block header",
89                need: BLOCK_HEADER_MIN_LEN,
90                have: data.len(),
91            });
92        }
93
94        Ok(Self {
95            signature,
96            block_number: le_u64(data, BLOCK_NUMBER_OFFSET),
97        })
98    }
99}
100
101/// The parsed ReFS superblock (`SUPB`, metadata level 0).
102///
103/// P0 carries only the self-describing block header; the checkpoint reference
104/// and the object/container-table pointers it holds are decoded in later phases.
105#[derive(Debug, Clone, PartialEq, Eq)]
106#[non_exhaustive]
107pub struct Superblock {
108    /// The self-describing metadata-block header (`SUPB`).
109    pub block: MetadataBlockRef,
110}
111
112impl Superblock {
113    /// Parse the superblock at byte `offset` in a whole-image buffer `data`.
114    ///
115    /// Slices from `offset` and validates the `SUPB` block header. The caller
116    /// obtains `offset` from [`crate::BootSector::superblock_offset`].
117    ///
118    /// # Errors
119    ///
120    /// - [`RefsError::Truncated`] if `offset` lies past the end of `data`.
121    /// - Any error from [`MetadataBlockRef::parse`] (bad signature, short
122    ///   header).
123    pub fn parse_at(data: &[u8], offset: u64) -> Result<Self, RefsError> {
124        let start = usize::try_from(offset).unwrap_or(usize::MAX);
125        let slice = data.get(start..).ok_or(RefsError::Truncated {
126            structure: "superblock (image slice)",
127            need: start,
128            have: data.len(),
129        })?;
130        let block = MetadataBlockRef::parse(slice, "SUPB", offset)?;
131        Ok(Self { block })
132    }
133}