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
io_transform! {
#[cfg(feature = "alloc")]
extern crate alloc;
use super::super::{Read, Write, Seek, SeekFrom};
use crate::error::{PartitionError, Result};
use crate::gpt::{GptHeader, GptPartitionEntry};
use crate::mbr::MasterBootRecord;
use crate::scheme::{detect_scheme_from_mbr, PartitionSchemeType};
#[cfg(feature = "read")]
use super::gpt_io::GptHeaderReadExt;
#[cfg(feature = "write")]
use super::gpt_io::GptHeaderWriteExt;
#[cfg(feature = "read")]
use super::mbr_io::MasterBootRecordReadExt;
#[cfg(feature = "write")]
use super::mbr_io::MasterBootRecordWriteExt;
#[cfg(feature = "alloc")]
use crate::scheme::GptDisk;
#[cfg(feature = "alloc")]
use crate::scheme::DiskPartitionScheme;
// I/O operations for GptDisk
/// Extension trait for reading [`GptDisk`] from I/O sources.
#[cfg(all(feature = "alloc", feature = "read"))]
pub trait GptDiskReadExt: Sized {
/// Reads a GPT disk structure from a reader.
///
/// Reads the primary GPT header at LBA 1 and the partition entry array.
/// The reader should be positioned at the beginning of the disk (LBA 0).
///
/// # Arguments
///
/// * `reader` - The reader to read from
/// * `block_size` - The logical block size in bytes (typically 512)
///
/// # Errors
///
/// Returns an error if reading fails or if the GPT structure is invalid.
async fn read_from<R: Read + Seek>(
reader: &mut R,
block_size: u32,
) -> Result<Self>;
}
#[cfg(all(feature = "alloc", feature = "read"))]
impl GptDiskReadExt for GptDisk {
async fn read_from<R: Read + Seek>(
reader: &mut R,
block_size: u32,
) -> Result<Self> {
// Read primary GPT header at LBA 1
let primary_header = GptHeader::read_from_lba(reader, 1, block_size).await?;
// Validate header CRC if feature enabled
#[cfg(feature = "crc")]
if !primary_header.verify_crc32() {
return Err(PartitionError::GptHeaderCrcMismatch {
expected: primary_header.header_crc32,
actual: primary_header.calculate_crc32(),
});
}
// Validate partition entry size
let entry_size = primary_header.size_of_partition_entry;
if entry_size != core::mem::size_of::<GptPartitionEntry>() as u32 {
return Err(PartitionError::InvalidPartitionEntrySize { size: entry_size });
}
// Read partition entries
let num_entries = primary_header.num_partition_entries as usize;
let mut entries = alloc::vec![GptPartitionEntry::default(); num_entries];
reader
.seek(SeekFrom::Start(
primary_header.partition_entry_lba * block_size as u64,
))
.await
.map_err(|_| PartitionError::Io)?;
for entry in entries.iter_mut() {
let mut buf = [0u8; 128];
reader
.read_exact(&mut buf)
.await
.map_err(|_| PartitionError::Io)?;
*entry = bytemuck::cast(buf);
}
// Verify partition array CRC if feature enabled
#[cfg(feature = "crc")]
{
let entries_crc = crate::gpt::calculate_partition_array_crc32(&entries);
if primary_header.partition_entry_array_crc32 != entries_crc {
return Err(PartitionError::GptEntriesCrcMismatch {
expected: primary_header.partition_entry_array_crc32,
actual: entries_crc,
});
}
}
// Try to read backup header
let backup_header =
match GptHeader::read_from_lba(reader, primary_header.alternate_lba, block_size).await {
Ok(header) => header,
Err(_) => GptHeader {
// If backup header read fails, construct it from primary
my_lba: primary_header.alternate_lba,
alternate_lba: primary_header.my_lba,
..primary_header
},
};
Ok(Self {
primary_header,
backup_header,
entries,
block_size,
})
}
}
/// Extension trait for writing [`GptDisk`] to I/O sinks.
#[cfg(all(feature = "alloc", feature = "write"))]
pub trait GptDiskWriteExt {
/// Writes the complete GPT structure to a writer.
///
/// Writes:
/// 1. Protective MBR at LBA 0
/// 2. Primary GPT header at LBA 1
/// 3. Primary partition entry array starting at LBA 2
/// 4. Backup partition entry array before backup header
/// 5. Backup GPT header at the last LBA
///
/// # Arguments
///
/// * `writer` - The writer to write to
///
/// # Errors
///
/// Returns an error if writing fails.
async fn write_to<W: Write + Seek>(&self, writer: &mut W) -> Result<()>;
/// Writes the complete GPT structure with a custom MBR.
///
/// This is useful for hybrid MBR configurations.
///
/// # Arguments
///
/// * `writer` - The writer to write to
/// * `mbr` - The MBR to write (protective or hybrid)
///
/// # Errors
///
/// Returns an error if writing fails.
async fn write_to_with_mbr<W: Write + Seek>(
&self,
writer: &mut W,
mbr: &MasterBootRecord,
) -> Result<()>;
}
#[cfg(all(feature = "alloc", feature = "write"))]
impl GptDiskWriteExt for GptDisk {
async fn write_to<W: Write + Seek>(&self, writer: &mut W) -> Result<()> {
// Write protective MBR at LBA 0
writer
.seek(SeekFrom::Start(0))
.await
.map_err(|_| PartitionError::Io)?;
let protective_mbr = self.create_protective_mbr();
protective_mbr.write_to(writer).await?;
// Write primary header at LBA 1
self.primary_header
.write_to_lba(writer, 1, self.block_size)
.await?;
// Write primary partition entries starting at partition_entry_lba
writer
.seek(SeekFrom::Start(
self.primary_header.partition_entry_lba * self.block_size as u64,
))
.await
.map_err(|_| PartitionError::Io)?;
for entry in &self.entries {
writer
.write_all(bytemuck::bytes_of(entry))
.await
.map_err(|_| PartitionError::Io)?;
}
// Write backup partition entries
writer
.seek(SeekFrom::Start(
self.backup_header.partition_entry_lba * self.block_size as u64,
))
.await
.map_err(|_| PartitionError::Io)?;
for entry in &self.entries {
writer
.write_all(bytemuck::bytes_of(entry))
.await
.map_err(|_| PartitionError::Io)?;
}
// Write backup header at last LBA
self.backup_header
.write_to_lba(writer, self.backup_header.my_lba, self.block_size)
.await?;
Ok(())
}
async fn write_to_with_mbr<W: Write + Seek>(
&self,
writer: &mut W,
mbr: &MasterBootRecord,
) -> Result<()> {
// Write MBR at LBA 0
writer
.seek(SeekFrom::Start(0))
.await
.map_err(|_| PartitionError::Io)?;
mbr.write_to(writer).await?;
// Write primary header at LBA 1
self.primary_header
.write_to_lba(writer, 1, self.block_size)
.await?;
// Write primary partition entries
writer
.seek(SeekFrom::Start(
self.primary_header.partition_entry_lba * self.block_size as u64,
))
.await
.map_err(|_| PartitionError::Io)?;
for entry in &self.entries {
writer
.write_all(bytemuck::bytes_of(entry))
.await
.map_err(|_| PartitionError::Io)?;
}
// Write backup partition entries
writer
.seek(SeekFrom::Start(
self.backup_header.partition_entry_lba * self.block_size as u64,
))
.await
.map_err(|_| PartitionError::Io)?;
for entry in &self.entries {
writer
.write_all(bytemuck::bytes_of(entry))
.await
.map_err(|_| PartitionError::Io)?;
}
// Write backup header at last LBA
self.backup_header
.write_to_lba(writer, self.backup_header.my_lba, self.block_size)
.await?;
Ok(())
}
}
// I/O operations for DiskPartitionScheme
/// Extension trait for reading [`DiskPartitionScheme`] from I/O sources.
#[cfg(all(feature = "alloc", feature = "read"))]
pub trait DiskPartitionSchemeReadExt: Sized {
/// Detects and reads a partition scheme from a disk image.
///
/// This method:
/// 1. Reads the MBR at LBA 0
/// 2. Detects if it's a protective MBR (GPT) or hybrid MBR
/// 3. If protective/hybrid, reads the GPT structure
/// 4. Returns the appropriate partition scheme
///
/// # Arguments
///
/// * `reader` - The reader to read from (should be positioned at LBA 0)
/// * `block_size` - The logical block size in bytes (typically 512)
///
/// # Errors
///
/// Returns an error if reading fails or if the partition structure is invalid.
async fn read_from<R: Read + Seek>(
reader: &mut R,
block_size: u32,
) -> Result<Self>;
}
#[cfg(all(feature = "alloc", feature = "read"))]
impl DiskPartitionSchemeReadExt for DiskPartitionScheme {
async fn read_from<R: Read + Seek>(
reader: &mut R,
block_size: u32,
) -> Result<Self> {
// Seek to beginning and read MBR
reader
.seek(SeekFrom::Start(0))
.await
.map_err(|_| PartitionError::Io)?;
let mbr = MasterBootRecord::read_from(reader).await?;
let scheme_type = detect_scheme_from_mbr(&mbr);
match scheme_type {
PartitionSchemeType::Mbr => Ok(Self::Mbr(mbr)),
PartitionSchemeType::Gpt => {
let gpt = GptDisk::read_from(reader, block_size).await?;
Ok(Self::Gpt {
protective_mbr: mbr,
gpt,
})
}
PartitionSchemeType::Hybrid => {
let gpt = GptDisk::read_from(reader, block_size).await?;
Ok(Self::Hybrid {
hybrid_mbr: mbr,
gpt,
})
}
}
}
}
/// Extension trait for writing [`DiskPartitionScheme`] to I/O sinks.
#[cfg(all(feature = "alloc", feature = "write"))]
pub trait DiskPartitionSchemeWriteExt {
/// Writes the partition scheme to a writer.
///
/// # Arguments
///
/// * `writer` - The writer to write to
///
/// # Errors
///
/// Returns an error if writing fails.
async fn write_to<W: Write + Seek>(&self, writer: &mut W) -> Result<()>;
}
#[cfg(all(feature = "alloc", feature = "write"))]
impl DiskPartitionSchemeWriteExt for DiskPartitionScheme {
async fn write_to<W: Write + Seek>(&self, writer: &mut W) -> Result<()> {
match self {
Self::Mbr(mbr) => {
writer
.seek(SeekFrom::Start(0))
.await
.map_err(|_| PartitionError::Io)?;
mbr.write_to(writer).await
}
Self::Gpt { gpt, .. } => gpt.write_to(writer).await,
Self::Hybrid { hybrid_mbr, gpt } => gpt.write_to_with_mbr(writer, hybrid_mbr).await,
}
}
}
} // io_transform!