msb-imago 0.1.1

A library for accessing virtual machine disk images.
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
//! VMDK implementation.

use crate::format::builder::{FormatDriverBuilder, FormatDriverBuilderBase};
use crate::format::drivers::FormatDriverInstance;
use crate::format::gate::ImplicitOpenGate;
use crate::format::wrapped::WrappedFormat;
use crate::format::{Format, PreallocateMode};
use crate::io_buffers::IoBuffer;
use crate::misc_helpers::{invalid_data, ResultErrorContext};
use crate::storage::ext::StorageExt;
use crate::{FormatAccess, ShallowMapping, Storage, StorageOpenOptions};
use async_trait::async_trait;
use std::fmt::{self, Display, Formatter};
use std::marker::PhantomData;
use std::ops::{Range, RangeInclusive};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::{cmp, io};

/// As usual, VMDK sector size is 512 bytes as a fixed value
const VMDK_SECTOR_SIZE: u64 = 512;
/// VMDK SPARSE data signature
const VMDK4_MAGIC: u32 = 0x564d444b; // 'KDMV'
/// Supported version range
const VMDK_VERSION_RANGE: RangeInclusive<u32> = 1..=3;

/// Represents the data storage for a VMDK extent
#[derive(Debug, Clone)]
enum VmdkStorage<S: Storage + 'static> {
    /// A FLAT extent with a RAW file starting from the exact offset
    Flat {
        /// Storage object containing linear (raw) data
        file: S,
        /// Byte offset in `file` where the data for this extent begins
        offset: u64,
    },
    /// A zero-filled extent
    Zero,
}

/// VMDK extent information after parsing, before opening
#[derive(Debug)]
enum VmdkParsedStorage {
    /// A FLAT extent with a RAW file starting from the exact offset
    Flat {
        /// Path to storage object containing linear (raw) data
        filename: String,
        /// Offset, in 512-byte sectors (as written in the VMDK descriptor), where
        /// the data for this extent begins in the storage object
        offset: u64,
    },
    /// A zero-filled extent
    Zero,
}

/// Access type for VMDK extents
#[derive(Debug, Clone, PartialEq)]
enum VmdkAccessType {
    /// Read-write access
    RW,
    /// Read-only access
    RdOnly,
    /// No access
    NoAccess,
}

/// VMDK extent
#[derive(Debug)]
struct VmdkExtent<S: Storage + 'static> {
    /// Access type (RW, RDONLY, NOACCESS).
    access_type: VmdkAccessType,
    /// Part of the virtual disk covered by this extent.
    ///
    /// The start is equal to the end of the extent before it (0 if none), and the end is equal to
    /// the start plus this extent’s length.
    disk_range: Range<u64>,
    /// Data source
    ///
    /// Present if and only if the access type is not NOACCESS.
    storage: Option<VmdkStorage<S>>,
}

/// VMDK extent descriptor information after parsing, before opening
#[derive(Debug)]
struct VmdkParsedExtent {
    /// Access type (RW, RDONLY, NOACCESS).
    access_type: VmdkAccessType,
    /// Number of sectors.
    sectors: u64,
    /// Data source
    ///
    /// Present if and only if the access type is not NOACCESS.
    storage: Option<VmdkParsedStorage>,
}

/// VMDK disk image format implementation.
#[derive(Debug)]
pub struct Vmdk<S: Storage + 'static, F: WrappedFormat<S> + 'static = FormatAccess<S>> {
    /// Storage object containing the VMDK descriptor file
    descriptor_file: Arc<S>,

    /// Backing image type.
    ///
    /// We do not support backing (parent) images yet, but capture the type so that when we do
    /// support it, the change will be syntactically compatible.
    parent_type: PhantomData<F>,

    /// Base options to be used for implicitly opened storage objects.
    storage_open_options: StorageOpenOptions,

    /// Virtual disk size in bytes.
    size: AtomicU64,

    /// Parsed VMDK descriptor.
    desc: VmdkDesc,

    /// Extent information as parsed from the VMDK descriptor file.
    parsed_extents: Vec<VmdkParsedExtent>,

    /// Storage objects for each extent.
    extents: Vec<VmdkExtent<S>>,
}

/// VMDK descriptor information.
#[derive(Debug, Clone)]
struct VmdkDesc {
    /// Version number of the VMDK descriptor
    version: u32,
    /// Content ID
    cid: String,
    /// Content ID of the parent link
    parent_cid: String,
    /// Type of virtual disk
    create_type: String,
    /// The disk geometry value (sectors)
    sectors: u64,
    /// The disk geometry value (heads)
    heads: u64,
    /// The disk geometry value (cylinders)
    cylinders: u64,
}

impl VmdkParsedExtent {
    /// Parse an extent descriptor line.
    fn try_from_descriptor_line(line: &str) -> io::Result<VmdkParsedExtent> {
        // See https://github.com/libyal/libvmdk/blob/main/documentation/VMWare%20Virtual%20Disk%20Format%20(VMDK).asciidoc#221-extent-descriptor

        let mut parts = line.split_whitespace();

        let access_type = match parts
            .next()
            .ok_or_else(|| invalid_data("Access type missing"))?
        {
            "RW" => VmdkAccessType::RW,
            "RDONLY" => VmdkAccessType::RdOnly,
            "NOACCESS" => VmdkAccessType::NoAccess,
            other => return Err(invalid_data(format!("Invalid access type '{other}'"))),
        };

        let sectors = parts
            .next()
            .ok_or_else(|| invalid_data("Sector count missing"))?
            .parse()
            .map_err(|_| invalid_data("Invalid sector count"))?;

        if access_type == VmdkAccessType::NoAccess {
            return Ok(VmdkParsedExtent {
                access_type,
                sectors,
                storage: None,
            });
        }

        let extent_type = parts
            .next()
            .ok_or_else(|| invalid_data("Extent type missing"))?;
        if extent_type == "ZERO" {
            return Ok(VmdkParsedExtent {
                access_type,
                sectors,
                storage: Some(VmdkParsedStorage::Zero),
            });
        }
        if extent_type != "FLAT" {
            return Err(io::Error::new(
                io::ErrorKind::Unsupported,
                format!("Unsupported extent type {extent_type}"),
            ));
        }

        // filename is enclosed in quotes and may contain spaces, so split the whole line by quotes
        // (We could simplify this if we could do `line.splitn_whitespace(4)` at the beginning of
        // this function, but `splitn_whitespace()` does not exist.)
        let mut quote_split = line.splitn(3, '"').map(|part| part.trim());
        // We know the line isn’t empty, so we must at least get one part
        let before_filename = quote_split.next().unwrap();
        let filename = quote_split
            .next()
            .ok_or_else(|| invalid_data("Extent filename missing"))?;
        let after_filename = quote_split
            .next()
            .ok_or_else(|| invalid_data("Extent filename not terminated"))?;

        let part_count_before_filename = before_filename.split_whitespace().count();
        if part_count_before_filename != 3 {
            return Err(invalid_data(format!(
                "Expected filename at field index 3, found at {part_count_before_filename}"
            )));
        }

        // Continue parsing after filename
        parts = after_filename.split_whitespace();

        let offset = parts
            .next()
            .map_or(Ok(0), |ofs_str| ofs_str.parse())
            .map_err(|_| invalid_data("Invalid offset"))?;

        Ok(VmdkParsedExtent {
            access_type,
            sectors,
            storage: Some(VmdkParsedStorage::Flat {
                filename: filename.to_string(),
                offset,
            }),
        })
    }
}

/// Remove double quotes around `input` if there are any.
fn strip_quotes(input: &str) -> &str {
    input
        .strip_prefix('"')
        .and_then(|value| value.strip_suffix('"'))
        .unwrap_or(input)
}

/// Helper to parse an integer from the descriptor file.
fn parse_desc_value<F: FromStr>(key: &str, value: &str) -> io::Result<F> {
    let stripped = strip_quotes(value);

    stripped
        .parse::<F>()
        .map_err(|_| invalid_data(format!("Invalid '{key}' value: {stripped}")))
}

impl<S: Storage + 'static, F: WrappedFormat<S> + 'static> Vmdk<S, F> {
    /// Create a new [`FormatDriverBuilder`] instance for the given image.
    pub fn builder(image: S) -> VmdkOpenBuilder<S, F> {
        VmdkOpenBuilder::new(image)
    }

    /// Create a new [`FormatDriverBuilder`] instance for an image under the given path.
    pub fn builder_path<P: AsRef<Path>>(image_path: P) -> VmdkOpenBuilder<S, F> {
        VmdkOpenBuilder::new_path(image_path)
    }

    /// Open an extent from the information in `extent`.
    ///
    /// `in_disk_offset` is the offset in the virtual disk where this extent fits in.  It should be
    /// the end offset of the extent before it.
    async fn open_implicit_extent<G: ImplicitOpenGate<S>>(
        &self,
        extent: &VmdkParsedExtent,
        in_disk_offset: u64,
        open_gate: &mut G,
    ) -> io::Result<VmdkExtent<S>> {
        let sectors = extent.sectors;
        let size = sectors.checked_mul(VMDK_SECTOR_SIZE).ok_or_else(|| {
            invalid_data(format!(
                "Extent size overflow: {sectors} * {VMDK_SECTOR_SIZE}"
            ))
        })?;
        let disk_range = in_disk_offset..in_disk_offset.checked_add(size).ok_or_else(|| {
            invalid_data(format!("Extent offset overflow: {in_disk_offset} + {size}"))
        })?;

        let Some(storage) = extent.storage.as_ref() else {
            return Ok(VmdkExtent {
                access_type: extent.access_type.clone(),
                disk_range,
                storage: None,
            });
        };

        let storage = match storage {
            VmdkParsedStorage::Flat { filename, offset } => {
                let absolute = self
                    .descriptor_file
                    .resolve_relative_path(filename)
                    .err_context(|| format!("Cannot resolve storage file name {filename}"))?;

                let mut file_opts = self.storage_open_options.clone().filename(absolute.clone());
                if extent.access_type == VmdkAccessType::RdOnly {
                    file_opts = file_opts.write(false);
                }

                let file = open_gate
                    .open_storage(file_opts)
                    .await
                    .err_context(|| format!("Data storage file {absolute:?}"))?;

                VmdkStorage::Flat {
                    file,
                    // The FLAT offset is in 512-byte sectors (like the extent length);
                    // scale it to bytes to match the byte-based `disk_range`.
                    offset: (*offset).checked_mul(VMDK_SECTOR_SIZE).ok_or_else(|| {
                        invalid_data(format!(
                            "Extent offset overflow: {offset} * {VMDK_SECTOR_SIZE}"
                        ))
                    })?,
                }
            }

            VmdkParsedStorage::Zero => VmdkStorage::Zero,
        };

        Ok(VmdkExtent {
            access_type: extent.access_type.clone(),
            disk_range,
            storage: Some(storage),
        })
    }

    /// Checks if the VMDK version is supported and returns an error if not
    fn error_out_unsupported_version(&self) -> io::Result<()> {
        let version = self.desc.version;
        if !VMDK_VERSION_RANGE.contains(&version) {
            return Err(io::Error::new(
                io::ErrorKind::Unsupported,
                format!("unsupported version {version}"),
            ));
        }
        Ok(())
    }

    /// Parse a line in the VMDK descriptor file
    fn parse_descriptor_line(&mut self, line: &str) -> io::Result<()> {
        let line = line.trim();

        if line.is_empty() || line.starts_with('#') {
            return Ok(());
        }

        // Parse extent descriptors (RW/RDONLY/NOACCESS)
        if let Some((access, _)) = line.split_once(char::is_whitespace) {
            if matches!(access, "RW" | "RDONLY" | "NOACCESS") {
                let extent = VmdkParsedExtent::try_from_descriptor_line(line)?;
                self.parsed_extents.push(extent);
                return Ok(());
            }
        }

        let Some((key, value)) = line.split_once('=') else {
            // Silently ignore
            return Ok(());
        };
        let key = key.trim();
        let value = value.trim();

        match key {
            "version" => {
                self.desc.version = value
                    .parse()
                    .map_err(|_| invalid_data("Invalid version format"))?;
            }
            "CID" => self.desc.cid = value.to_string(),
            "parentCID" => self.desc.parent_cid = value.to_string(),
            "createType" => self.desc.create_type = strip_quotes(value).to_string(),
            "parentFileNameHint" => {
                return Err(io::Error::new(
                    io::ErrorKind::Unsupported,
                    "unsupported VMDK differential image (delta link)",
                ))
            }
            "ddb.geometry.sectors" => self.desc.sectors = parse_desc_value(key, value)?,
            "ddb.geometry.heads" => self.desc.heads = parse_desc_value(key, value)?,
            "ddb.geometry.cylinders" => self.desc.cylinders = parse_desc_value(key, value)?,

            // Ignore unidentified "ddb." (The Disk Database) items
            key if key.starts_with("ddb.") => (),

            key => {
                return Err(invalid_data(format!(
                    "Unrecognized VMDK descriptor file key '{key}'"
                )))
            }
        }

        Ok(())
    }

    /// Read and parse the VMDK descriptor by reading in lines until we find the end
    async fn parse_descriptor_file(&mut self) -> io::Result<()> {
        let desc_file_sz = self.descriptor_file.size()?;
        if desc_file_sz < 4 {
            return Err(invalid_data("VMDK descriptor file too short"));
        }
        // Sanity check to avoid unbounded allocation
        if desc_file_sz > 2 * 1024 * 1024 {
            return Err(invalid_data(
                "VMDK descriptor file too long (max. 2 MB supported)",
            ));
        }

        let desc_file_sz: usize = desc_file_sz.try_into().unwrap();
        let mut desc_file = IoBuffer::new(desc_file_sz, self.descriptor_file.mem_align())?;
        self.descriptor_file.read(desc_file.as_mut(), 0).await?;

        let desc_file = desc_file.as_ref().into_slice();

        // Check if it's a SPARSE format, bail it out now
        if u32::from_le_bytes(desc_file[..4].try_into().unwrap()) == VMDK4_MAGIC {
            return Err(io::Error::new(
                io::ErrorKind::Unsupported,
                "Unsupported VMDK sparse data file",
            ));
        }

        for (line_i, line) in desc_file.split(|chr| *chr == b'\n').enumerate() {
            let line = str::from_utf8(line).map_err(|e| {
                invalid_data(format!(
                    "{}: Line {}: {e}",
                    self.descriptor_file,
                    line_i + 1
                ))
            })?;

            self.parse_descriptor_line(line)
                .err_context(|| format!("{}: Line {}", self.descriptor_file, line_i + 1))?;
        }

        self.error_out_unsupported_version()?;
        self.size = self
            .parsed_extents
            .iter()
            .try_fold(0u64, |sum, extent| {
                let sectors = extent.sectors;
                let size = sectors.checked_mul(VMDK_SECTOR_SIZE).ok_or_else(|| {
                    invalid_data(format!(
                        "Extent size overflow: {sectors} * {VMDK_SECTOR_SIZE}"
                    ))
                })?;
                sum.checked_add(size)
                    .ok_or_else(|| invalid_data(format!("Extent offset overflow: {sum} + {size}")))
            })?
            .into();

        Ok(())
    }

    /// Internal implementation for opening a VMDK image.
    async fn do_open(
        descriptor_file: S,
        storage_open_options: StorageOpenOptions,
    ) -> io::Result<Self> {
        let mut vmdk = Vmdk {
            descriptor_file: Arc::new(descriptor_file),
            parent_type: PhantomData,
            desc: VmdkDesc {
                version: 0,
                cid: String::new(),
                parent_cid: String::new(),
                create_type: String::new(),
                sectors: 0,
                heads: 0,
                cylinders: 0,
            },
            parsed_extents: vec![],
            extents: vec![],
            size: 0.into(),
            storage_open_options,
        };

        vmdk.parse_descriptor_file().await?;
        Ok(vmdk)
    }

    /// Opens a VMDK file.
    ///
    /// This will not open any other storage objects needed, i.e. no extent data files.  Handling
    /// those manually is not yet supported, so you have to make use of the implicit references
    /// given in the image header, for which you can use
    /// [`Vmdk::open_implicit_dependencies_gated()`].
    pub async fn open_image(descriptor_file: S, writable: bool) -> io::Result<Self> {
        if writable {
            return Err(io::Error::new(
                io::ErrorKind::Unsupported,
                "No VMDK write support",
            ));
        }
        Self::do_open(descriptor_file, StorageOpenOptions::new()).await
    }

    /// Open all implicit dependencies.
    ///
    /// In the case of VMDK, these are the extent data files.
    pub async fn open_implicit_dependencies_gated<G: ImplicitOpenGate<S>>(
        &mut self,
        mut gate: G,
    ) -> io::Result<()> {
        if self.extents.is_empty() {
            let mut in_disk_offset = 0;
            for extent in &self.parsed_extents {
                let opened = self
                    .open_implicit_extent(extent, in_disk_offset, &mut gate)
                    .await?;
                in_disk_offset = opened.disk_range.end;
                self.extents.push(opened);
            }
        }

        Ok(())
    }

    /// Return the extent covering `offset`, if any.
    fn get_extent_at(&self, offset: u64) -> Option<&VmdkExtent<S>> {
        self.extents
            .binary_search_by(|extent| {
                if extent.disk_range.contains(&offset) {
                    cmp::Ordering::Equal
                } else if extent.disk_range.end <= offset {
                    // disk_range is half-open [start, end); use <= so that
                    // end == offset returns Less, not Greater.
                    cmp::Ordering::Less
                } else {
                    cmp::Ordering::Greater
                }
            })
            .ok()
            .map(|index| &self.extents[index])
    }
}

impl<S: Storage + 'static, F: WrappedFormat<S> + 'static> Display for Vmdk<S, F> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "vmdk[{}]", self.descriptor_file)
    }
}

#[async_trait(?Send)]
impl<S: Storage + 'static, F: WrappedFormat<S> + 'static> FormatDriverInstance for Vmdk<S, F> {
    type Storage = S;

    fn format(&self) -> Format {
        Format::Vmdk
    }

    async unsafe fn probe(storage: &S) -> io::Result<bool>
    where
        Self: Sized,
    {
        // Check that the potential descriptor file has a reasonable length, is utf8, and contains
        // a supported `version` key.
        // (Or has the `VMDK4_MAGIC`.)

        let desc_file_size = storage.size()?;
        if !(4..=2 * 1024 * 1024).contains(&desc_file_size) {
            return Ok(false);
        }

        let desc_file_size: usize = desc_file_size.try_into().unwrap();
        let mut desc_file = IoBuffer::new(desc_file_size, storage.mem_align())?;
        storage.read(desc_file.as_mut(), 0).await?;

        let desc_file = desc_file.as_ref().into_slice();
        if u32::from_le_bytes(desc_file[..4].try_into().unwrap()) == VMDK4_MAGIC {
            return Ok(true);
        }

        for line in desc_file.split(|chr| *chr == b'\n') {
            let Ok(line) = str::from_utf8(line) else {
                return Ok(false);
            };

            let Some((key, value)) = line.split_once('=') else {
                continue;
            };
            if key.trim() == "version" {
                let Ok(version) = value.trim().parse() else {
                    return Ok(false);
                };
                return Ok(VMDK_VERSION_RANGE.contains(&version));
            }
        }

        Ok(false)
    }

    fn size(&self) -> u64 {
        self.size.load(Ordering::Relaxed)
    }

    fn zero_granularity(&self) -> Option<u64> {
        None
    }

    fn collect_storage_dependencies(&self) -> Vec<&S> {
        let mut v = vec![self.descriptor_file.as_ref()];
        for e in &self.extents {
            let Some(storage) = e.storage.as_ref() else {
                continue;
            };
            match storage {
                VmdkStorage::Flat { file, offset: _ } => v.push(file),
                VmdkStorage::Zero => (),
            }
        }
        v
    }

    fn writable(&self) -> bool {
        false
    }

    async fn get_mapping<'a>(
        &'a self,
        offset: u64,
        max_length: u64,
    ) -> io::Result<(ShallowMapping<'a, S>, u64)> {
        let max_length = match self.size().checked_sub(offset) {
            None | Some(0) => return Ok((ShallowMapping::Eof {}, 0)),
            Some(remaining) => cmp::min(remaining, max_length),
        };

        let Some(extent) = self.get_extent_at(offset) else {
            return Ok((ShallowMapping::Eof {}, 0));
        };
        // `get_extent_at` guarantees this won’t underflow
        let in_extent_offset = offset - extent.disk_range.start;

        let writable = match extent.access_type {
            VmdkAccessType::RW => true,
            VmdkAccessType::RdOnly => false,
            VmdkAccessType::NoAccess => {
                // Is that right?  Should this be ::Special?
                return Err(io::Error::other("NOACCESS extent is accessed"));
            }
        };

        // `access_type != NoAccess`, so `unwrap()` is safe
        let mapping = match extent.storage.as_ref().unwrap() {
            VmdkStorage::Flat {
                file,
                offset: base_offset,
            } => ShallowMapping::Raw {
                storage: file,
                offset: base_offset.checked_add(in_extent_offset).ok_or_else(|| {
                    invalid_data(format!(
                        "Extent offset overflow: {base_offset} + {in_extent_offset}"
                    ))
                })?,
                writable,
            },

            VmdkStorage::Zero => ShallowMapping::Zero { explicit: true },
        };

        Ok((
            mapping,
            cmp::min(max_length, extent.disk_range.end - offset),
        ))
    }

    async fn ensure_data_mapping<'a>(
        &'a self,
        _offset: u64,
        _length: u64,
        _overwrite: bool,
    ) -> io::Result<(&'a S, u64, u64)> {
        Err(io::Error::other("Image is read-only"))
    }

    async fn flush(&self) -> io::Result<()> {
        Ok(())
    }

    async fn sync(&self) -> io::Result<()> {
        Ok(())
    }

    async unsafe fn invalidate_cache(&self) -> io::Result<()> {
        Ok(())
    }

    async fn resize_grow(&self, _new_size: u64, _prealloc_mode: PreallocateMode) -> io::Result<()> {
        Err(io::Error::other("Image is read-only"))
    }

    async fn resize_shrink(&mut self, _new_size: u64) -> io::Result<()> {
        Err(io::Error::other("Image is read-only"))
    }
}

/// Options builder for opening a VMDK image.
pub struct VmdkOpenBuilder<S: Storage + 'static, F: WrappedFormat<S> + 'static = FormatAccess<S>>(
    FormatDriverBuilderBase<S>,
    PhantomData<F>,
);

impl<S: Storage + 'static, F: WrappedFormat<S> + 'static> FormatDriverBuilder<S>
    for VmdkOpenBuilder<S, F>
{
    type Format = Vmdk<S, F>;
    const FORMAT: Format = Format::Vmdk;

    fn new(image: S) -> Self {
        VmdkOpenBuilder(FormatDriverBuilderBase::new(image), PhantomData)
    }

    fn new_path<P: AsRef<Path>>(path: P) -> Self {
        VmdkOpenBuilder(FormatDriverBuilderBase::new_path(path), PhantomData)
    }

    fn write(mut self, writable: bool) -> Self {
        self.0.set_write(writable);
        self
    }

    fn storage_open_options(mut self, options: StorageOpenOptions) -> Self {
        self.0.set_storage_open_options(options);
        self
    }

    async fn open<G: ImplicitOpenGate<S>>(self, mut gate: G) -> io::Result<Self::Format> {
        if self.0.get_writable() {
            return Err(io::Error::new(
                io::ErrorKind::Unsupported,
                "No VMDK write support",
            ));
        }

        let file = self.0.open_image(&mut gate).await?;
        let mut vmdk = Vmdk::open_image(file, false).await?;
        vmdk.open_implicit_dependencies_gated(gate).await?;
        Ok(vmdk)
    }

    fn get_image_path(&self) -> Option<PathBuf> {
        self.0.get_image_path()
    }

    fn get_writable(&self) -> bool {
        self.0.get_writable()
    }

    fn get_storage_open_options(&self) -> Option<&StorageOpenOptions> {
        self.0.get_storage_opts()
    }
}

//--------------------------------------------------------------------------------------------------
// Tests
//--------------------------------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::Vmdk;
    use crate::file::File;
    use crate::format::access::{FormatAccess, FormatReadPlanStep};
    use crate::{FormatDriverBuilder, PermissiveImplicitOpenGate};
    use std::io;

    /// A FLAT extent's offset is in 512-byte sectors, so a nonzero-offset extent (the
    /// 2nd+ slice of a >2 GiB file) must resolve to byte `offset * 512`, not `offset`.
    #[test]
    fn flat_nonzero_offset_is_scaled_sectors_to_bytes() -> io::Result<()> {
        let runtime = tokio::runtime::Builder::new_current_thread().build()?;
        runtime.block_on(async {
            // No `tempfile` dev-dependency; use a pid-unique scratch dir.
            let dir = std::env::temp_dir().join(format!("imago_vmdk_off_{}", std::process::id()));
            std::fs::create_dir_all(&dir)?;
            let flat_path = dir.join("layer.flat");
            let desc_path = dir.join("disk.vmdk");

            // 4-sector (2048-byte) backing file is enough for two 2-sector extents.
            std::fs::write(&flat_path, vec![0u8; 4 * 512])?;

            // Two FLAT extents into one file; the 2nd at a nonzero sector offset (2).
            let desc = "# Disk DescriptorFile\n\
                version=1\n\
                CID=fffffffe\n\
                parentCID=ffffffff\n\
                createType=\"twoGbMaxExtentFlat\"\n\
                \n\
                RW 2 FLAT \"layer.flat\" 0\n\
                RW 2 FLAT \"layer.flat\" 2\n\
                \n\
                ddb.geometry.cylinders = \"1\"\n\
                ddb.geometry.heads = \"16\"\n\
                ddb.geometry.sectors = \"63\"\n";
            std::fs::write(&desc_path, desc)?;

            let vmdk = Vmdk::<File>::builder_path(&desc_path)
                .open(PermissiveImplicitOpenGate::default())
                .await?;
            let image = FormatAccess::new(vmdk);

            // Resolve a read at the start of the 2nd extent (virtual offset 1024).
            let plan = image.plan_read(1024, 512).await?;
            let steps = plan.steps();
            assert!(!steps.is_empty(), "expected a read step, got none");
            // Assert on `offset` (resolved backing offset), not `image_offset`
            // (the virtual offset, which is 1024 regardless of the bug).
            let storage_offset = match &steps[0] {
                FormatReadPlanStep::Raw { offset, .. } => *offset,
                step => panic!("expected a Raw step, got {step:?}"),
            };

            // 2 sectors * 512 = 1024 (the bug yielded the raw sector value, 2).
            assert_eq!(
                storage_offset, 1024,
                "FLAT offset must be scaled sectors->bytes; got {storage_offset}"
            );

            std::fs::remove_dir_all(&dir).ok();
            Ok(())
        })
    }
}