disk/
composite.rs

1// Copyright 2019 The ChromiumOS Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use std::cmp::max;
6use std::cmp::min;
7use std::collections::HashSet;
8use std::convert::TryInto;
9use std::fs::File;
10use std::fs::OpenOptions;
11use std::io;
12use std::io::ErrorKind;
13use std::io::Read;
14use std::io::Seek;
15use std::io::SeekFrom;
16use std::io::Write;
17use std::ops::Range;
18use std::path::Path;
19use std::path::PathBuf;
20use std::sync::atomic::AtomicBool;
21use std::sync::atomic::Ordering;
22use std::sync::Arc;
23
24use async_trait::async_trait;
25use base::AsRawDescriptors;
26use base::FileAllocate;
27use base::FileReadWriteAtVolatile;
28use base::FileSetLen;
29use base::RawDescriptor;
30use base::VolatileSlice;
31use crc32fast::Hasher;
32use cros_async::BackingMemory;
33use cros_async::Executor;
34use cros_async::IoOptions;
35use cros_async::MemRegionIter;
36use protobuf::Message;
37use protos::cdisk_spec;
38use protos::cdisk_spec::ComponentDisk;
39use protos::cdisk_spec::CompositeDisk;
40use protos::cdisk_spec::ReadWriteCapability;
41use remain::sorted;
42use thiserror::Error;
43use uuid::Uuid;
44
45use crate::gpt;
46use crate::gpt::write_gpt_header;
47use crate::gpt::write_protective_mbr;
48use crate::gpt::GptPartitionEntry;
49use crate::gpt::GPT_BEGINNING_SIZE;
50use crate::gpt::GPT_END_SIZE;
51use crate::gpt::GPT_HEADER_SIZE;
52use crate::gpt::GPT_NUM_PARTITIONS;
53use crate::gpt::GPT_PARTITION_ENTRY_SIZE;
54use crate::gpt::SECTOR_SIZE;
55use crate::open_disk_file;
56use crate::AsyncDisk;
57use crate::DiskFile;
58use crate::DiskFileParams;
59use crate::DiskGetLen;
60use crate::ImageType;
61use crate::ToAsyncDisk;
62
63/// The amount of padding needed between the last partition entry and the first partition, to align
64/// the partition appropriately. The two sectors are for the MBR and the GPT header.
65const PARTITION_ALIGNMENT_SIZE: usize = GPT_BEGINNING_SIZE as usize
66    - 2 * SECTOR_SIZE as usize
67    - GPT_NUM_PARTITIONS as usize * GPT_PARTITION_ENTRY_SIZE as usize;
68const HEADER_PADDING_LENGTH: usize = SECTOR_SIZE as usize - GPT_HEADER_SIZE as usize;
69// Keep all partitions 4k aligned for performance.
70const PARTITION_SIZE_SHIFT: u8 = 12;
71
72// From https://en.wikipedia.org/wiki/GUID_Partition_Table#Partition_type_GUIDs.
73const LINUX_FILESYSTEM_GUID: Uuid = Uuid::from_u128(0x0FC63DAF_8483_4772_8E79_3D69D8477DE4);
74const EFI_SYSTEM_PARTITION_GUID: Uuid = Uuid::from_u128(0xC12A7328_F81F_11D2_BA4B_00A0C93EC93B);
75
76#[sorted]
77#[derive(Error, Debug)]
78pub enum Error {
79    #[error("failed to use underlying disk: \"{0}\"")]
80    DiskError(Box<crate::Error>),
81    #[error("duplicate GPT partition label \"{0}\"")]
82    DuplicatePartitionLabel(String),
83    #[error("failed to write GPT header: \"{0}\"")]
84    GptError(gpt::Error),
85    #[error("invalid magic header for composite disk format")]
86    InvalidMagicHeader,
87    #[error("invalid partition path {0:?}")]
88    InvalidPath(PathBuf),
89    #[error("failed to parse specification proto: \"{0}\"")]
90    InvalidProto(protobuf::Error),
91    #[error("invalid specification: \"{0}\"")]
92    InvalidSpecification(String),
93    #[error("no image files for partition {0:?}")]
94    NoImageFiles(PartitionInfo),
95    #[error("failed to open component file \"{1}\": \"{0}\"")]
96    OpenFile(io::Error, String),
97    #[error("failed to read specification: \"{0}\"")]
98    ReadSpecificationError(io::Error),
99    #[error("Read-write partition {0:?} size is not a multiple of {multiple}.", multiple = 1 << PARTITION_SIZE_SHIFT)]
100    UnalignedReadWrite(PartitionInfo),
101    #[error("unknown version {0} in specification")]
102    UnknownVersion(u64),
103    #[error("unsupported component disk type \"{0:?}\"")]
104    UnsupportedComponent(ImageType),
105    #[error("failed to write composite disk header: \"{0}\"")]
106    WriteHeader(io::Error),
107    #[error("failed to write specification proto: \"{0}\"")]
108    WriteProto(protobuf::Error),
109    #[error("failed to write zero filler: \"{0}\"")]
110    WriteZeroFiller(io::Error),
111}
112
113impl From<gpt::Error> for Error {
114    fn from(e: gpt::Error) -> Self {
115        Self::GptError(e)
116    }
117}
118
119pub type Result<T> = std::result::Result<T, Error>;
120
121#[derive(Debug)]
122struct ComponentDiskPart {
123    file: Box<dyn DiskFile>,
124    offset: u64, // Location in the block device visible to the guest
125    length: u64,
126    file_offset: u64, // Location within the host file
127    // Whether there have been any writes since the last fsync or fdatasync.
128    needs_flush: Arc<AtomicBool>,
129}
130
131impl ComponentDiskPart {
132    fn range(&self) -> Range<u64> {
133        self.offset..(self.offset + self.length)
134    }
135
136    fn try_clone(&self) -> io::Result<Self> {
137        Ok(Self {
138            file: self.file.try_clone()?,
139            offset: self.offset,
140            length: self.length,
141            file_offset: self.file_offset,
142            needs_flush: Arc::clone(&self.needs_flush),
143        })
144    }
145}
146
147/// Represents a composite virtual disk made out of multiple component files. This is described on
148/// disk by a protocol buffer file that lists out the component file locations and their offsets
149/// and lengths on the virtual disk. The spaces covered by the component disks must be contiguous
150/// and not overlapping.
151#[derive(Debug)]
152pub struct CompositeDiskFile {
153    component_disks: Vec<ComponentDiskPart>,
154    // We keep the root composite file open so that the file lock is not dropped.
155    _disk_spec_file: File,
156}
157
158impl DiskFile for CompositeDiskFile {
159    fn try_clone(&self) -> io::Result<Box<dyn DiskFile>> {
160        Ok(Box::new(CompositeDiskFile {
161            component_disks: self
162                .component_disks
163                .iter()
164                .map(ComponentDiskPart::try_clone)
165                .collect::<io::Result<Vec<_>>>()?,
166            _disk_spec_file: self._disk_spec_file.try_clone()?,
167        }))
168    }
169}
170
171fn ranges_overlap(a: &Range<u64>, b: &Range<u64>) -> bool {
172    range_intersection(a, b).is_some()
173}
174
175fn range_intersection(a: &Range<u64>, b: &Range<u64>) -> Option<Range<u64>> {
176    let r = Range {
177        start: max(a.start, b.start),
178        end: min(a.end, b.end),
179    };
180    if r.is_empty() {
181        None
182    } else {
183        Some(r)
184    }
185}
186
187/// The version of the composite disk format supported by this implementation.
188const COMPOSITE_DISK_VERSION: u64 = 2;
189
190/// A magic string placed at the beginning of a composite disk file to identify it.
191pub const CDISK_MAGIC: &str = "composite_disk\x1d";
192
193impl CompositeDiskFile {
194    fn new(mut disks: Vec<ComponentDiskPart>, disk_spec_file: File) -> Result<CompositeDiskFile> {
195        disks.sort_by(|d1, d2| d1.offset.cmp(&d2.offset));
196        for s in disks.windows(2) {
197            if s[0].offset == s[1].offset {
198                return Err(Error::InvalidSpecification(format!(
199                    "Two disks at offset {}",
200                    s[0].offset
201                )));
202            }
203        }
204        Ok(CompositeDiskFile {
205            component_disks: disks,
206            _disk_spec_file: disk_spec_file,
207        })
208    }
209
210    /// Set up a composite disk by reading the specification from a file. The file must consist of
211    /// the CDISK_MAGIC string followed by one binary instance of the CompositeDisk protocol
212    /// buffer. Returns an error if it could not read the file or if the specification was invalid.
213    pub fn from_file(mut file: File, params: DiskFileParams) -> Result<CompositeDiskFile> {
214        file.seek(SeekFrom::Start(0))
215            .map_err(Error::ReadSpecificationError)?;
216        let mut magic_space = [0u8; CDISK_MAGIC.len()];
217        file.read_exact(&mut magic_space[..])
218            .map_err(Error::ReadSpecificationError)?;
219        if magic_space != CDISK_MAGIC.as_bytes() {
220            return Err(Error::InvalidMagicHeader);
221        }
222        let proto: cdisk_spec::CompositeDisk =
223            Message::parse_from_reader(&mut file).map_err(Error::InvalidProto)?;
224        if proto.version > COMPOSITE_DISK_VERSION {
225            return Err(Error::UnknownVersion(proto.version));
226        }
227        let mut disks: Vec<ComponentDiskPart> = proto
228            .component_disks
229            .iter()
230            .map(|disk| {
231                let writable = !params.is_read_only
232                    && disk.read_write_capability
233                        == cdisk_spec::ReadWriteCapability::READ_WRITE.into();
234                let component_path = PathBuf::from(&disk.file_path);
235                let path = if component_path.is_relative() || proto.version > 1 {
236                    params.path.parent().unwrap().join(component_path)
237                } else {
238                    component_path
239                };
240
241                // Note that a read-only parts of a composite disk should NOT be marked sparse,
242                // as the action of marking them sparse is a write. This may seem a little hacky,
243                // and it is; however:
244                //    (a)  there is not a good way to pass sparseness parameters per composite disk
245                //         part (the proto does not have fields for it).
246                //    (b)  this override of sorts always matches the correct user intent.
247                Ok(ComponentDiskPart {
248                    file: open_disk_file(DiskFileParams {
249                        path: path.to_owned(),
250                        is_read_only: !writable,
251                        is_sparse_file: params.is_sparse_file && writable,
252                        // TODO: Should pass `params.is_overlapped` through here. Needs testing.
253                        // is_overlapped: false,
254                        is_direct: params.is_direct,
255                        lock: params.lock,
256                        depth: params.depth + 1,
257                        ..Default::default()
258                    })
259                    .map_err(|e| Error::DiskError(Box::new(e)))?,
260                    offset: disk.offset,
261                    length: 0, // Assigned later
262                    file_offset: disk.file_offset,
263                    needs_flush: Arc::new(AtomicBool::new(false)),
264                })
265            })
266            .collect::<Result<Vec<ComponentDiskPart>>>()?;
267        disks.sort_by(|d1, d2| d1.offset.cmp(&d2.offset));
268        for i in 0..(disks.len() - 1) {
269            let length = disks[i + 1].offset - disks[i].offset;
270            if length == 0 {
271                let text = format!("Two disks at offset {}", disks[i].offset);
272                return Err(Error::InvalidSpecification(text));
273            }
274            if let Some(disk) = disks.get_mut(i) {
275                disk.length = length;
276            } else {
277                let text = format!("Unable to set disk length {length}");
278                return Err(Error::InvalidSpecification(text));
279            }
280        }
281        if let Some(last_disk) = disks.last_mut() {
282            if proto.length <= last_disk.offset {
283                let text = format!(
284                    "Full size of disk doesn't match last offset. {} <= {}",
285                    proto.length, last_disk.offset
286                );
287                return Err(Error::InvalidSpecification(text));
288            }
289            last_disk.length = proto.length - last_disk.offset;
290        } else {
291            let text = format!("Unable to set last disk length to end at {}", proto.length);
292            return Err(Error::InvalidSpecification(text));
293        }
294
295        CompositeDiskFile::new(disks, file)
296    }
297
298    fn length(&self) -> u64 {
299        if let Some(disk) = self.component_disks.last() {
300            disk.offset + disk.length
301        } else {
302            0
303        }
304    }
305
306    fn disk_at_offset(&self, offset: u64) -> io::Result<&ComponentDiskPart> {
307        self.component_disks
308            .iter()
309            .find(|disk| disk.range().contains(&offset))
310            .ok_or_else(|| {
311                io::Error::new(
312                    ErrorKind::InvalidData,
313                    format!("no disk at offset {offset}"),
314                )
315            })
316    }
317}
318
319impl DiskGetLen for CompositeDiskFile {
320    fn get_len(&self) -> io::Result<u64> {
321        Ok(self.length())
322    }
323}
324
325impl FileSetLen for CompositeDiskFile {
326    fn set_len(&self, _len: u64) -> io::Result<()> {
327        Err(io::Error::other("unsupported operation"))
328    }
329}
330
331// Implements Read and Write targeting volatile storage for composite disks.
332//
333// Note that reads and writes will return early if crossing component disk boundaries.
334// This is allowed by the read and write specifications, which only say read and write
335// have to return how many bytes were actually read or written. Use read_exact_volatile
336// or write_all_volatile to make sure all bytes are received/transmitted.
337//
338// If one of the component disks does a partial read or write, that also gets passed
339// transparently to the parent.
340impl FileReadWriteAtVolatile for CompositeDiskFile {
341    fn read_at_volatile(&self, slice: VolatileSlice, offset: u64) -> io::Result<usize> {
342        let cursor_location = offset;
343        let disk = self.disk_at_offset(cursor_location)?;
344        let subslice = if cursor_location + slice.size() as u64 > disk.offset + disk.length {
345            let new_size = disk.offset + disk.length - cursor_location;
346            slice
347                .sub_slice(0, new_size as usize)
348                .map_err(|e| io::Error::new(ErrorKind::InvalidData, e.to_string()))?
349        } else {
350            slice
351        };
352        disk.file
353            .read_at_volatile(subslice, cursor_location - disk.offset + disk.file_offset)
354    }
355    fn write_at_volatile(&self, slice: VolatileSlice, offset: u64) -> io::Result<usize> {
356        let cursor_location = offset;
357        let disk = self.disk_at_offset(cursor_location)?;
358        let subslice = if cursor_location + slice.size() as u64 > disk.offset + disk.length {
359            let new_size = disk.offset + disk.length - cursor_location;
360            slice
361                .sub_slice(0, new_size as usize)
362                .map_err(|e| io::Error::new(ErrorKind::InvalidData, e.to_string()))?
363        } else {
364            slice
365        };
366
367        let bytes = disk
368            .file
369            .write_at_volatile(subslice, cursor_location - disk.offset + disk.file_offset)?;
370        disk.needs_flush.store(true, Ordering::SeqCst);
371        Ok(bytes)
372    }
373}
374
375impl AsRawDescriptors for CompositeDiskFile {
376    fn as_raw_descriptors(&self) -> Vec<RawDescriptor> {
377        self.component_disks
378            .iter()
379            .flat_map(|d| d.file.as_raw_descriptors())
380            .collect()
381    }
382}
383
384struct AsyncComponentDiskPart {
385    file: Box<dyn AsyncDisk>,
386    offset: u64, // Location in the block device visible to the guest
387    length: u64,
388    file_offset: u64, // Location within the host file
389    needs_flush: Arc<AtomicBool>,
390}
391
392pub struct AsyncCompositeDiskFile {
393    component_disks: Vec<AsyncComponentDiskPart>,
394}
395
396impl DiskGetLen for AsyncCompositeDiskFile {
397    fn get_len(&self) -> io::Result<u64> {
398        Ok(self.length())
399    }
400}
401
402impl FileSetLen for AsyncCompositeDiskFile {
403    fn set_len(&self, _len: u64) -> io::Result<()> {
404        Err(io::Error::other("unsupported operation"))
405    }
406}
407
408impl FileAllocate for AsyncCompositeDiskFile {
409    fn allocate(&self, offset: u64, length: u64) -> io::Result<()> {
410        let range = offset..(offset + length);
411        let disks = self
412            .component_disks
413            .iter()
414            .filter(|disk| ranges_overlap(&disk.range(), &range));
415        for disk in disks {
416            if let Some(intersection) = range_intersection(&range, &disk.range()) {
417                disk.file.allocate(
418                    intersection.start - disk.offset + disk.file_offset,
419                    intersection.end - intersection.start,
420                )?;
421                disk.needs_flush.store(true, Ordering::SeqCst);
422            }
423        }
424        Ok(())
425    }
426}
427
428impl ToAsyncDisk for CompositeDiskFile {
429    fn to_async_disk(self: Box<Self>, ex: &Executor) -> crate::Result<Box<dyn AsyncDisk>> {
430        Ok(Box::new(AsyncCompositeDiskFile {
431            component_disks: self
432                .component_disks
433                .into_iter()
434                .map(|disk| -> crate::Result<_> {
435                    Ok(AsyncComponentDiskPart {
436                        file: disk.file.to_async_disk(ex)?,
437                        offset: disk.offset,
438                        length: disk.length,
439                        file_offset: disk.file_offset,
440                        needs_flush: disk.needs_flush,
441                    })
442                })
443                .collect::<crate::Result<Vec<_>>>()?,
444        }))
445    }
446}
447
448impl AsyncComponentDiskPart {
449    fn range(&self) -> Range<u64> {
450        self.offset..(self.offset + self.length)
451    }
452
453    fn set_needs_flush(&self) {
454        self.needs_flush.store(true, Ordering::SeqCst);
455    }
456}
457
458impl AsyncCompositeDiskFile {
459    fn length(&self) -> u64 {
460        if let Some(disk) = self.component_disks.last() {
461            disk.offset + disk.length
462        } else {
463            0
464        }
465    }
466
467    fn disk_at_offset(&self, offset: u64) -> io::Result<&AsyncComponentDiskPart> {
468        self.component_disks
469            .iter()
470            .find(|disk| disk.range().contains(&offset))
471            .ok_or_else(|| {
472                io::Error::new(
473                    ErrorKind::InvalidData,
474                    format!("no disk at offset {offset}"),
475                )
476            })
477    }
478
479    fn disks_in_range<'a>(&'a self, range: &Range<u64>) -> Vec<&'a AsyncComponentDiskPart> {
480        self.component_disks
481            .iter()
482            .filter(|disk| ranges_overlap(&disk.range(), range))
483            .collect()
484    }
485}
486
487#[async_trait(?Send)]
488impl AsyncDisk for AsyncCompositeDiskFile {
489    async fn flush(&self) -> crate::Result<()> {
490        futures::future::try_join_all(self.component_disks.iter().map(|c| c.file.flush())).await?;
491        Ok(())
492    }
493
494    async fn fsync(&self) -> crate::Result<()> {
495        // NOTE: The fsync implementation isn't really async, so no point in adding concurrency
496        // here unless we introduce a blocking threadpool.
497        for disk in self.component_disks.iter() {
498            if disk.needs_flush.fetch_and(false, Ordering::SeqCst) {
499                if let Err(e) = disk.file.fsync().await {
500                    disk.set_needs_flush();
501                    return Err(e);
502                }
503            }
504        }
505        Ok(())
506    }
507
508    async fn fdatasync(&self) -> crate::Result<()> {
509        // NOTE: The fdatasync implementation isn't really async, so no point in adding concurrency
510        // here unless we introduce a blocking threadpool.
511        for disk in self.component_disks.iter() {
512            if disk.needs_flush.fetch_and(false, Ordering::SeqCst) {
513                if let Err(e) = disk.file.fdatasync().await {
514                    disk.set_needs_flush();
515                    return Err(e);
516                }
517            }
518        }
519        Ok(())
520    }
521
522    async fn read_to_mem<'a>(
523        &'a self,
524        file_offset: u64,
525        mem: Arc<dyn BackingMemory + Send + Sync>,
526        mem_offsets: MemRegionIter<'a>,
527        options: IoOptions,
528    ) -> crate::Result<usize> {
529        let disk = self
530            .disk_at_offset(file_offset)
531            .map_err(crate::Error::ReadingData)?;
532        let remaining_disk = disk.offset + disk.length - file_offset;
533        disk.file
534            .read_to_mem(
535                file_offset - disk.offset + disk.file_offset,
536                mem,
537                mem_offsets.take_bytes(remaining_disk.try_into().unwrap()),
538                options,
539            )
540            .await
541    }
542
543    async fn write_from_mem<'a>(
544        &'a self,
545        file_offset: u64,
546        mem: Arc<dyn BackingMemory + Send + Sync>,
547        mem_offsets: MemRegionIter<'a>,
548        options: IoOptions,
549    ) -> crate::Result<usize> {
550        let disk = self
551            .disk_at_offset(file_offset)
552            .map_err(crate::Error::ReadingData)?;
553        let remaining_disk = disk.offset + disk.length - file_offset;
554        let n = disk
555            .file
556            .write_from_mem(
557                file_offset - disk.offset + disk.file_offset,
558                mem,
559                mem_offsets.take_bytes(remaining_disk.try_into().unwrap()),
560                options,
561            )
562            .await?;
563        disk.set_needs_flush();
564        Ok(n)
565    }
566
567    async fn punch_hole(&self, file_offset: u64, length: u64) -> crate::Result<()> {
568        let range = file_offset..(file_offset + length);
569        let disks = self.disks_in_range(&range);
570        for disk in disks {
571            if let Some(intersection) = range_intersection(&range, &disk.range()) {
572                disk.file
573                    .punch_hole(
574                        intersection.start - disk.offset + disk.file_offset,
575                        intersection.end - intersection.start,
576                    )
577                    .await?;
578                disk.set_needs_flush();
579            }
580        }
581        Ok(())
582    }
583
584    async fn write_zeroes_at(&self, file_offset: u64, length: u64) -> crate::Result<()> {
585        let range = file_offset..(file_offset + length);
586        let disks = self.disks_in_range(&range);
587        for disk in disks {
588            if let Some(intersection) = range_intersection(&range, &disk.range()) {
589                disk.file
590                    .write_zeroes_at(
591                        intersection.start - disk.offset + disk.file_offset,
592                        intersection.end - intersection.start,
593                    )
594                    .await?;
595                disk.set_needs_flush();
596            }
597        }
598        Ok(())
599    }
600}
601
602/// Information about a partition to create.
603#[derive(Clone, Debug, Eq, PartialEq)]
604pub struct PartitionInfo {
605    pub label: String,
606    pub path: PathBuf,
607    pub partition_type: ImagePartitionType,
608    pub writable: bool,
609    pub size: u64,
610    pub part_guid: Option<Uuid>,
611}
612
613impl PartitionInfo {
614    fn aligned_size(&self) -> u64 {
615        self.size.next_multiple_of(1 << PARTITION_SIZE_SHIFT)
616    }
617}
618
619/// The type of partition.
620#[derive(Copy, Clone, Debug, Eq, PartialEq)]
621pub enum ImagePartitionType {
622    LinuxFilesystem,
623    EfiSystemPartition,
624}
625
626impl ImagePartitionType {
627    fn guid(self) -> Uuid {
628        match self {
629            Self::LinuxFilesystem => LINUX_FILESYSTEM_GUID,
630            Self::EfiSystemPartition => EFI_SYSTEM_PARTITION_GUID,
631        }
632    }
633}
634
635/// Write protective MBR and primary GPT table.
636fn write_beginning(
637    file: &mut impl Write,
638    disk_guid: Uuid,
639    partitions: &[u8],
640    partition_entries_crc32: u32,
641    secondary_table_offset: u64,
642    disk_size: u64,
643) -> Result<()> {
644    // Write the protective MBR to the first sector.
645    write_protective_mbr(file, disk_size)?;
646
647    // Write the GPT header, and pad out to the end of the sector.
648    write_gpt_header(
649        file,
650        disk_guid,
651        partition_entries_crc32,
652        secondary_table_offset,
653        false,
654    )?;
655    file.write_all(&[0; HEADER_PADDING_LENGTH])
656        .map_err(Error::WriteHeader)?;
657
658    // Write partition entries, including unused ones.
659    file.write_all(partitions).map_err(Error::WriteHeader)?;
660
661    // Write zeroes to align the first partition appropriately.
662    file.write_all(&[0; PARTITION_ALIGNMENT_SIZE])
663        .map_err(Error::WriteHeader)?;
664
665    Ok(())
666}
667
668/// Write secondary GPT table.
669fn write_end(
670    file: &mut impl Write,
671    disk_guid: Uuid,
672    partitions: &[u8],
673    partition_entries_crc32: u32,
674    secondary_table_offset: u64,
675) -> Result<()> {
676    // Write partition entries, including unused ones.
677    file.write_all(partitions).map_err(Error::WriteHeader)?;
678
679    // Write the GPT header, and pad out to the end of the sector.
680    write_gpt_header(
681        file,
682        disk_guid,
683        partition_entries_crc32,
684        secondary_table_offset,
685        true,
686    )?;
687    file.write_all(&[0; HEADER_PADDING_LENGTH])
688        .map_err(Error::WriteHeader)?;
689
690    Ok(())
691}
692
693/// Create the `GptPartitionEntry` for the given partition.
694fn create_gpt_entry(partition: &PartitionInfo, offset: u64) -> GptPartitionEntry {
695    let mut partition_name: Vec<u16> = partition.label.encode_utf16().collect();
696    partition_name.resize(36, 0);
697
698    GptPartitionEntry {
699        partition_type_guid: partition.partition_type.guid(),
700        unique_partition_guid: partition.part_guid.unwrap_or(Uuid::new_v4()),
701        first_lba: offset / SECTOR_SIZE,
702        last_lba: (offset + partition.aligned_size()) / SECTOR_SIZE - 1,
703        attributes: 0,
704        partition_name: partition_name.try_into().unwrap(),
705    }
706}
707
708/// Create one or more `ComponentDisk` proto messages for the given partition.
709fn create_component_disks(
710    partition: &PartitionInfo,
711    offset: u64,
712    zero_filler_path: &str,
713) -> Result<Vec<ComponentDisk>> {
714    let aligned_size = partition.aligned_size();
715
716    let mut component_disks = vec![ComponentDisk {
717        offset,
718        file_path: partition
719            .path
720            .to_str()
721            .ok_or_else(|| Error::InvalidPath(partition.path.to_owned()))?
722            .to_string(),
723        read_write_capability: if partition.writable {
724            ReadWriteCapability::READ_WRITE.into()
725        } else {
726            ReadWriteCapability::READ_ONLY.into()
727        },
728        ..ComponentDisk::new()
729    }];
730
731    if partition.size != aligned_size {
732        if partition.writable {
733            return Err(Error::UnalignedReadWrite(partition.to_owned()));
734        } else {
735            // Fill in the gap by reusing the zero filler file, because we know it is always bigger
736            // than the alignment size. Its size is 1 << PARTITION_SIZE_SHIFT (4k).
737            component_disks.push(ComponentDisk {
738                offset: offset + partition.size,
739                file_path: zero_filler_path.to_owned(),
740                read_write_capability: ReadWriteCapability::READ_ONLY.into(),
741                ..ComponentDisk::new()
742            });
743        }
744    }
745
746    Ok(component_disks)
747}
748
749/// Create a new composite disk image containing the given partitions, and write it out to the given
750/// files.
751pub fn create_composite_disk(
752    partitions: &[PartitionInfo],
753    zero_filler_path: &Path,
754    header_path: &Path,
755    header_file: &mut impl Write,
756    footer_path: &Path,
757    footer_file: &mut impl Write,
758    output_composite: &mut File,
759) -> Result<()> {
760    let zero_filler_path = zero_filler_path
761        .to_str()
762        .ok_or_else(|| Error::InvalidPath(zero_filler_path.to_owned()))?
763        .to_string();
764    let header_path = header_path
765        .to_str()
766        .ok_or_else(|| Error::InvalidPath(header_path.to_owned()))?
767        .to_string();
768    let footer_path = footer_path
769        .to_str()
770        .ok_or_else(|| Error::InvalidPath(footer_path.to_owned()))?
771        .to_string();
772
773    let mut composite_proto = CompositeDisk::new();
774    composite_proto.version = COMPOSITE_DISK_VERSION;
775    composite_proto.component_disks.push(ComponentDisk {
776        file_path: header_path,
777        offset: 0,
778        read_write_capability: ReadWriteCapability::READ_ONLY.into(),
779        ..ComponentDisk::new()
780    });
781
782    // Write partitions to a temporary buffer so that we can calculate the CRC, and construct the
783    // ComponentDisk proto messages at the same time.
784    let mut partitions_buffer =
785        [0u8; GPT_NUM_PARTITIONS as usize * GPT_PARTITION_ENTRY_SIZE as usize];
786    let mut writer: &mut [u8] = &mut partitions_buffer;
787    let mut next_disk_offset = GPT_BEGINNING_SIZE;
788    let mut labels = HashSet::with_capacity(partitions.len());
789    for partition in partitions {
790        let gpt_entry = create_gpt_entry(partition, next_disk_offset);
791        if !labels.insert(gpt_entry.partition_name) {
792            return Err(Error::DuplicatePartitionLabel(partition.label.clone()));
793        }
794        gpt_entry.write_bytes(&mut writer)?;
795
796        for component_disk in
797            create_component_disks(partition, next_disk_offset, &zero_filler_path)?
798        {
799            composite_proto.component_disks.push(component_disk);
800        }
801
802        next_disk_offset += partition.aligned_size();
803    }
804    // The secondary GPT needs to be at the very end of the file, but its size (0x4200) is not
805    // aligned to the chosen partition size (0x1000). We compensate for that by writing some
806    // padding to the start of the footer file.
807    const FOOTER_PADDING: u64 =
808        GPT_END_SIZE.next_multiple_of(1 << PARTITION_SIZE_SHIFT) - GPT_END_SIZE;
809    let footer_file_offset = next_disk_offset;
810    let secondary_table_offset = footer_file_offset + FOOTER_PADDING;
811    let disk_size = secondary_table_offset + GPT_END_SIZE;
812    composite_proto.component_disks.push(ComponentDisk {
813        file_path: footer_path,
814        offset: footer_file_offset,
815        read_write_capability: ReadWriteCapability::READ_ONLY.into(),
816        ..ComponentDisk::new()
817    });
818
819    // Calculate CRC32 of partition entries.
820    let mut hasher = Hasher::new();
821    hasher.update(&partitions_buffer);
822    let partition_entries_crc32 = hasher.finalize();
823
824    let disk_guid = Uuid::new_v4();
825    write_beginning(
826        header_file,
827        disk_guid,
828        &partitions_buffer,
829        partition_entries_crc32,
830        secondary_table_offset,
831        disk_size,
832    )?;
833
834    footer_file
835        .write_all(&[0; FOOTER_PADDING as usize])
836        .map_err(Error::WriteHeader)?;
837    write_end(
838        footer_file,
839        disk_guid,
840        &partitions_buffer,
841        partition_entries_crc32,
842        secondary_table_offset,
843    )?;
844
845    composite_proto.length = disk_size;
846    output_composite
847        .write_all(CDISK_MAGIC.as_bytes())
848        .map_err(Error::WriteHeader)?;
849    composite_proto
850        .write_to_writer(output_composite)
851        .map_err(Error::WriteProto)?;
852
853    Ok(())
854}
855
856/// Create a zero filler file which can be used to fill the gaps between partition files.
857/// The filler is sized to be big enough to fill the gaps. (1 << PARTITION_SIZE_SHIFT)
858pub fn create_zero_filler<P: AsRef<Path>>(zero_filler_path: P) -> Result<()> {
859    let f = OpenOptions::new()
860        .create(true)
861        .read(true)
862        .write(true)
863        .truncate(true)
864        .open(zero_filler_path.as_ref())
865        .map_err(Error::WriteZeroFiller)?;
866    f.set_len(1 << PARTITION_SIZE_SHIFT)
867        .map_err(Error::WriteZeroFiller)
868}
869
870#[cfg(test)]
871mod tests {
872    use std::fs::OpenOptions;
873    use std::io::Write;
874    use std::matches;
875
876    use base::AsRawDescriptor;
877    use tempfile::tempfile;
878
879    use super::*;
880
881    fn new_from_components(disks: Vec<ComponentDiskPart>) -> Result<CompositeDiskFile> {
882        CompositeDiskFile::new(disks, tempfile().unwrap())
883    }
884
885    #[test]
886    fn block_duplicate_offset_disks() {
887        let file1 = tempfile().unwrap();
888        let file2 = tempfile().unwrap();
889        let disk_part1 = ComponentDiskPart {
890            file: Box::new(file1),
891            offset: 0,
892            length: 100,
893            file_offset: 0,
894            needs_flush: Arc::new(AtomicBool::new(false)),
895        };
896        let disk_part2 = ComponentDiskPart {
897            file: Box::new(file2),
898            offset: 0,
899            length: 100,
900            file_offset: 0,
901            needs_flush: Arc::new(AtomicBool::new(false)),
902        };
903        assert!(new_from_components(vec![disk_part1, disk_part2]).is_err());
904    }
905
906    #[test]
907    fn get_len() {
908        let file1 = tempfile().unwrap();
909        let file2 = tempfile().unwrap();
910        let disk_part1 = ComponentDiskPart {
911            file: Box::new(file1),
912            offset: 0,
913            length: 100,
914            file_offset: 0,
915            needs_flush: Arc::new(AtomicBool::new(false)),
916        };
917        let disk_part2 = ComponentDiskPart {
918            file: Box::new(file2),
919            offset: 100,
920            length: 100,
921            file_offset: 0,
922            needs_flush: Arc::new(AtomicBool::new(false)),
923        };
924        let composite = new_from_components(vec![disk_part1, disk_part2]).unwrap();
925        let len = composite.get_len().unwrap();
926        assert_eq!(len, 200);
927    }
928
929    #[test]
930    fn async_get_len() {
931        let file1 = tempfile().unwrap();
932        let file2 = tempfile().unwrap();
933        let disk_part1 = ComponentDiskPart {
934            file: Box::new(file1),
935            offset: 0,
936            length: 100,
937            file_offset: 0,
938            needs_flush: Arc::new(AtomicBool::new(false)),
939        };
940        let disk_part2 = ComponentDiskPart {
941            file: Box::new(file2),
942            offset: 100,
943            length: 100,
944            file_offset: 0,
945            needs_flush: Arc::new(AtomicBool::new(false)),
946        };
947        let composite = new_from_components(vec![disk_part1, disk_part2]).unwrap();
948
949        let ex = Executor::new().unwrap();
950        let composite = Box::new(composite).to_async_disk(&ex).unwrap();
951        let len = composite.get_len().unwrap();
952        assert_eq!(len, 200);
953    }
954
955    #[test]
956    fn single_file_passthrough() {
957        let file = tempfile().unwrap();
958        let disk_part = ComponentDiskPart {
959            file: Box::new(file),
960            offset: 0,
961            length: 100,
962            file_offset: 0,
963            needs_flush: Arc::new(AtomicBool::new(false)),
964        };
965        let composite = new_from_components(vec![disk_part]).unwrap();
966        let mut input_memory = [55u8; 5];
967        let input_volatile_memory = VolatileSlice::new(&mut input_memory[..]);
968        composite
969            .write_all_at_volatile(input_volatile_memory, 0)
970            .unwrap();
971        let mut output_memory = [0u8; 5];
972        let output_volatile_memory = VolatileSlice::new(&mut output_memory[..]);
973        composite
974            .read_exact_at_volatile(output_volatile_memory, 0)
975            .unwrap();
976        assert_eq!(input_memory, output_memory);
977    }
978
979    #[test]
980    fn single_file_passthrough_file_offset() {
981        let file = tempfile().unwrap();
982        let mut input_memory = [55u8, 56u8, 57u8, 58u8, 59u8];
983        let input_volatile_memory = VolatileSlice::new(&mut input_memory[..]);
984        file.write_all_at_volatile(input_volatile_memory, 0)
985            .unwrap();
986
987        let disk_part = ComponentDiskPart {
988            file: Box::new(file),
989            offset: 0,
990            length: 100,
991            file_offset: 2,
992            needs_flush: Arc::new(AtomicBool::new(false)),
993        };
994        let composite = new_from_components(vec![disk_part]).unwrap();
995        let mut output_memory = [0u8; 3];
996        let output_volatile_memory = VolatileSlice::new(&mut output_memory[..]);
997        composite
998            .read_exact_at_volatile(output_volatile_memory, 0)
999            .unwrap();
1000        assert_eq!(input_memory[2..], output_memory);
1001    }
1002
1003    #[test]
1004    fn async_single_file_passthrough() {
1005        let file = tempfile().unwrap();
1006        let disk_part = ComponentDiskPart {
1007            file: Box::new(file),
1008            offset: 0,
1009            length: 100,
1010            file_offset: 0,
1011            needs_flush: Arc::new(AtomicBool::new(false)),
1012        };
1013        let composite = new_from_components(vec![disk_part]).unwrap();
1014        let ex = Executor::new().unwrap();
1015        ex.run_until(async {
1016            let composite = Box::new(composite).to_async_disk(&ex).unwrap();
1017            let expected = [55u8; 5];
1018            assert_eq!(
1019                composite.write_double_buffered(0, &expected).await.unwrap(),
1020                5
1021            );
1022            let mut buf = [0u8; 5];
1023            assert_eq!(
1024                composite
1025                    .read_double_buffered(0, &mut buf[..])
1026                    .await
1027                    .unwrap(),
1028                5
1029            );
1030            assert_eq!(buf, expected);
1031        })
1032        .unwrap();
1033    }
1034
1035    #[test]
1036    fn async_single_file_passthrough_offset() {
1037        let file = tempfile().unwrap();
1038        let mut input_memory = [55u8, 56u8, 57u8, 58u8, 59u8];
1039        let input_volatile_memory = VolatileSlice::new(&mut input_memory[..]);
1040        file.write_all_at_volatile(input_volatile_memory, 0)
1041            .unwrap();
1042
1043        let disk_part = ComponentDiskPart {
1044            file: Box::new(file),
1045            offset: 0,
1046            length: 100,
1047            file_offset: 2,
1048            needs_flush: Arc::new(AtomicBool::new(false)),
1049        };
1050        let composite = new_from_components(vec![disk_part]).unwrap();
1051        let ex = Executor::new().unwrap();
1052        ex.run_until(async {
1053            let composite = Box::new(composite).to_async_disk(&ex).unwrap();
1054            let mut buf = [0u8; 3];
1055            assert_eq!(
1056                composite
1057                    .read_double_buffered(0, &mut buf[..])
1058                    .await
1059                    .unwrap(),
1060                3
1061            );
1062            assert_eq!(input_memory[2..], buf);
1063        })
1064        .unwrap();
1065    }
1066
1067    #[test]
1068    fn triple_file_descriptors() {
1069        let file1 = tempfile().unwrap();
1070        let file2 = tempfile().unwrap();
1071        let file3 = tempfile().unwrap();
1072        let mut in_descriptors = vec![
1073            file1.as_raw_descriptor(),
1074            file2.as_raw_descriptor(),
1075            file3.as_raw_descriptor(),
1076        ];
1077        in_descriptors.sort_unstable();
1078        let disk_part1 = ComponentDiskPart {
1079            file: Box::new(file1),
1080            offset: 0,
1081            length: 100,
1082            file_offset: 0,
1083            needs_flush: Arc::new(AtomicBool::new(false)),
1084        };
1085        let disk_part2 = ComponentDiskPart {
1086            file: Box::new(file2),
1087            offset: 100,
1088            length: 100,
1089            file_offset: 0,
1090            needs_flush: Arc::new(AtomicBool::new(false)),
1091        };
1092        let disk_part3 = ComponentDiskPart {
1093            file: Box::new(file3),
1094            offset: 200,
1095            length: 100,
1096            file_offset: 0,
1097            needs_flush: Arc::new(AtomicBool::new(false)),
1098        };
1099        let composite = new_from_components(vec![disk_part1, disk_part2, disk_part3]).unwrap();
1100        let mut out_descriptors = composite.as_raw_descriptors();
1101        out_descriptors.sort_unstable();
1102        assert_eq!(in_descriptors, out_descriptors);
1103    }
1104
1105    #[test]
1106    fn triple_file_passthrough() {
1107        let file1 = tempfile().unwrap();
1108        let file2 = tempfile().unwrap();
1109        let file3 = tempfile().unwrap();
1110        let disk_part1 = ComponentDiskPart {
1111            file: Box::new(file1),
1112            offset: 0,
1113            length: 100,
1114            file_offset: 0,
1115            needs_flush: Arc::new(AtomicBool::new(false)),
1116        };
1117        let disk_part2 = ComponentDiskPart {
1118            file: Box::new(file2),
1119            offset: 100,
1120            length: 100,
1121            file_offset: 0,
1122            needs_flush: Arc::new(AtomicBool::new(false)),
1123        };
1124        let disk_part3 = ComponentDiskPart {
1125            file: Box::new(file3),
1126            offset: 200,
1127            length: 100,
1128            file_offset: 0,
1129            needs_flush: Arc::new(AtomicBool::new(false)),
1130        };
1131        let composite = new_from_components(vec![disk_part1, disk_part2, disk_part3]).unwrap();
1132        let mut input_memory = [55u8; 200];
1133        let input_volatile_memory = VolatileSlice::new(&mut input_memory[..]);
1134        composite
1135            .write_all_at_volatile(input_volatile_memory, 50)
1136            .unwrap();
1137        let mut output_memory = [0u8; 200];
1138        let output_volatile_memory = VolatileSlice::new(&mut output_memory[..]);
1139        composite
1140            .read_exact_at_volatile(output_volatile_memory, 50)
1141            .unwrap();
1142        assert!(input_memory.iter().eq(output_memory.iter()));
1143    }
1144
1145    #[test]
1146    fn async_triple_file_passthrough() {
1147        let file1 = tempfile().unwrap();
1148        let file2 = tempfile().unwrap();
1149        let file3 = tempfile().unwrap();
1150        let disk_part1 = ComponentDiskPart {
1151            file: Box::new(file1),
1152            offset: 0,
1153            length: 100,
1154            file_offset: 0,
1155            needs_flush: Arc::new(AtomicBool::new(false)),
1156        };
1157        let disk_part2 = ComponentDiskPart {
1158            file: Box::new(file2),
1159            offset: 100,
1160            length: 100,
1161            file_offset: 0,
1162            needs_flush: Arc::new(AtomicBool::new(false)),
1163        };
1164        let disk_part3 = ComponentDiskPart {
1165            file: Box::new(file3),
1166            offset: 200,
1167            length: 100,
1168            file_offset: 0,
1169            needs_flush: Arc::new(AtomicBool::new(false)),
1170        };
1171        let composite = new_from_components(vec![disk_part1, disk_part2, disk_part3]).unwrap();
1172        let ex = Executor::new().unwrap();
1173        ex.run_until(async {
1174            let composite = Box::new(composite).to_async_disk(&ex).unwrap();
1175
1176            let expected = [55u8; 200];
1177            assert_eq!(
1178                composite.write_double_buffered(0, &expected).await.unwrap(),
1179                100
1180            );
1181            assert_eq!(
1182                composite
1183                    .write_double_buffered(100, &expected[100..])
1184                    .await
1185                    .unwrap(),
1186                100
1187            );
1188
1189            let mut buf = [0u8; 200];
1190            assert_eq!(
1191                composite
1192                    .read_double_buffered(0, &mut buf[..])
1193                    .await
1194                    .unwrap(),
1195                100
1196            );
1197            assert_eq!(
1198                composite
1199                    .read_double_buffered(100, &mut buf[100..])
1200                    .await
1201                    .unwrap(),
1202                100
1203            );
1204            assert_eq!(buf, expected);
1205        })
1206        .unwrap();
1207    }
1208
1209    #[test]
1210    fn async_triple_file_punch_hole() {
1211        let file1 = tempfile().unwrap();
1212        let file2 = tempfile().unwrap();
1213        let file3 = tempfile().unwrap();
1214        let disk_part1 = ComponentDiskPart {
1215            file: Box::new(file1),
1216            offset: 0,
1217            length: 100,
1218            file_offset: 0,
1219            needs_flush: Arc::new(AtomicBool::new(false)),
1220        };
1221        let disk_part2 = ComponentDiskPart {
1222            file: Box::new(file2),
1223            offset: 100,
1224            length: 100,
1225            file_offset: 0,
1226            needs_flush: Arc::new(AtomicBool::new(false)),
1227        };
1228        let disk_part3 = ComponentDiskPart {
1229            file: Box::new(file3),
1230            offset: 200,
1231            length: 100,
1232            file_offset: 0,
1233            needs_flush: Arc::new(AtomicBool::new(false)),
1234        };
1235        let composite = new_from_components(vec![disk_part1, disk_part2, disk_part3]).unwrap();
1236        let ex = Executor::new().unwrap();
1237        ex.run_until(async {
1238            let composite = Box::new(composite).to_async_disk(&ex).unwrap();
1239
1240            let input = [55u8; 300];
1241            assert_eq!(
1242                composite.write_double_buffered(0, &input).await.unwrap(),
1243                100
1244            );
1245            assert_eq!(
1246                composite
1247                    .write_double_buffered(100, &input[100..])
1248                    .await
1249                    .unwrap(),
1250                100
1251            );
1252            assert_eq!(
1253                composite
1254                    .write_double_buffered(200, &input[200..])
1255                    .await
1256                    .unwrap(),
1257                100
1258            );
1259
1260            composite.punch_hole(50, 200).await.unwrap();
1261
1262            let mut buf = [0u8; 300];
1263            assert_eq!(
1264                composite
1265                    .read_double_buffered(0, &mut buf[..])
1266                    .await
1267                    .unwrap(),
1268                100
1269            );
1270            assert_eq!(
1271                composite
1272                    .read_double_buffered(100, &mut buf[100..])
1273                    .await
1274                    .unwrap(),
1275                100
1276            );
1277            assert_eq!(
1278                composite
1279                    .read_double_buffered(200, &mut buf[200..])
1280                    .await
1281                    .unwrap(),
1282                100
1283            );
1284
1285            let mut expected = input;
1286            expected[50..250].iter_mut().for_each(|x| *x = 0);
1287            assert_eq!(buf, expected);
1288        })
1289        .unwrap();
1290    }
1291
1292    #[test]
1293    fn async_triple_file_write_zeroes() {
1294        let file1 = tempfile().unwrap();
1295        let file2 = tempfile().unwrap();
1296        let file3 = tempfile().unwrap();
1297        let disk_part1 = ComponentDiskPart {
1298            file: Box::new(file1),
1299            offset: 0,
1300            length: 100,
1301            file_offset: 0,
1302            needs_flush: Arc::new(AtomicBool::new(false)),
1303        };
1304        let disk_part2 = ComponentDiskPart {
1305            file: Box::new(file2),
1306            offset: 100,
1307            length: 100,
1308            file_offset: 0,
1309            needs_flush: Arc::new(AtomicBool::new(false)),
1310        };
1311        let disk_part3 = ComponentDiskPart {
1312            file: Box::new(file3),
1313            offset: 200,
1314            length: 100,
1315            file_offset: 0,
1316            needs_flush: Arc::new(AtomicBool::new(false)),
1317        };
1318        let composite = new_from_components(vec![disk_part1, disk_part2, disk_part3]).unwrap();
1319        let ex = Executor::new().unwrap();
1320        ex.run_until(async {
1321            let composite = Box::new(composite).to_async_disk(&ex).unwrap();
1322
1323            let input = [55u8; 300];
1324            assert_eq!(
1325                composite.write_double_buffered(0, &input).await.unwrap(),
1326                100
1327            );
1328            assert_eq!(
1329                composite
1330                    .write_double_buffered(100, &input[100..])
1331                    .await
1332                    .unwrap(),
1333                100
1334            );
1335            assert_eq!(
1336                composite
1337                    .write_double_buffered(200, &input[200..])
1338                    .await
1339                    .unwrap(),
1340                100
1341            );
1342
1343            composite.write_zeroes_at(50, 200).await.unwrap();
1344
1345            let mut buf = [0u8; 300];
1346            assert_eq!(
1347                composite
1348                    .read_double_buffered(0, &mut buf[..])
1349                    .await
1350                    .unwrap(),
1351                100
1352            );
1353            assert_eq!(
1354                composite
1355                    .read_double_buffered(100, &mut buf[100..])
1356                    .await
1357                    .unwrap(),
1358                100
1359            );
1360            assert_eq!(
1361                composite
1362                    .read_double_buffered(200, &mut buf[200..])
1363                    .await
1364                    .unwrap(),
1365                100
1366            );
1367
1368            let mut expected = input;
1369            expected[50..250].iter_mut().for_each(|x| *x = 0);
1370            assert_eq!(buf, expected);
1371        })
1372        .unwrap();
1373    }
1374
1375    // TODO: fsync on a RO file is legal, this test doesn't work as expected. Consider using a mock
1376    // DiskFile to detect the fsync calls.
1377    #[test]
1378    fn async_fsync_skips_unchanged_parts() {
1379        let mut rw_file = tempfile().unwrap();
1380        rw_file.write_all(&[0u8; 100]).unwrap();
1381        rw_file.seek(SeekFrom::Start(0)).unwrap();
1382        let mut ro_disk_image = tempfile::NamedTempFile::new().unwrap();
1383        ro_disk_image.write_all(&[0u8; 100]).unwrap();
1384        let ro_file = OpenOptions::new()
1385            .read(true)
1386            .open(ro_disk_image.path())
1387            .unwrap();
1388
1389        let rw_part = ComponentDiskPart {
1390            file: Box::new(rw_file),
1391            offset: 0,
1392            length: 100,
1393            file_offset: 0,
1394            needs_flush: Arc::new(AtomicBool::new(false)),
1395        };
1396        let ro_part = ComponentDiskPart {
1397            file: Box::new(ro_file),
1398            offset: 100,
1399            length: 100,
1400            file_offset: 0,
1401            needs_flush: Arc::new(AtomicBool::new(false)),
1402        };
1403        let composite = new_from_components(vec![rw_part, ro_part]).unwrap();
1404        let ex = Executor::new().unwrap();
1405        ex.run_until(async {
1406            let composite = Box::new(composite).to_async_disk(&ex).unwrap();
1407
1408            // Write to the RW part so that some fsync operation will occur.
1409            composite.write_zeroes_at(0, 20).await.unwrap();
1410
1411            // This is the test's assert. fsyncing should NOT touch a read-only disk part. On
1412            // Windows, this would be an error.
1413            composite.fsync().await.expect(
1414                "Failed to fsync composite disk. \
1415                     This can happen if the disk writable state is wrong.",
1416            );
1417        })
1418        .unwrap();
1419    }
1420
1421    #[test]
1422    fn beginning_size() {
1423        let mut buffer = vec![];
1424        let partitions = [0u8; GPT_NUM_PARTITIONS as usize * GPT_PARTITION_ENTRY_SIZE as usize];
1425        let disk_size = 1000 * SECTOR_SIZE;
1426        write_beginning(
1427            &mut buffer,
1428            Uuid::from_u128(0x12345678_1234_5678_abcd_12345678abcd),
1429            &partitions,
1430            42,
1431            disk_size - GPT_END_SIZE,
1432            disk_size,
1433        )
1434        .unwrap();
1435
1436        assert_eq!(buffer.len(), GPT_BEGINNING_SIZE as usize);
1437    }
1438
1439    #[test]
1440    fn end_size() {
1441        let mut buffer = vec![];
1442        let partitions = [0u8; GPT_NUM_PARTITIONS as usize * GPT_PARTITION_ENTRY_SIZE as usize];
1443        let disk_size = 1000 * SECTOR_SIZE;
1444        write_end(
1445            &mut buffer,
1446            Uuid::from_u128(0x12345678_1234_5678_abcd_12345678abcd),
1447            &partitions,
1448            42,
1449            disk_size - GPT_END_SIZE,
1450        )
1451        .unwrap();
1452
1453        assert_eq!(buffer.len(), GPT_END_SIZE as usize);
1454    }
1455
1456    /// Creates a composite disk image with no partitions.
1457    #[test]
1458    fn create_composite_disk_empty() {
1459        let mut header_image = tempfile().unwrap();
1460        let mut footer_image = tempfile().unwrap();
1461        let mut composite_image = tempfile().unwrap();
1462
1463        create_composite_disk(
1464            &[],
1465            Path::new("/zero_filler.img"),
1466            Path::new("/header_path.img"),
1467            &mut header_image,
1468            Path::new("/footer_path.img"),
1469            &mut footer_image,
1470            &mut composite_image,
1471        )
1472        .unwrap();
1473    }
1474
1475    /// Creates a composite disk image with two partitions.
1476    #[test]
1477    #[allow(clippy::unnecessary_to_owned)] // false positives
1478    fn create_composite_disk_success() {
1479        fn tmpfile(prefix: &str) -> tempfile::NamedTempFile {
1480            tempfile::Builder::new().prefix(prefix).tempfile().unwrap()
1481        }
1482
1483        let mut header_image = tmpfile("header");
1484        let mut footer_image = tmpfile("footer");
1485        let mut composite_image = tmpfile("composite");
1486
1487        // The test doesn't read these, just needs to be able to open them.
1488        let partition1 = tmpfile("partition1");
1489        let partition2 = tmpfile("partition1");
1490        let zero_filler = tmpfile("zero");
1491
1492        create_composite_disk(
1493            &[
1494                PartitionInfo {
1495                    label: "partition1".to_string(),
1496                    path: partition1.path().to_path_buf(),
1497                    partition_type: ImagePartitionType::LinuxFilesystem,
1498                    writable: false,
1499                    // Needs small amount of padding.
1500                    size: 4000,
1501                    part_guid: None,
1502                },
1503                PartitionInfo {
1504                    label: "partition2".to_string(),
1505                    path: partition2.path().to_path_buf(),
1506                    partition_type: ImagePartitionType::LinuxFilesystem,
1507                    writable: true,
1508                    // Needs no padding.
1509                    size: 4096,
1510                    part_guid: Some(Uuid::from_u128(0x4049C8DC_6C2B_C740_A95A_BDAA629D4378)),
1511                },
1512            ],
1513            zero_filler.path(),
1514            &header_image.path().to_path_buf(),
1515            header_image.as_file_mut(),
1516            &footer_image.path().to_path_buf(),
1517            footer_image.as_file_mut(),
1518            composite_image.as_file_mut(),
1519        )
1520        .unwrap();
1521
1522        // Check magic.
1523        composite_image.rewind().unwrap();
1524        let mut magic_space = [0u8; CDISK_MAGIC.len()];
1525        composite_image.read_exact(&mut magic_space[..]).unwrap();
1526        assert_eq!(magic_space, CDISK_MAGIC.as_bytes());
1527        // Check proto.
1528        let proto = CompositeDisk::parse_from_reader(&mut composite_image).unwrap();
1529        assert_eq!(
1530            proto,
1531            CompositeDisk {
1532                version: 2,
1533                component_disks: vec![
1534                    ComponentDisk {
1535                        file_path: header_image.path().to_str().unwrap().to_string(),
1536                        offset: 0,
1537                        read_write_capability: ReadWriteCapability::READ_ONLY.into(),
1538                        ..ComponentDisk::new()
1539                    },
1540                    ComponentDisk {
1541                        file_path: partition1.path().to_str().unwrap().to_string(),
1542                        offset: 0x5000, // GPT_BEGINNING_SIZE,
1543                        read_write_capability: ReadWriteCapability::READ_ONLY.into(),
1544                        ..ComponentDisk::new()
1545                    },
1546                    ComponentDisk {
1547                        file_path: zero_filler.path().to_str().unwrap().to_string(),
1548                        offset: 0x5fa0, // GPT_BEGINNING_SIZE + 4000,
1549                        read_write_capability: ReadWriteCapability::READ_ONLY.into(),
1550                        ..ComponentDisk::new()
1551                    },
1552                    ComponentDisk {
1553                        file_path: partition2.path().to_str().unwrap().to_string(),
1554                        offset: 0x6000, // GPT_BEGINNING_SIZE + 4096,
1555                        read_write_capability: ReadWriteCapability::READ_WRITE.into(),
1556                        ..ComponentDisk::new()
1557                    },
1558                    ComponentDisk {
1559                        file_path: footer_image.path().to_str().unwrap().to_string(),
1560                        offset: 0x7000, // GPT_BEGINNING_SIZE + 4096 + 4096,
1561                        read_write_capability: ReadWriteCapability::READ_ONLY.into(),
1562                        ..ComponentDisk::new()
1563                    },
1564                ],
1565                length: 0xc000,
1566                ..CompositeDisk::new()
1567            }
1568        );
1569
1570        // Open the file as a composite disk and do some basic GPT header/footer validation.
1571        let ex = Executor::new().unwrap();
1572        ex.run_until(async {
1573            let disk = Box::new(
1574                CompositeDiskFile::from_file(
1575                    composite_image.into_file(),
1576                    DiskFileParams {
1577                        path: "/foo".into(),
1578                        is_read_only: true,
1579                        lock: false,
1580                        ..Default::default()
1581                    },
1582                )
1583                .unwrap(),
1584            )
1585            .to_async_disk(&ex)
1586            .unwrap();
1587
1588            let header_offset = SECTOR_SIZE;
1589            let footer_offset = disk.get_len().unwrap() - SECTOR_SIZE;
1590
1591            let mut header_bytes = [0u8; SECTOR_SIZE as usize];
1592            assert_eq!(
1593                disk.read_double_buffered(header_offset, &mut header_bytes[..])
1594                    .await
1595                    .unwrap(),
1596                SECTOR_SIZE as usize
1597            );
1598
1599            let mut footer_bytes = [0u8; SECTOR_SIZE as usize];
1600            assert_eq!(
1601                disk.read_double_buffered(footer_offset, &mut footer_bytes[..])
1602                    .await
1603                    .unwrap(),
1604                SECTOR_SIZE as usize
1605            );
1606
1607            // Check the header and footer fields point to each other correctly.
1608            let header_current_lba = u64::from_le_bytes(header_bytes[24..32].try_into().unwrap());
1609            assert_eq!(header_current_lba * SECTOR_SIZE, header_offset);
1610            let header_backup_lba = u64::from_le_bytes(header_bytes[32..40].try_into().unwrap());
1611            assert_eq!(header_backup_lba * SECTOR_SIZE, footer_offset);
1612
1613            let footer_current_lba = u64::from_le_bytes(footer_bytes[24..32].try_into().unwrap());
1614            assert_eq!(footer_current_lba * SECTOR_SIZE, footer_offset);
1615            let footer_backup_lba = u64::from_le_bytes(footer_bytes[32..40].try_into().unwrap());
1616            assert_eq!(footer_backup_lba * SECTOR_SIZE, header_offset);
1617
1618            // Header and footer should be equal if we zero the pointers and CRCs.
1619            header_bytes[16..20].fill(0);
1620            header_bytes[24..40].fill(0);
1621            footer_bytes[16..20].fill(0);
1622            footer_bytes[24..40].fill(0);
1623            assert_eq!(header_bytes, footer_bytes);
1624        })
1625        .unwrap();
1626    }
1627
1628    /// Attempts to create a composite disk image with two partitions with the same label.
1629    #[test]
1630    fn create_composite_disk_duplicate_label() {
1631        let mut header_image = tempfile().unwrap();
1632        let mut footer_image = tempfile().unwrap();
1633        let mut composite_image = tempfile().unwrap();
1634
1635        let result = create_composite_disk(
1636            &[
1637                PartitionInfo {
1638                    label: "label".to_string(),
1639                    path: "/partition1.img".to_string().into(),
1640                    partition_type: ImagePartitionType::LinuxFilesystem,
1641                    writable: false,
1642                    size: 0,
1643                    part_guid: None,
1644                },
1645                PartitionInfo {
1646                    label: "label".to_string(),
1647                    path: "/partition2.img".to_string().into(),
1648                    partition_type: ImagePartitionType::LinuxFilesystem,
1649                    writable: true,
1650                    size: 0,
1651                    part_guid: None,
1652                },
1653            ],
1654            Path::new("/zero_filler.img"),
1655            Path::new("/header_path.img"),
1656            &mut header_image,
1657            Path::new("/footer_path.img"),
1658            &mut footer_image,
1659            &mut composite_image,
1660        );
1661        assert!(matches!(result, Err(Error::DuplicatePartitionLabel(label)) if label == "label"));
1662    }
1663
1664    #[test]
1665    fn clone_composite_disk() {
1666        let tmp_dir = tempfile::tempdir().unwrap();
1667        let part1_path = tmp_dir.path().join("part1.img");
1668        let part1 = File::create(&part1_path).unwrap();
1669        part1.set_len(4096).unwrap();
1670        let part2_path = tmp_dir.path().join("part2.img");
1671        let part2 = File::create(&part2_path).unwrap();
1672        part2.set_len(4096).unwrap();
1673
1674        let zero_filler_path = tmp_dir.path().join("zero_filler.img");
1675        File::create(&zero_filler_path)
1676            .unwrap()
1677            .set_len(4096 * 16)
1678            .unwrap();
1679        let header_path = tmp_dir.path().join("header.img");
1680        let mut header_image = OpenOptions::new()
1681            .read(true)
1682            .write(true)
1683            .create_new(true)
1684            .open(&header_path)
1685            .unwrap();
1686        let footer_path = tmp_dir.path().join("footer.img");
1687        let mut footer_image = OpenOptions::new()
1688            .read(true)
1689            .write(true)
1690            .create_new(true)
1691            .open(&footer_path)
1692            .unwrap();
1693        let composite_path = tmp_dir.path().join("composite.img");
1694        let mut composite_file = OpenOptions::new()
1695            .read(true)
1696            .write(true)
1697            .create_new(true)
1698            .open(&composite_path)
1699            .unwrap();
1700
1701        create_composite_disk(
1702            &[
1703                PartitionInfo {
1704                    label: "part1".to_string(),
1705                    path: part1_path,
1706                    partition_type: ImagePartitionType::LinuxFilesystem,
1707                    writable: true,
1708                    size: 4096,
1709                    part_guid: None,
1710                },
1711                PartitionInfo {
1712                    label: "part2".to_string(),
1713                    path: part2_path,
1714                    partition_type: ImagePartitionType::LinuxFilesystem,
1715                    writable: true,
1716                    size: 4096,
1717                    part_guid: None,
1718                },
1719            ],
1720            &zero_filler_path,
1721            &header_path,
1722            &mut header_image,
1723            &footer_path,
1724            &mut footer_image,
1725            &mut composite_file,
1726        )
1727        .unwrap();
1728
1729        let composite = CompositeDiskFile::from_file(
1730            composite_file,
1731            DiskFileParams {
1732                path: composite_path,
1733                is_read_only: false,
1734                is_sparse_file: false,
1735                is_direct: false,
1736                depth: 0,
1737                ..Default::default()
1738            },
1739        )
1740        .unwrap();
1741        let cloned = composite.try_clone().unwrap();
1742        assert_eq!(cloned.get_len().unwrap(), composite.get_len().unwrap());
1743
1744        let mut input = [0xA5u8; 16];
1745        let mut output = [0u8; 16];
1746        let offset = composite.component_disks[2].offset;
1747        composite
1748            .write_all_at_volatile(VolatileSlice::new(&mut input), offset)
1749            .unwrap();
1750        cloned
1751            .read_exact_at_volatile(VolatileSlice::new(&mut output), offset)
1752            .unwrap();
1753        assert_eq!(output, input);
1754    }
1755}