Skip to main content

apfs_core/
volume.rs

1//! Volume superblock (`apfs_superblock_t`, magic `APFS_MAGIC = 'BSPA'` →
2//! "APSB" → LE `0x42535041`) and per-volume navigation roots.
3//!
4//! Each volume's APSB (Apple *APFS Reference*, `apfs_superblock_t`) carries the
5//! volume's own object map (`apfs_omap_oid`), the file-system tree root
6//! (`apfs_root_tree_oid`, a virtual oid resolved through the volume omap), the
7//! extent-reference tree (`apfs_extentref_tree_oid`), the snapshot-metadata tree
8//! (`apfs_snap_meta_tree_oid`), the volume role/flags, `apfs_volname`, and
9//! `apfs_fs_index`.
10//!
11//! Field offsets (little-endian on disk), after the 32-byte `obj_phys_t` header
12//! — verified verbatim against libfsapfs `fsapfs_volume_superblock` and the raw
13//! self-minted fixture:
14//!
15//! | off | size | field                                |
16//! |-----|------|--------------------------------------|
17//! | 32  | 4    | `apfs_magic` ("APSB")                |
18//! | 36  | 4    | `apfs_fs_index`                      |
19//! | 40  | 8    | `apfs_features` (compatible)         |
20//! | 48  | 8    | `apfs_readonly_compatible_features`  |
21//! | 56  | 8    | `apfs_incompatible_features`         |
22//! | 116 | 4    | `apfs_root_tree_type`                |
23//! | 128 | 8    | `apfs_omap_oid` (volume omap block)  |
24//! | 136 | 8    | `apfs_root_tree_oid` (virtual)       |
25//! | 144 | 8    | `apfs_extentref_tree_oid`            |
26//! | 152 | 8    | `apfs_snap_meta_tree_oid`            |
27//! | 240 | 16   | `apfs_vol_uuid`                      |
28//! | 256 | 8    | `apfs_fs_flags`                      |
29//! | 704 | 256  | `apfs_volname[APFS_VOLNAME_LEN]`     |
30
31use crate::object::{fletcher64_checksum, fletcher64_stored, ObjPhys};
32
33/// Volume superblock magic `APFS_MAGIC` ('BSPA', "APSB" in a hex dump).
34pub const APFS_MAGIC: u32 = 0x4253_5041;
35
36/// Object type code `OBJECT_TYPE_FS 0xd` — the APSB object type (low 16 bits of
37/// `o_type`).
38const OBJECT_TYPE_FS: u16 = 0xd;
39
40// `apfs_superblock_t` field offsets after the 32-byte `obj_phys_t` header.
41const OFF_MAGIC: usize = 32;
42const OFF_FS_INDEX: usize = 36;
43const OFF_FEATURES: usize = 40;
44const OFF_RO_COMPAT_FEATURES: usize = 48;
45const OFF_INCOMPAT_FEATURES: usize = 56;
46const OFF_ROOT_TREE_TYPE: usize = 116;
47const OFF_OMAP_OID: usize = 128;
48const OFF_ROOT_TREE_OID: usize = 136;
49const OFF_EXTENTREF_TREE_OID: usize = 144;
50const OFF_SNAP_META_TREE_OID: usize = 152;
51const OFF_VOL_UUID: usize = 240;
52const OFF_FS_FLAGS: usize = 256;
53const OFF_VOLNAME: usize = 704;
54
55/// `APFS_VOLNAME_LEN` (Apple) — the fixed `apfs_volname` field size in bytes.
56const VOLNAME_LEN: usize = 256;
57
58/// Minimum readable APSB length: header through the volume name field.
59const APSB_MIN_LEN: usize = OFF_VOLNAME + VOLNAME_LEN;
60
61/// Build the `apfs_superblock` [`crate::ApfsError::UnexpectedObjectType`] error
62/// (`expected`/`found` are the offending values) — shared by the short-block,
63/// wrong-type, and wrong-magic guards so the error shape lives in one place.
64fn apsb_bad_type(expected: u32, found: u32) -> crate::ApfsError {
65    crate::ApfsError::UnexpectedObjectType {
66        structure: "apfs_superblock",
67        expected,
68        found,
69    }
70}
71
72/// A parsed volume superblock (subset; `#[non_exhaustive]` for additive growth).
73///
74/// The fs-tree navigation entry points ([`Self::root_tree_oid`] /
75/// [`Self::omap_oid`]) are consumed by [`crate::dir`] for name→inode path
76/// resolution.
77#[derive(Debug, Clone)]
78#[non_exhaustive]
79pub struct ApfsVolume {
80    oid: u64,
81    xid: u64,
82    fs_index: u32,
83    features: u64,
84    readonly_compatible_features: u64,
85    incompatible_features: u64,
86    root_tree_type: u32,
87    omap_oid: u64,
88    root_tree_oid: u64,
89    extentref_tree_oid: u64,
90    snap_meta_tree_oid: u64,
91    uuid: [u8; 16],
92    fs_flags: u64,
93    name: String,
94}
95
96impl ApfsVolume {
97    /// Parse and validate an APSB block (magic-by-type + signature + Fletcher-64
98    /// checksum) before trusting any field.
99    ///
100    /// # Errors
101    /// [`crate::ApfsError::UnexpectedObjectType`] on a short block, a non-FS
102    /// object type, or a wrong `apfs_magic` signature (carrying the offending
103    /// value); [`crate::ApfsError::ChecksumMismatch`] on a Fletcher-64 failure.
104    pub fn parse(block: &[u8]) -> crate::Result<Self> {
105        if block.len() < APSB_MIN_LEN {
106            return Err(apsb_bad_type(APFS_MAGIC, 0));
107        }
108        // Object-type gate: the block must be an FS (volume superblock) object.
109        let Some(hdr) = ObjPhys::parse(block) else {
110            // cov:unreachable: len checked >= APSB_MIN_LEN > OBJ_PHYS_LEN, so
111            // ObjPhys::parse (None only on len < OBJ_PHYS_LEN) is always Some.
112            return Err(apsb_bad_type(APFS_MAGIC, 0)); // cov:unreachable
113        };
114        if hdr.obj_type() != OBJECT_TYPE_FS {
115            return Err(apsb_bad_type(u32::from(OBJECT_TYPE_FS), hdr.obj_type_raw));
116        }
117
118        // Signature gate: apfs_magic == "APSB".
119        let magic = crate::bytes::le_u32(block, OFF_MAGIC);
120        if magic != APFS_MAGIC {
121            return Err(apsb_bad_type(APFS_MAGIC, magic));
122        }
123
124        // Checksum gate before trusting the tree oids.
125        let stored = fletcher64_stored(block);
126        let computed = fletcher64_checksum(block);
127        if stored != computed {
128            return Err(crate::ApfsError::ChecksumMismatch {
129                block: hdr.oid,
130                stored,
131                computed,
132            });
133        }
134
135        // Volume name: a NUL-terminated UTF-8 string within the 256-byte field.
136        let name = decode_volname(block, OFF_VOLNAME, VOLNAME_LEN);
137
138        Ok(Self {
139            oid: hdr.oid,
140            xid: hdr.xid,
141            fs_index: crate::bytes::le_u32(block, OFF_FS_INDEX),
142            features: crate::bytes::le_u64(block, OFF_FEATURES),
143            readonly_compatible_features: crate::bytes::le_u64(block, OFF_RO_COMPAT_FEATURES),
144            incompatible_features: crate::bytes::le_u64(block, OFF_INCOMPAT_FEATURES),
145            root_tree_type: crate::bytes::le_u32(block, OFF_ROOT_TREE_TYPE),
146            omap_oid: crate::bytes::le_u64(block, OFF_OMAP_OID),
147            root_tree_oid: crate::bytes::le_u64(block, OFF_ROOT_TREE_OID),
148            extentref_tree_oid: crate::bytes::le_u64(block, OFF_EXTENTREF_TREE_OID),
149            snap_meta_tree_oid: crate::bytes::le_u64(block, OFF_SNAP_META_TREE_OID),
150            uuid: crate::bytes::arr::<16>(block, OFF_VOL_UUID),
151            fs_flags: crate::bytes::le_u64(block, OFF_FS_FLAGS),
152            name,
153        })
154    }
155
156    /// The volume superblock object id (`nx_o.o_oid`).
157    #[must_use]
158    pub fn oid(&self) -> u64 {
159        self.oid
160    }
161
162    /// The transaction id of this volume superblock (`nx_o.o_xid`). Used as the
163    /// xid for resolving virtual fs-tree oids through the volume omap.
164    #[must_use]
165    pub fn xid(&self) -> u64 {
166        self.xid
167    }
168
169    /// `apfs_fs_index` — this volume's index within the container's `nx_fs_oid[]`.
170    #[must_use]
171    pub fn fs_index(&self) -> u32 {
172        self.fs_index
173    }
174
175    /// `apfs_features` — compatible feature flags.
176    #[must_use]
177    pub fn features(&self) -> u64 {
178        self.features
179    }
180
181    /// `apfs_readonly_compatible_features` — read-only-compatible feature flags.
182    #[must_use]
183    pub fn readonly_compatible_features(&self) -> u64 {
184        self.readonly_compatible_features
185    }
186
187    /// `apfs_incompatible_features` — incompatible feature flags (the
188    /// case-insensitivity / normalization bits affect directory-name matching).
189    #[must_use]
190    pub fn incompatible_features(&self) -> u64 {
191        self.incompatible_features
192    }
193
194    /// `apfs_root_tree_type` — the storage-flag + object-type word of the
195    /// file-system root tree (the root tree is virtual, so its high bits carry
196    /// the virtual storage flag).
197    #[must_use]
198    pub fn root_tree_type(&self) -> u32 {
199        self.root_tree_type
200    }
201
202    /// `apfs_omap_oid` — the block address of this volume's object map
203    /// (`omap_phys_t`, a physical object). The fs-tree's virtual oids resolve
204    /// through this omap.
205    #[must_use]
206    pub fn omap_oid(&self) -> u64 {
207        self.omap_oid
208    }
209
210    /// Return this volume superblock with its `omap_oid` replaced.
211    ///
212    /// A *snapshot's* frozen `apfs_superblock_t` carries `apfs_omap_oid == 0`:
213    /// snapshots have no object map of their own and are read through the
214    /// **live** volume's omap, resolved at the snapshot's `xid` (the omap B-tree
215    /// retains historical `(oid, xid) → paddr` mappings that snapshots pin). A
216    /// point-in-time view therefore keeps the frozen superblock's `root_tree_oid`
217    /// and `xid` but borrows the live volume's omap. See
218    /// [`crate::snapshot::mount_snapshot`].
219    #[must_use]
220    pub fn with_omap_oid(mut self, omap_oid: u64) -> Self {
221        self.omap_oid = omap_oid;
222        self
223    }
224
225    /// `apfs_root_tree_oid` — the **virtual** oid of the file-system tree root
226    /// (`FSTREE`). Resolve it through the volume omap ([`Self::omap_oid`]) at
227    /// [`Self::xid`] to get the root node's physical block address.
228    #[must_use]
229    pub fn root_tree_oid(&self) -> u64 {
230        self.root_tree_oid
231    }
232
233    /// `apfs_extentref_tree_oid` — the extent-reference tree oid.
234    #[must_use]
235    pub fn extentref_tree_oid(&self) -> u64 {
236        self.extentref_tree_oid
237    }
238
239    /// `apfs_snap_meta_tree_oid` — the snapshot-metadata tree oid.
240    #[must_use]
241    pub fn snap_meta_tree_oid(&self) -> u64 {
242        self.snap_meta_tree_oid
243    }
244
245    /// `apfs_vol_uuid` — the volume UUID.
246    #[must_use]
247    pub fn uuid(&self) -> [u8; 16] {
248        self.uuid
249    }
250
251    /// `apfs_fs_flags` — volume flags (e.g. encryption state bits).
252    #[must_use]
253    pub fn fs_flags(&self) -> u64 {
254        self.fs_flags
255    }
256
257    /// The volume name (`apfs_volname`).
258    #[must_use]
259    pub fn name(&self) -> &str {
260        &self.name
261    }
262}
263
264/// Decode a fixed-width, NUL-terminated UTF-8 volume name field. Bytes after the
265/// first NUL (or the whole field if there is none) are dropped; invalid UTF-8 is
266/// replaced (never panics).
267fn decode_volname(block: &[u8], offset: usize, len: usize) -> String {
268    let Some(field) = block.get(offset..offset + len) else {
269        return String::new(); // cov:unreachable: caller checks block.len() >= APSB_MIN_LEN
270    };
271    let end = field.iter().position(|&b| b == 0).unwrap_or(field.len());
272    String::from_utf8_lossy(&field[..end]).into_owned()
273}