Skip to main content

file_system/mbr/
mod.rs

1/*!
2Master Boot Record (MBR) module.
3
4This module provides functionality for working with MBR partition tables
5backed by the `mbrman` crate.
6*/
7
8use core::fmt;
9
10use crate::{DirectBlockDevice, PartitionDevice, Position, Size};
11
12mod error;
13mod partition;
14
15pub use error::*;
16pub use partition::*;
17
18#[cfg(test)]
19use crate::MemoryDevice;
20
21/// Master Boot Record structure (512 bytes).
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct Mbr {
24    /// Bootstrap code area (440 bytes).
25    pub bootstrap_code: [u8; 440],
26    /// 32-bit disk signature.
27    pub disk_signature: [u8; 4],
28    /// Copy protected bytes.
29    pub copy_protected: [u8; 2],
30    /// Partition table entries.
31    pub partitions: [PartitionEntry; 4],
32    /// Boot signature bytes (`[0x55, 0xAA]`).
33    pub boot_signature: [u8; 2],
34}
35
36impl Mbr {
37    /// Size of MBR in bytes.
38    pub const SIZE: usize = 512;
39    /// Standard partition alignment block offset.
40    pub const MINIMUM_START_BLOCK: Size = 2048;
41
42    /// Create a new empty MBR with a specified 32-bit disk signature.
43    pub fn new_with_signature(disk_signature: u32) -> Self {
44        Self {
45            bootstrap_code: [0u8; 440],
46            disk_signature: disk_signature.to_le_bytes(),
47            copy_protected: [0u8; 2],
48            partitions: [PartitionEntry::default(); 4],
49            boot_signature: [0x55, 0xAA],
50        }
51    }
52
53    /// Parse an MBR from a 512-byte raw sector.
54    pub fn from_bytes(data: &[u8]) -> Result<Self> {
55        let sector: &[u8; Self::SIZE] = data
56            .get(..Self::SIZE)
57            .and_then(|s| s.try_into().ok())
58            .ok_or(Error::BufferTooSmall)?;
59
60        let header = mbrman::MBRHeader::from_bytes(sector).map_err(Error::from)?;
61        Ok(Self {
62            bootstrap_code: header.bootstrap_code,
63            disk_signature: header.disk_signature,
64            copy_protected: header.copy_protected,
65            partitions: [
66                PartitionEntry::from_mbrman(&header.partition_1),
67                PartitionEntry::from_mbrman(&header.partition_2),
68                PartitionEntry::from_mbrman(&header.partition_3),
69                PartitionEntry::from_mbrman(&header.partition_4),
70            ],
71            boot_signature: header.boot_signature,
72        })
73    }
74
75    /// Encode the MBR into a 512-byte sector.
76    pub fn to_bytes(&self) -> Result<[u8; Self::SIZE]> {
77        let [p1, p2, p3, p4] = self.partitions;
78        Ok(mbrman::MBRHeader {
79            bootstrap_code: self.bootstrap_code,
80            disk_signature: self.disk_signature,
81            copy_protected: self.copy_protected,
82            partition_1: p1.to_mbrman(),
83            partition_2: p2.to_mbrman(),
84            partition_3: p3.to_mbrman(),
85            partition_4: p4.to_mbrman(),
86            boot_signature: self.boot_signature,
87        }
88        .to_bytes()?)
89    }
90
91    /// Read and parse the MBR from a block device.
92    pub fn read_from_device(device: &impl DirectBlockDevice) -> Result<Self> {
93        device.open()?;
94        let mut buffer = [0u8; Self::SIZE];
95        let result = (|| {
96            device.set_position(0, &Position::Start(0))?;
97            if device.read_sync(&mut buffer, 0)? < Self::SIZE {
98                return Err(Error::ReadFailed);
99            }
100            Self::from_bytes(&buffer)
101        })();
102        let _ = device.close();
103        result
104    }
105
106    /// Write the MBR to sector 0 of a block device.
107    pub fn write_to_device(&self, device: &impl DirectBlockDevice) -> Result<()> {
108        let buffer = self.to_bytes()?;
109        device.open()?;
110        let result = (|| {
111            device.set_position(0, &Position::Start(0))?;
112            if device.write_sync(&buffer, 0)? < Self::SIZE {
113                return Err(Error::WriteFailed);
114            }
115            Ok(())
116        })();
117        let _ = device.close();
118        result
119    }
120
121    /// Check if the MBR signature matches `[0x55, 0xAA]`.
122    pub fn is_valid(&self) -> bool {
123        self.boot_signature == [0x55, 0xAA]
124    }
125
126    /// Get the 32-bit disk signature.
127    pub fn get_disk_signature(&self) -> u32 {
128        u32::from_le_bytes(self.disk_signature)
129    }
130
131    /// Validate MBR signature, partition overlaps, and single-bootable rule.
132    pub fn validate(&self) -> Result<()> {
133        if !self.is_valid() {
134            return Err(Error::InvalidSignature);
135        }
136        for (i, p1) in self.partitions.iter().enumerate() {
137            if p1.is_valid()
138                && self.partitions[i + 1..]
139                    .iter()
140                    .any(|p2| p2.is_valid() && p1.overlaps_with(p2))
141            {
142                return Err(Error::OverlappingPartitions);
143            }
144        }
145        if self.partitions.iter().filter(|p| p.bootable).count() > 1 {
146            return Err(Error::MultipleBootablePartitions);
147        }
148        Ok(())
149    }
150
151    /// Format a disk with a specific disk signature and single partition, returning a `PartitionDevice`.
152    pub fn format_disk_with_signature_and_partition<'a, D: DirectBlockDevice>(
153        device: &'a D,
154        disk_signature: u32,
155        partition_type: PartitionKind,
156    ) -> Result<PartitionDevice<'a, D>> {
157        device.open()?;
158        let block_count = device.get_block_count()?;
159        device.close()?;
160
161        if block_count < Self::MINIMUM_START_BLOCK {
162            return Err(Error::DeviceTooSmall);
163        }
164
165        let partition_block_count = (block_count - Self::MINIMUM_START_BLOCK) as u32;
166        if partition_block_count == 0 {
167            return Err(Error::DeviceTooSmall);
168        }
169
170        let mut mbr = Self::new_with_signature(disk_signature);
171        mbr.partitions[0] = PartitionEntry {
172            bootable: true,
173            kind: partition_type,
174            start_block: Self::MINIMUM_START_BLOCK as u32,
175            block_count: partition_block_count,
176            first_chs: mbrman::CHS::empty(),
177            last_chs: mbrman::CHS::empty(),
178        };
179        mbr.write_to_device(device)?;
180
181        create_partition_device(device, &mbr.partitions[0])
182    }
183
184    /// Find an existing partition with the specified disk signature, or format the disk.
185    pub fn find_or_create_partition_with_signature<'a, D: DirectBlockDevice>(
186        device: &'a D,
187        target_signature: u32,
188        partition_type: PartitionKind,
189    ) -> Result<PartitionDevice<'a, D>> {
190        if let Ok(existing_mbr) = Self::read_from_device(device)
191            && existing_mbr.get_disk_signature() == target_signature
192            && existing_mbr.is_valid()
193            && let Some(valid_partition) = existing_mbr.partitions.iter().find(|p| p.is_valid())
194        {
195            return create_partition_device(device, valid_partition);
196        }
197
198        Self::format_disk_with_signature_and_partition(device, target_signature, partition_type)
199    }
200}
201
202impl fmt::Display for Mbr {
203    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
204        write!(
205            formatter,
206            "MBR (signature: 0x{:08X}, partitions: {})",
207            self.get_disk_signature(),
208            self.partitions.iter().filter(|p| p.is_valid()).count()
209        )
210    }
211}
212
213/// Create a partition device from an MBR partition entry.
214pub fn create_partition_device<'a, D: DirectBlockDevice>(
215    device: &'a D,
216    partition: &PartitionEntry,
217) -> Result<PartitionDevice<'a, D>> {
218    if !partition.is_valid() {
219        return Err(Error::InvalidPartition);
220    }
221    device.open()?;
222    let block_size = device.get_block_size()?;
223    Ok(PartitionDevice::new(
224        device,
225        partition.start_block as _,
226        partition.block_count as _,
227        block_size,
228    ))
229}
230
231#[cfg(test)]
232mod tests {
233    use super::*;
234
235    fn create_legacy_sample_mbr_bytes() -> [u8; 512] {
236        let mut data = [0u8; 512];
237        data[440..444].copy_from_slice(&0x12345678u32.to_le_bytes());
238        // Partition 1: FAT32 LBA (0x0C), bootable, starts at LBA 2048, size 204800 sectors
239        data[446] = 0x80;
240        data[450] = 0x0C;
241        data[454..458].copy_from_slice(&2048u32.to_le_bytes());
242        data[458..462].copy_from_slice(&204800u32.to_le_bytes());
243        // Partition 2: Linux (0x83), non-bootable, starts at LBA 206848, size 102400 sectors
244        data[466] = 0x83;
245        data[470..474].copy_from_slice(&206848u32.to_le_bytes());
246        data[474..478].copy_from_slice(&102400u32.to_le_bytes());
247        data[510..512].copy_from_slice(&[0x55, 0xAA]);
248        data
249    }
250
251    #[test]
252    fn test_legacy_golden_bytes_round_trip() {
253        let golden = create_legacy_sample_mbr_bytes();
254        let mbr = Mbr::from_bytes(&golden).expect("parse legacy golden bytes");
255        assert_eq!(mbr.get_disk_signature(), 0x12345678);
256        assert!(mbr.is_valid() && mbr.validate().is_ok());
257
258        assert!(mbr.partitions[0].bootable);
259        assert_eq!(mbr.partitions[0].kind, PartitionKind::from(0x0C));
260        assert_eq!(mbr.partitions[0].start_block, 2048);
261        assert_eq!(mbr.partitions[0].block_count, 204800);
262
263        assert!(!mbr.partitions[1].bootable);
264        assert_eq!(mbr.partitions[1].kind, PartitionKind::from(0x83));
265        assert_eq!(mbr.partitions[1].start_block, 206848);
266        assert_eq!(mbr.partitions[1].block_count, 102400);
267
268        assert!(!mbr.partitions[2].is_valid() && !mbr.partitions[3].is_valid());
269
270        let serialized = mbr.to_bytes().expect("serialize");
271        assert_eq!(serialized, golden);
272
273        let mbrman_header = mbrman::MBRHeader::from_bytes(&serialized).expect("mbrman parse");
274        assert_eq!(mbrman_header.to_bytes().expect("mbrman to_bytes"), golden);
275    }
276
277    #[test]
278    fn test_xila_formatted_mbr_round_trip() {
279        let device = MemoryDevice::<512>::new(4 * 1024 * 1024);
280        let partition =
281            Mbr::format_disk_with_signature_and_partition(&device, 0x616C6958, PartitionKind::Xila)
282                .expect("format disk");
283
284        assert_eq!(partition.get_start_lba(), 2048);
285        assert_eq!(partition.get_block_count(), 8192 - 2048);
286
287        let read_back = Mbr::read_from_device(&device).expect("read MBR");
288        assert_eq!(read_back.get_disk_signature(), 0x616C6958);
289        assert!(read_back.validate().is_ok());
290        assert_eq!(read_back.partitions[0].kind, PartitionKind::Xila);
291        assert!(read_back.partitions[0].bootable);
292        assert_eq!(read_back.partitions[0].start_block, 2048);
293        assert_eq!(read_back.partitions[0].block_count, 6144);
294    }
295
296    #[test]
297    fn test_validation_rules() {
298        let mut mbr = Mbr::new_with_signature(0x12345678);
299        assert!(mbr.validate().is_ok());
300
301        // Overlapping partitions
302        mbr.partitions[0] = PartitionEntry {
303            bootable: false,
304            kind: PartitionKind::Other(0x0C),
305            start_block: 1000,
306            block_count: 1000,
307            ..Default::default()
308        };
309        mbr.partitions[1] = PartitionEntry {
310            bootable: false,
311            kind: PartitionKind::Other(0x83),
312            start_block: 1500,
313            block_count: 1000,
314            ..Default::default()
315        };
316        assert_eq!(mbr.validate(), Err(Error::OverlappingPartitions));
317
318        // Multiple bootable partitions
319        mbr.partitions[1].start_block = 2500;
320        mbr.partitions[1].bootable = true;
321        mbr.partitions[0].bootable = true;
322        assert_eq!(mbr.validate(), Err(Error::MultipleBootablePartitions));
323
324        // Invalid signature
325        mbr.boot_signature = [0, 0];
326        assert_eq!(mbr.validate(), Err(Error::InvalidSignature));
327    }
328
329    #[test]
330    fn test_find_or_create_partition_with_signature() {
331        let device = MemoryDevice::<512>::new(4 * 1024 * 1024);
332        let p1 =
333            Mbr::find_or_create_partition_with_signature(&device, 0x12345678, PartitionKind::Xila)
334                .expect("format disk");
335        assert_eq!(p1.get_start_lba(), 2048);
336
337        let p2 =
338            Mbr::find_or_create_partition_with_signature(&device, 0x12345678, PartitionKind::Xila)
339                .expect("find partition");
340        assert_eq!(p2.get_start_lba(), 2048);
341    }
342}