hadris-part 2.2.0

Partition table support for MBR, GPT, and Hybrid MBR
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
//! Hybrid MBR support for dual BIOS/UEFI bootable disks.
//!
//! A Hybrid MBR is a special MBR that contains both a protective entry (type 0xEE)
//! and regular MBR partition entries that mirror selected GPT partitions. This allows
//! the disk to be bootable on both BIOS and UEFI systems.
//!
//! # Warning
//!
//! Hybrid MBRs are not part of the UEFI specification and can cause issues with
//! some operating systems. Use with caution.

#[cfg(feature = "alloc")]
extern crate alloc;

#[cfg(feature = "alloc")]
use alloc::vec::Vec;

use crate::error::{Error, Result};
use crate::gpt::GptPartitionEntry;
use crate::mbr::{Chs, MasterBootRecord, MbrPartition, MbrPartitionTable, MbrPartitionType};
use endian_num::Le;

/// A partition to be mirrored from GPT to MBR in a hybrid configuration.
#[derive(Debug, Clone, Copy)]
pub struct MirroredPartition {
    /// Index of the GPT partition to mirror (0-based).
    pub gpt_partition_index: u32,
    /// MBR partition type to use.
    pub mbr_type: MbrPartitionType,
    /// Whether to mark this partition as bootable (active).
    pub bootable: bool,
}

impl MirroredPartition {
    /// Creates a new mirrored partition configuration.
    pub const fn new(gpt_index: u32, mbr_type: MbrPartitionType) -> Self {
        Self {
            gpt_partition_index: gpt_index,
            mbr_type,
            bootable: false,
        }
    }

    /// Sets the bootable flag.
    pub const fn with_bootable(mut self, bootable: bool) -> Self {
        self.bootable = bootable;
        self
    }
}

/// Configuration for a Hybrid MBR.
///
/// A Hybrid MBR contains:
/// - A protective MBR entry (type 0xEE) covering either the entire disk or the
///   area not covered by mirrored partitions
/// - Up to 3 mirrored partition entries (MBR can only have 4 entries total)
#[derive(Debug, Clone, Default)]
pub struct HybridMbrConfig {
    /// Index of the MBR slot for the protective partition (0-3).
    /// Usually 0 or 3 (first or last).
    pub protective_slot: usize,
    /// Partitions to mirror from GPT to MBR (max 3).
    #[cfg(feature = "alloc")]
    pub mirrored: Vec<MirroredPartition>,
    /// Partitions to mirror from GPT to MBR (max 3).
    #[cfg(not(feature = "alloc"))]
    pub mirrored: [Option<MirroredPartition>; 3],
    /// Number of mirrored partitions (used in no-alloc mode).
    #[cfg(not(feature = "alloc"))]
    pub mirrored_count: usize,
}

impl HybridMbrConfig {
    /// Creates a new empty Hybrid MBR configuration.
    pub const fn new() -> Self {
        Self {
            protective_slot: 0,
            #[cfg(feature = "alloc")]
            mirrored: Vec::new(),
            #[cfg(not(feature = "alloc"))]
            mirrored: [None, None, None],
            #[cfg(not(feature = "alloc"))]
            mirrored_count: 0,
        }
    }

    /// Sets the protective partition slot index.
    pub const fn with_protective_slot(mut self, slot: usize) -> Self {
        self.protective_slot = slot;
        self
    }

    /// Adds a mirrored partition.
    #[cfg(feature = "alloc")]
    pub fn add_mirrored(mut self, partition: MirroredPartition) -> Self {
        self.mirrored.push(partition);
        self
    }

    /// Adds a mirrored partition.
    #[cfg(not(feature = "alloc"))]
    pub fn add_mirrored(mut self, partition: MirroredPartition) -> Self {
        if self.mirrored_count < 3 {
            self.mirrored[self.mirrored_count] = Some(partition);
            self.mirrored_count += 1;
        }
        self
    }

    /// Returns the number of mirrored partitions.
    #[cfg(feature = "alloc")]
    pub fn mirrored_count(&self) -> usize {
        self.mirrored.len()
    }

    /// Returns the number of mirrored partitions.
    #[cfg(not(feature = "alloc"))]
    pub fn mirrored_count(&self) -> usize {
        self.mirrored_count
    }

    /// Validates the configuration.
    pub fn validate(&self) -> Result<()> {
        if self.protective_slot > 3 {
            return Err(Error::InvalidHybridMbr {
                reason: "protective slot must be 0-3",
            });
        }

        let count = self.mirrored_count();
        if count > 3 {
            return Err(Error::TooManyPartitions {
                max: 3,
                requested: count,
            });
        }

        // Check that mirrored slots don't conflict with protective slot
        #[cfg(feature = "alloc")]
        for (i, _) in self.mirrored.iter().enumerate() {
            let slot = self.calculate_slot(i);
            if slot == self.protective_slot {
                return Err(Error::InvalidHybridMbr {
                    reason: "mirrored partition conflicts with protective slot",
                });
            }
        }

        Ok(())
    }

    /// Calculates the MBR slot for a mirrored partition index.
    fn calculate_slot(&self, mirror_index: usize) -> usize {
        let mut slot = 0;
        let mut count = 0;
        while count <= mirror_index && slot < 4 {
            if slot != self.protective_slot {
                if count == mirror_index {
                    return slot;
                }
                count += 1;
            }
            slot += 1;
        }
        slot
    }
}

/// Builder for creating Hybrid MBRs.
#[derive(Debug)]
pub struct HybridMbrBuilder {
    config: HybridMbrConfig,
    disk_sectors: u64,
}

impl HybridMbrBuilder {
    /// Creates a new builder for a disk with the given size in sectors.
    pub fn new(disk_sectors: u64) -> Self {
        Self {
            config: HybridMbrConfig::new(),
            disk_sectors,
        }
    }

    /// Sets the protective partition slot (0-3).
    pub fn protective_slot(mut self, slot: usize) -> Self {
        self.config.protective_slot = slot;
        self
    }

    /// Adds a GPT partition to mirror in the MBR.
    pub fn mirror_partition(
        self,
        gpt_index: u32,
        mbr_type: MbrPartitionType,
        bootable: bool,
    ) -> Self {
        let partition = MirroredPartition::new(gpt_index, mbr_type).with_bootable(bootable);
        Self {
            config: self.config.add_mirrored(partition),
            ..self
        }
    }

    /// Builds the Hybrid MBR given the GPT partition entries.
    pub fn build(self, gpt_entries: &[GptPartitionEntry]) -> Result<MasterBootRecord> {
        self.config.validate()?;

        let mut mbr = MasterBootRecord::default();
        let mut partition_table = MbrPartitionTable::new();

        // Collect mirrored partitions and their ranges
        #[cfg(feature = "alloc")]
        let mirrored_iter = self.config.mirrored.iter();
        #[cfg(not(feature = "alloc"))]
        let mirrored_iter = self.config.mirrored[..self.config.mirrored_count]
            .iter()
            .filter_map(|p| p.as_ref());

        let mut mirrored_ranges: [(u64, u64); 3] = [(0, 0); 3];
        let mut mirror_count = 0;

        for (i, mirrored) in mirrored_iter.enumerate() {
            let gpt_idx = mirrored.gpt_partition_index as usize;
            if gpt_idx >= gpt_entries.len() {
                return Err(Error::InvalidHybridMbr {
                    reason: "GPT partition index out of bounds",
                });
            }

            let gpt_entry = &gpt_entries[gpt_idx];
            if gpt_entry.is_unused() {
                return Err(Error::InvalidHybridMbr {
                    reason: "referenced GPT partition is unused",
                });
            }

            // Check if partition fits in 32-bit MBR addressing
            let first_native = gpt_entry.first_lba.to_ne();
            let last_native = gpt_entry.last_lba.to_ne();

            if first_native > last_native {
                return Err(Error::InvalidHybridMbr {
                    reason: "GPT partition has an inverted LBA range",
                });
            }

            if last_native > u32::MAX as u64 {
                return Err(Error::InvalidHybridMbr {
                    reason: "GPT partition extends beyond MBR 32-bit limit",
                });
            }

            let slot = self.config.calculate_slot(i);
            let start_lba = first_native as u32;
            let sector_count = (last_native - first_native + 1) as u32;

            partition_table[slot] = MbrPartition {
                boot_indicator: if mirrored.bootable { 0x80 } else { 0x00 },
                start_chs: Chs::new(start_lba),
                part_type: mirrored.mbr_type.to_u8(),
                end_chs: Chs::new(start_lba + sector_count - 1),
                start_lba: Le::<u32>::from_ne(start_lba),
                sector_count: Le::<u32>::from_ne(sector_count),
            };

            mirrored_ranges[mirror_count] = (first_native, last_native);
            mirror_count += 1;
        }

        // Create protective MBR entry covering LBA 1 through `protective_end`
        // (the last LBA before the first mirrored partition, or the last LBA of
        // the disk when no mirrored partition starts after LBA 1)
        let last_disk_lba = self.disk_sectors.saturating_sub(1).min(u32::MAX as u64) as u32;
        let protective_end = if mirror_count > 0 {
            // Find the start of the first mirrored partition
            let mut first_start = u64::MAX;
            for range in mirrored_ranges.iter().take(mirror_count) {
                if range.0 < first_start && range.0 > 1 {
                    first_start = range.0;
                }
            }
            if first_start == u64::MAX {
                // All mirrored partitions start at sector 1 or less
                last_disk_lba
            } else {
                (first_start - 1).min(u32::MAX as u64) as u32
            }
        } else {
            last_disk_lba
        };
        let protective_end = protective_end.max(1);
        let protective_size = protective_end;

        partition_table[self.config.protective_slot] = MbrPartition {
            boot_indicator: 0x00,
            start_chs: Chs::new(1),
            part_type: MbrPartitionType::ProtectiveMbr.to_u8(),
            end_chs: Chs::new(protective_end),
            start_lba: Le::<u32>::from_ne(1),
            sector_count: Le::<u32>::from_ne(protective_size),
        };

        mbr.partition_table = partition_table;
        Ok(mbr)
    }
}

/// Checks if an MBR appears to be a Hybrid MBR.
///
/// Returns `true` if the MBR contains a protective partition (type 0xEE)
/// and at least one other non-empty partition.
pub fn is_hybrid_mbr(mbr: &MasterBootRecord) -> bool {
    let mut has_protective = false;
    let mut has_other = false;

    let pt = mbr.get_partition_table();
    for partition in &pt.partitions {
        if partition.is_empty() {
            continue;
        }
        if partition.partition_type().is_protective() {
            has_protective = true;
        } else {
            has_other = true;
        }
    }

    has_protective && has_other
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::gpt::Guid;

    #[test]
    fn test_hybrid_mbr_config_validation() {
        let config = HybridMbrConfig::new()
            .with_protective_slot(0)
            .add_mirrored(MirroredPartition::new(0, MbrPartitionType::Fat32));

        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_hybrid_mbr_config_too_many_partitions() {
        let mut config = HybridMbrConfig::new();
        #[cfg(feature = "alloc")]
        {
            config.mirrored = alloc::vec![
                MirroredPartition::new(0, MbrPartitionType::Fat32),
                MirroredPartition::new(1, MbrPartitionType::LinuxNative),
                MirroredPartition::new(2, MbrPartitionType::LinuxNative),
                MirroredPartition::new(3, MbrPartitionType::LinuxNative),
            ];
        }

        let result = config.validate();
        assert!(matches!(result, Err(Error::TooManyPartitions { .. })));
    }

    #[test]
    fn test_hybrid_mbr_builder() {
        let gpt_entries = [
            GptPartitionEntry::new(Guid::EFI_SYSTEM, Guid::UNUSED, 2048, 206847),
            GptPartitionEntry::default(),
        ];

        let mbr = HybridMbrBuilder::new(1000000)
            .protective_slot(0)
            .mirror_partition(0, MbrPartitionType::EfiSystemPartition, false)
            .build(&gpt_entries)
            .unwrap();

        assert!(mbr.has_valid_signature());
        assert!(is_hybrid_mbr(&mbr));
    }

    #[test]
    fn test_protective_entry_covers_gap_before_first_mirror() {
        let gpt_entries = [GptPartitionEntry::new(
            Guid::EFI_SYSTEM,
            Guid::UNUSED,
            34,
            206847,
        )];

        let mbr = HybridMbrBuilder::new(1_000_000)
            .protective_slot(0)
            .mirror_partition(0, MbrPartitionType::EfiSystemPartition, false)
            .build(&gpt_entries)
            .unwrap();

        let pt = mbr.get_partition_table();
        let protective = &pt.partitions[0];
        assert_eq!(protective.start_lba.to_ne(), 1);
        assert_eq!(protective.sector_count.to_ne(), 33);
        assert_eq!(protective.end_chs, Chs::new(33));

        let mirrored = &pt.partitions[1];
        assert_eq!(mirrored.start_lba.to_ne(), 34);
    }

    #[test]
    fn test_protective_entry_covers_disk_without_mirrors() {
        let mbr = HybridMbrBuilder::new(1_000_000)
            .protective_slot(0)
            .build(&[])
            .unwrap();

        let pt = mbr.get_partition_table();
        let protective = &pt.partitions[0];
        assert_eq!(protective.start_lba.to_ne(), 1);
        assert_eq!(protective.sector_count.to_ne(), 999_999);
        assert_eq!(protective.end_chs, Chs::new(999_999));
    }

    #[test]
    fn test_is_hybrid_mbr() {
        // Pure protective MBR
        let protective = MasterBootRecord::protective(1000000);
        assert!(!is_hybrid_mbr(&protective));

        // Hybrid MBR
        let mut hybrid = protective;
        hybrid.with_partition_table(|pt| {
            pt[1] = MbrPartition::new(MbrPartitionType::Fat32, 2048, 100000);
        });
        assert!(is_hybrid_mbr(&hybrid));
    }
}