Skip to main content

loader/
linux.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Linux specific loader definitions and implementation.
5
6pub mod mptable_boot;
7
8use crate::common::ChunkBuf;
9use crate::common::ImportFileRegion;
10use crate::common::ImportFileRegionError;
11use crate::common::ReadSeek;
12use crate::common::import_default_gdt;
13use crate::elf::load_static_elf;
14use crate::importer::Aarch64Register;
15use crate::importer::BootPageAcceptance;
16use crate::importer::GuestArch;
17use crate::importer::ImageLoad;
18use crate::importer::X86Register;
19use crate::mptable;
20use aarch64defs::Cpsr64;
21use aarch64defs::IntermPhysAddrSize;
22use aarch64defs::SctlrEl1;
23use aarch64defs::TranslationBaseEl1;
24use aarch64defs::TranslationControlEl1;
25use aarch64defs::TranslationGranule0;
26use aarch64defs::TranslationGranule1;
27use bitfield_struct::bitfield;
28use hvdef::HV_PAGE_SIZE;
29use loader_defs::linux as defs;
30use memory_range::MemoryRange;
31use page_table::IdentityMapSize;
32use page_table::x64::IdentityMapBuilder;
33use page_table::x64::PAGE_TABLE_MAX_BYTES;
34use page_table::x64::PAGE_TABLE_MAX_COUNT;
35use page_table::x64::PageTable;
36use page_table::x64::X64_LARGE_PAGE_SIZE;
37use page_table::x64::align_up_to_page_size;
38use std::ffi::CString;
39use std::io::Read;
40use std::io::Seek;
41use std::io::SeekFrom;
42use std::mem::size_of;
43use thiserror::Error;
44use vm_topology::memory::MemoryLayout;
45use x86defs::cpuid::CpuidFunction;
46use zerocopy::FromBytes;
47use zerocopy::FromZeros;
48use zerocopy::Immutable;
49use zerocopy::IntoBytes;
50use zerocopy::KnownLayout;
51
52struct ZeroPageBuildResult {
53    boot_params: defs::boot_params,
54    additional_pages: Option<MemoryRange>,
55}
56
57/// Construct a zero page from the following parameters.
58fn build_zero_page(
59    mem_layout: &MemoryLayout,
60    acpi_len: usize,
61    smbios_struct_len: usize,
62    additional_page_count: u64,
63    cmdline: &CString,
64    initrd_base: u32,
65    initrd_size: u32,
66    bzimage_header: Option<&defs::setup_header>,
67) -> Result<ZeroPageBuildResult, Error> {
68    // Loader type 0xff = unregistered bootloader, used for both ELF and
69    // bzImage paths since OpenVMM does not have a registered Linux
70    // bootloader ID.
71    const LOADER_TYPE_UNREGISTERED: u8 = 0xff;
72
73    // Start with the bzImage setup header if available, otherwise build
74    // a minimal default header.
75    let mut hdr = match bzimage_header {
76        Some(orig) => *orig,
77        None => defs::setup_header {
78            boot_flag: 0xaa55.into(),
79            header: 0x53726448.into(),
80            kernel_alignment: 0x100000.into(),
81            ..FromZeros::new_zeroed()
82        },
83    };
84
85    // Set bootloader-owned fields regardless of kernel format.
86    hdr.type_of_loader = LOADER_TYPE_UNREGISTERED;
87    hdr.cmd_line_ptr = CMDLINE_BASE.try_into().expect("must fit in u32");
88    hdr.cmdline_size = (cmdline.as_bytes().len() as u64)
89        .try_into()
90        .expect("must fit in u32");
91    hdr.ramdisk_image = initrd_base.into();
92    hdr.ramdisk_size = initrd_size.into();
93
94    let mut p = defs::boot_params {
95        hdr,
96        ..FromZeros::new_zeroed()
97    };
98
99    let mut ram = mem_layout.ram().iter().cloned();
100    let range = ram.next().expect("at least one ram range");
101    assert_eq!(range.range.start(), 0);
102    assert!(range.range.end() >= 0x100000);
103
104    // x86 low-memory layout for direct boot:
105    //   [0, acpi_base)          RAM       boot metadata: GDT, zero page, cmdline,
106    //                                     identity-map page tables
107    //   [acpi_base, acpi_end)   ACPI      RSDT/XSDT and all ACPI tables
108    //   [acpi_end, smbios_end)  RESERVED  SMBIOS structure table
109    //   [smbios_end, additional_end) RESERVED additional requested pages
110    //   [additional_end, 0xe0000)    RAM
111    //   [0xe0000, 0x100000)     RESERVED  legacy BIOS region holding the RSDP at
112    //                                     0xe0000 (found by the kernel's legacy
113    //                                     scan) and the SMBIOS _SM3_ anchor at
114    //                                     0xf0000 (found by the kernel's DMI scan)
115    //   [0x100000, end)         RAM
116    //
117    // The RSDP lives at the fixed 0xe0000 and the tables it points to live in
118    // reclaimable ACPI memory below; the kernel discovers the RSDP via its
119    // legacy scan, so no `acpi_rsdp_addr` (Linux 4.20+) is required. The SMBIOS
120    // structure table sits just above the ACPI tables in its own reserved
121    // region so it can grow well past the 64 KiB F-segment.
122    const ONE_MB: u64 = 0x100000;
123    let aligned_acpi_len = align_up_to_page_size(acpi_len as u64);
124    let acpi_end = ACPI_TABLES_BASE + aligned_acpi_len;
125    let aligned_smbios_len = align_up_to_page_size(smbios_struct_len as u64);
126    let smbios_end = acpi_end + aligned_smbios_len;
127    let additional_size = additional_page_count
128        .checked_mul(HV_PAGE_SIZE)
129        .ok_or(Error::LowTablesTooLarge(u64::MAX, RSDP_BASE))?;
130    let additional_end = smbios_end
131        .checked_add(additional_size)
132        .ok_or(Error::LowTablesTooLarge(u64::MAX, RSDP_BASE))?;
133    if additional_end > RSDP_BASE {
134        return Err(Error::LowTablesTooLarge(additional_end, RSDP_BASE));
135    }
136    let additional_pages =
137        (additional_size != 0).then(|| MemoryRange::new(smbios_end..additional_end));
138
139    // Emit the e820 entries in ascending address order. Zero-length regions
140    // (e.g. the SMBIOS reserved region when no SMBIOS tables are present) are
141    // skipped, and the fixed-size map is bounds-checked so an over-long memory
142    // layout is reported rather than panicking.
143    let e820_cap = p.e820_map.len();
144    let mut n = 0;
145    let mut push = |addr: u64, size: u64, typ: u32| -> Result<(), Error> {
146        if size == 0 {
147            return Ok(());
148        }
149        let entry = p
150            .e820_map
151            .get_mut(n)
152            .ok_or(Error::TooManyMemoryRanges(e820_cap))?;
153        *entry = defs::e820entry {
154            addr: addr.into(),
155            size: size.into(),
156            typ: typ.into(),
157        };
158        n += 1;
159        Ok(())
160    };
161    push(0, ACPI_TABLES_BASE, defs::E820_RAM)?;
162    push(ACPI_TABLES_BASE, aligned_acpi_len, defs::E820_ACPI)?;
163    push(acpi_end, aligned_smbios_len, defs::E820_RESERVED)?;
164    push(smbios_end, additional_size, defs::E820_RESERVED)?;
165    push(additional_end, RSDP_BASE - additional_end, defs::E820_RAM)?;
166    push(RSDP_BASE, ONE_MB - RSDP_BASE, defs::E820_RESERVED)?;
167    push(ONE_MB, range.range.end() - ONE_MB, defs::E820_RAM)?;
168    for range in ram {
169        push(range.range.start(), range.range.len(), defs::E820_RAM)?;
170    }
171    p.e820_entries = n as u8;
172
173    Ok(ZeroPageBuildResult {
174        boot_params: p,
175        additional_pages,
176    })
177}
178
179#[derive(Debug, Error)]
180pub enum FlatLoaderError {
181    #[error("unsupported ELF File byte order")]
182    BigEndianElfOnLittle,
183    #[error("error reading kernel data structure")]
184    BadImageMagic,
185    #[error("big-endian kernel image is not supported")]
186    BigEndianKernelImage,
187    #[error("only images with 4K pages are supported")]
188    FourKibPageImageIsRequired,
189    #[error("the kernel is required to run in the low memory; not supported")]
190    LowMemoryKernel,
191    #[error("failed to read kernel image")]
192    ReadKernelImage,
193    #[error("failed to seek to file offset as pointed by the ELF program header")]
194    SeekKernelStart,
195    #[error("failed to seek to offset of kernel image")]
196    SeekKernelImage,
197}
198
199#[derive(Debug, Error)]
200pub enum Error {
201    #[error("elf loader error")]
202    ElfLoader(#[source] crate::elf::Error),
203    #[error("bzImage parse error")]
204    BzImage(#[source] crate::bzimage::Error),
205    #[error("flat loader error")]
206    FlatLoader(#[source] FlatLoaderError),
207    #[error("Address is not page aligned")]
208    UnalignedAddress(u64),
209    #[error("importer error")]
210    Importer(#[source] anyhow::Error),
211    #[error("failed to import initrd")]
212    ImportInitrd(#[source] ImportFileRegionError),
213    #[error("initrd address after kernel {0:#x} cannot be aligned to 2 MiB")]
214    InitrdAddressTooHigh(u64),
215    #[error("failed to import bzImage payload")]
216    ImportBzImage(#[source] ImportFileRegionError),
217    #[error("PageTableBuilder: {0}")]
218    PageTableBuilder(#[from] page_table::Error),
219    #[error("kernel command line ({0} bytes) exceeds its {1:#x}-byte slot")]
220    CommandLineTooLong(usize, u64),
221    #[error("low-memory tables and boot pages end at {0:#x}, past the reserved region at {1:#x}")]
222    LowTablesTooLarge(u64, u64),
223    #[error("SNP CC blob address {0:#x} does not fit in the Linux boot protocol field")]
224    SnpCcBlobAddressTooHigh(u64),
225    #[error("too many memory ranges to fit in the {0}-entry e820 map")]
226    TooManyMemoryRanges(usize),
227    #[error("acpi tables are empty")]
228    EmptyAcpiTables,
229    #[error("MP-table Linux direct boot requires an uncompressed ELF kernel")]
230    MpTableRequiresElf,
231    #[error("failed to construct MP tables")]
232    MpTable(#[from] mptable::Error),
233    #[error("MP table ending at {table_end:#x} overlaps the GDT at {gdt_addr:#x}")]
234    MpTableOverlap { table_end: usize, gdt_addr: u64 },
235    #[error("invalid MP-table reserved memory range {start:#x}..{end:#x}")]
236    InvalidReservedMemoryRange { start: u64, end: u64 },
237    #[error(
238        "MP-table boot image range {image_start:#x}..{image_end:#x} overlaps reserved range {reserved_start:#x}..{reserved_end:#x}"
239    )]
240    MpTableImageOverlap {
241        image_start: u64,
242        image_end: u64,
243        reserved_start: u64,
244        reserved_end: u64,
245    },
246    #[error("the memory layout cannot represent the fixed MP-table platform ranges")]
247    InvalidMpTableMemoryLayout,
248}
249
250/// ACPI tables to place in guest memory: a one-page RSDP plus the tables it
251/// points to.
252///
253/// Produced by the caller-supplied builder passed to [`load_x86`] /
254/// [`load_config_x86`]. The builder is handed a nominal RSDP address `gpa` and
255/// must return `tables` that are self-consistent for placement at `gpa +
256/// 0x1000`; the loader then re-homes the RSDP to the fixed legacy-scan address.
257pub struct AcpiTables {
258    /// The RSDP. Given a whole page.
259    pub rsdp: Vec<u8>,
260    /// The remaining tables pointed to by the RSDP.
261    pub tables: Vec<u8>,
262}
263
264// The loader owns the entire sub-1 MB x86 direct-boot memory map so that
265// callers supply only table *contents*, never addresses. The resulting e820
266// map (see `build_zero_page`) is:
267//
268//   [0, ACPI_TABLES_BASE)          RAM       GDT, zero page, cmdline, page tables
269//   [ACPI_TABLES_BASE, acpi_end)   ACPI      RSDT/XSDT and all ACPI tables
270//   [acpi_end, smbios_end)         RESERVED  SMBIOS structure table
271//   [smbios_end, RSDP_BASE)        RAM
272//   [RSDP_BASE, 0x100000)          RESERVED  RSDP (0xe0000) + _SM3_ anchor (0xf0000)
273//   [0x100000, end)                RAM       kernel and beyond
274const GDT_BASE: u64 = 0x1000;
275pub const ZERO_PAGE_BASE: u64 = 0x2000;
276const CMDLINE_BASE: u64 = 0x3000;
277const CR3_BASE: u64 = 0x4000;
278/// The identity-map page tables occupy `[CR3_BASE, CR3_BASE + PAGE_TABLE_MAX_BYTES)`;
279/// the boot metadata ends there.
280const LOW_METADATA_END: u64 = CR3_BASE + PAGE_TABLE_MAX_BYTES as u64;
281/// The ACPI builder is handed `LOW_METADATA_END` as a nominal RSDP page, so its
282/// tables live one page above.
283const ACPI_TABLES_BASE: u64 = LOW_METADATA_END + 0x1000;
284/// The RSDP is pinned at the fixed 0xe0000 so the kernel's legacy RSDP scan of
285/// `[0xe0000, 0x100000)` finds it, with no dependency on
286/// `boot_params.acpi_rsdp_addr` (Linux 4.20+).
287pub const RSDP_BASE: u64 = 0xe0000;
288/// The x86 kernel brute-force scans the F-segment `[0xf0000, 0x100000)` for the
289/// SMBIOS `_SM3_` DMI anchor, so the 24-byte entry point is pinned there. Its
290/// 64-bit structure-table pointer lets the (potentially large) structure table
291/// live in the low reserved area instead — see [`smbios_struct_table_base`].
292const SMBIOS_FSEGMENT_BASE: u64 = 0xf0000;
293/// The Linux x86 kernel loads at the conventional 1 MB mark.
294const KERNEL_BASE: u64 = 0x100000;
295
296/// Enables allocation of the SEV-SNP Linux boot protocol pages.
297#[derive(Debug, Clone, Copy)]
298pub struct SnpBootConfig {
299    /// The page-table bit that marks private memory.
300    pub c_bit: u8,
301}
302
303const SNP_BOOT_PAGE_COUNT: u64 = 5;
304
305/// The GPA of the SMBIOS structure table: immediately above the ACPI tables in
306/// the low reserved area. Only the `_SM3_` anchor stays in the F-segment; the
307/// structure table lives here, reachable via the anchor's 64-bit pointer, so it
308/// can grow well past the 64 KiB F-segment.
309fn smbios_struct_table_base(acpi_tables_len: usize) -> u64 {
310    ACPI_TABLES_BASE + align_up_to_page_size(acpi_tables_len as u64)
311}
312
313// Compile-time check that the fixed low-memory layout constants are ordered and
314// non-overlapping. A violation here is a code bug, caught at build time.
315const _: () = {
316    assert!(GDT_BASE < ZERO_PAGE_BASE);
317    assert!(ZERO_PAGE_BASE < CMDLINE_BASE);
318    assert!(CMDLINE_BASE < CR3_BASE);
319    assert!(ACPI_TABLES_BASE < RSDP_BASE);
320    assert!(RSDP_BASE < SMBIOS_FSEGMENT_BASE);
321    assert!(SMBIOS_FSEGMENT_BASE < KERNEL_BASE);
322};
323
324#[derive(Debug, PartialEq, Eq, Clone, Copy)]
325pub enum InitrdAddressType {
326    /// Load the initrd after the kernel at the next 2MB aligned address.
327    AfterKernel,
328    /// Load the initrd at the specified address.
329    Address(u64),
330}
331
332pub struct InitrdConfig<'a> {
333    pub initrd_address: InitrdAddressType,
334    pub initrd: &'a mut dyn ReadSeek,
335    pub size: u64,
336}
337
338/// Information returned about the kernel loaded.
339#[derive(Debug, Default)]
340pub struct KernelInfo {
341    /// The base gpa the kernel was loaded at.
342    pub gpa: u64,
343    /// The size in bytes of the region the kernel was loaded at.
344    pub size: u64,
345    /// The gpa of the entrypoint of the kernel.
346    pub entrypoint: u64,
347}
348
349/// Information returned about the initrd loaded.
350#[derive(Debug, Default)]
351pub struct InitrdInfo {
352    /// The gpa the initrd was loaded at.
353    pub gpa: u64,
354    /// The size in bytes of the initrd loaded. Note that the region imported is aligned up to page size.
355    pub size: u64,
356}
357
358/// Information returned about where certain parts were loaded.
359#[derive(Debug, Default)]
360pub struct LoadInfo {
361    /// The information about the kernel loaded.
362    pub kernel: KernelInfo,
363    /// The information about the initrd loaded.
364    pub initrd: Option<InitrdInfo>,
365    /// The information about the device tree blob loaded.
366    pub dtb: Option<std::ops::Range<u64>>,
367    /// If a bzImage was loaded, the original setup header from the image.
368    /// This must be placed into the zero page so the kernel's startup code
369    /// can read its own configuration.
370    pub bzimage_setup_header: Option<defs::setup_header>,
371}
372
373/// The SEV-SNP pages that a Linux guest needs on every boot path.
374#[derive(Debug, Clone, Copy, PartialEq, Eq)]
375pub struct SnpGuestPages {
376    /// The GPA of the secrets page.
377    pub secrets: u64,
378    /// The GPA of the CPUID page.
379    pub cpuid: u64,
380    /// The GPA of the `cc_blob_sev_info` page that points to the other two.
381    pub cc_blob: u64,
382}
383
384/// Imports the secrets, CPUID, and CC-blob pages at three pages from `base`.
385fn import_snp_guest_pages(
386    importer: &mut impl ImageLoad<X86Register>,
387    base: u64,
388) -> Result<SnpGuestPages, Error> {
389    let pages = SnpGuestPages {
390        secrets: base,
391        cpuid: base + HV_PAGE_SIZE,
392        cc_blob: base + 2 * HV_PAGE_SIZE,
393    };
394
395    importer
396        .import_pages(
397            pages.secrets / HV_PAGE_SIZE,
398            1,
399            "linux-snp-secrets",
400            BootPageAcceptance::SecretsPage,
401            &[],
402        )
403        .map_err(Error::Importer)?;
404    let mut cpuid_page = crate::cpuid::HV_PSP_CPUID_PAGE::default();
405    // TODO: Decide whether the paravisor leaf list is correct for enlightened
406    // direct-boot Linux SNP guests. It currently provides the extended-state
407    // subleaves Linux needs.
408    for (index, leaf) in crate::cpuid::SNP_REQUIRED_CPUID_LEAF_LIST_PARAVISOR
409        .iter()
410        .enumerate()
411    {
412        let entry = &mut cpuid_page.cpuid_leaf_info[index];
413        entry.eax_in = leaf.eax;
414        entry.ecx_in = leaf.ecx;
415        if leaf.eax == CpuidFunction::ExtendedStateEnumeration.0 && leaf.ecx <= 1 {
416            entry.xfem_in = 1;
417        }
418    }
419    cpuid_page.count = crate::cpuid::SNP_REQUIRED_CPUID_LEAF_LIST_PARAVISOR.len() as u32;
420    importer
421        .import_pages(
422            pages.cpuid / HV_PAGE_SIZE,
423            1,
424            "linux-snp-cpuid",
425            BootPageAcceptance::CpuidPage,
426            cpuid_page.as_bytes(),
427        )
428        .map_err(Error::Importer)?;
429
430    let cc_blob = defs::cc_blob_sev_info {
431        magic: defs::CC_BLOB_SEV_INFO_MAGIC,
432        version: 0,
433        _reserved: 0,
434        secrets_phys: pages.secrets,
435        secrets_len: HV_PAGE_SIZE as u32,
436        _rsvd1: 0,
437        cpuid_phys: pages.cpuid,
438        cpuid_len: HV_PAGE_SIZE as u32,
439        _rsvd2: 0,
440    };
441    importer
442        .import_pages(
443            pages.cc_blob / HV_PAGE_SIZE,
444            1,
445            "linux-snp-cc-blob",
446            BootPageAcceptance::Exclusive,
447            cc_blob.as_bytes(),
448        )
449        .map_err(Error::Importer)?;
450
451    Ok(pages)
452}
453
454fn import_snp_boot_pages(
455    importer: &mut impl ImageLoad<X86Register>,
456    range: MemoryRange,
457) -> Result<u64, Error> {
458    assert_eq!(range.len(), SNP_BOOT_PAGE_COUNT * HV_PAGE_SIZE);
459    let pages = import_snp_guest_pages(importer, range.start())?;
460    let cc_setup_data_address = range.start() + 3 * HV_PAGE_SIZE;
461    let vmsa_address = range.start() + 4 * HV_PAGE_SIZE;
462
463    let cc_blob_address =
464        u32::try_from(pages.cc_blob).map_err(|_| Error::SnpCcBlobAddressTooHigh(pages.cc_blob))?;
465    let cc_setup_data = defs::cc_setup_data {
466        header: defs::setup_data {
467            next: 0,
468            ty: defs::SETUP_CC_BLOB,
469            len: (size_of::<defs::cc_setup_data>() - size_of::<defs::setup_data>()) as u32,
470        },
471        cc_blob_address,
472        _padding: [0; 3],
473    };
474    importer
475        .import_pages(
476            cc_setup_data_address / HV_PAGE_SIZE,
477            1,
478            "linux-snp-cc-setup-data",
479            BootPageAcceptance::Exclusive,
480            cc_setup_data.as_bytes(),
481        )
482        .map_err(Error::Importer)?;
483
484    importer
485        .set_vp_context_page(vmsa_address / HV_PAGE_SIZE)
486        .map_err(Error::Importer)?;
487
488    Ok(cc_setup_data_address)
489}
490
491/// Check if an address is aligned to a page.
492fn check_address_alignment(address: u64) -> Result<(), Error> {
493    if !address.is_multiple_of(HV_PAGE_SIZE) {
494        Err(Error::UnalignedAddress(address))
495    } else {
496        Ok(())
497    }
498}
499
500fn align_initrd_after_kernel(next_addr: u64) -> Result<u64, Error> {
501    next_addr
502        .checked_next_multiple_of(X64_LARGE_PAGE_SIZE)
503        .ok_or(Error::InitrdAddressTooHigh(next_addr))
504}
505
506/// Import initrd
507fn import_initrd<R: GuestArch>(
508    initrd: Option<InitrdConfig<'_>>,
509    next_addr: u64,
510    importer: &mut dyn ImageLoad<R>,
511) -> Result<Option<InitrdInfo>, Error> {
512    let initrd_info = match initrd {
513        Some(cfg) => {
514            let initrd_address = match cfg.initrd_address {
515                InitrdAddressType::AfterKernel => align_initrd_after_kernel(next_addr)?,
516                InitrdAddressType::Address(addr) => addr,
517            };
518
519            tracing::trace!(initrd_address, "loading initrd");
520            check_address_alignment(initrd_address)?;
521
522            ChunkBuf::new()
523                .import_file_region(
524                    importer,
525                    ImportFileRegion {
526                        file: cfg.initrd,
527                        file_offset: 0,
528                        file_length: cfg.size,
529                        gpa: initrd_address,
530                        memory_length: cfg.size,
531                        acceptance: BootPageAcceptance::Exclusive,
532                        tag: "linux-initrd",
533                    },
534                )
535                .map_err(Error::ImportInitrd)?;
536
537            Some(InitrdInfo {
538                gpa: initrd_address,
539                size: cfg.size,
540            })
541        }
542        None => None,
543    };
544    Ok(initrd_info)
545}
546
547/// Load only a Linux kernel and optional initrd to VTL0.
548/// This does not setup register state or any other config information.
549///
550/// The kernel image may be either an uncompressed ELF (`vmlinux`) or a
551/// compressed bzImage. If a bzImage is detected, the bzImage payload is
552/// loaded directly into guest memory and the kernel's own decompressor
553/// runs at boot time.
554///
555/// # Arguments
556///
557/// * `importer` - The importer to use.
558/// * `kernel_image` - Kernel image (uncompressed ELF or bzImage).
559/// * `kernel_minimum_start_address` - The minimum address the kernel can load at.
560///   It cannot contain an entrypoint or program headers that refer to memory below this address.
561/// * `initrd` - The initrd config, optional.
562pub fn load_kernel_and_initrd_x64<F>(
563    importer: &mut dyn ImageLoad<X86Register>,
564    kernel_image: &mut F,
565    kernel_minimum_start_address: u64,
566    initrd: Option<InitrdConfig<'_>>,
567) -> Result<LoadInfo, Error>
568where
569    F: Read + Seek,
570{
571    tracing::trace!(kernel_minimum_start_address, "loading x86_64 kernel");
572
573    if crate::bzimage::is_bzimage(kernel_image).map_err(Error::BzImage)? {
574        tracing::info!("detected bzImage format, loading via Linux boot protocol");
575        return load_bzimage(importer, kernel_image, kernel_minimum_start_address, initrd);
576    }
577
578    let elf_load_info = load_static_elf(
579        importer,
580        kernel_image,
581        kernel_minimum_start_address,
582        0,
583        false,
584        BootPageAcceptance::Exclusive,
585        "linux-kernel",
586    )
587    .map_err(Error::ElfLoader)?;
588
589    let crate::elf::LoadInfo {
590        minimum_address_used: min_addr,
591        next_available_address: next_addr,
592        entrypoint,
593    } = elf_load_info;
594    tracing::trace!(min_addr, next_addr, entrypoint, "loaded kernel");
595
596    let initrd_info = import_initrd(initrd, next_addr, importer)?;
597
598    Ok(LoadInfo {
599        kernel: KernelInfo {
600            gpa: min_addr,
601            size: next_addr - min_addr,
602            entrypoint,
603        },
604        initrd: initrd_info,
605        dtb: None,
606        bzimage_setup_header: None,
607    })
608}
609
610/// Load a bzImage by placing its payload directly into guest memory at the
611/// load address and following the Linux boot protocol. The kernel's built-in
612/// decompressor handles the rest at boot time.
613fn load_bzimage(
614    importer: &mut dyn ImageLoad<X86Register>,
615    kernel_image: &mut (impl Read + Seek),
616    kernel_start_address: u64,
617    initrd: Option<InitrdConfig<'_>>,
618) -> Result<LoadInfo, Error> {
619    let info = crate::bzimage::parse_bzimage(kernel_image).map_err(Error::BzImage)?;
620
621    check_address_alignment(kernel_start_address)?;
622
623    let payload_offset = (info.setup_sects as u64 + 1) * 512;
624    let payload_len = info.protected_mode_size;
625    let payload_memory_len = align_up_to_page_size(payload_len);
626    let entrypoint = kernel_start_address + info.entry_offset;
627
628    tracing::info!(
629        kernel_start_address = format_args!("{:#x}", kernel_start_address),
630        payload_offset,
631        payload_len,
632        entrypoint = format_args!("{:#x}", entrypoint),
633        "loading bzImage payload into guest memory"
634    );
635
636    ChunkBuf::new()
637        .import_file_region(
638            importer,
639            ImportFileRegion {
640                file: kernel_image,
641                file_offset: payload_offset,
642                file_length: payload_len,
643                gpa: kernel_start_address,
644                memory_length: payload_memory_len,
645                acceptance: BootPageAcceptance::Exclusive,
646                tag: "linux-kernel",
647            },
648        )
649        .map_err(Error::ImportBzImage)?;
650
651    // Place initrd after the kernel's init_size region to avoid being
652    // overwritten during decompression.
653    let next_addr = kernel_start_address + payload_memory_len;
654    let pref_address: u64 = info.setup_header.pref_address.into();
655    let init_end = kernel_start_address
656        .max(pref_address)
657        .saturating_add(info.init_size as u64);
658    let next_addr = next_addr.max(init_end);
659    let initrd_info = import_initrd(initrd, next_addr, importer)?;
660
661    Ok(LoadInfo {
662        kernel: KernelInfo {
663            gpa: kernel_start_address,
664            size: payload_memory_len,
665            entrypoint,
666        },
667        initrd: initrd_info,
668        dtb: None,
669        bzimage_setup_header: Some(info.setup_header),
670    })
671}
672
673/// Import the boot metadata, ACPI/SMBIOS tables, zero page, and initial
674/// registers for a kernel already described by `load_info`.
675///
676/// Internal helper shared by [`load_x86`] and [`load_config_x86`]. All guest
677/// addresses come from the module-level layout constants; callers supply only
678/// the table contents.
679fn import_config(
680    importer: &mut impl ImageLoad<X86Register>,
681    load_info: &LoadInfo,
682    cmdline: &CString,
683    mem_layout: &MemoryLayout,
684    acpi: &AcpiTables,
685    smbios: Option<&crate::smbios::BuiltSmbios>,
686    snp_boot: Option<SnpBootConfig>,
687) -> Result<(), Error> {
688    // Only import the cmdline if it actually contains something.
689    // TODO: This should use the IGVM parameter instead?
690    let raw_cmdline = cmdline.as_bytes_with_nul();
691    if raw_cmdline.len() as u64 > CR3_BASE - CMDLINE_BASE {
692        return Err(Error::CommandLineTooLong(
693            raw_cmdline.len(),
694            CR3_BASE - CMDLINE_BASE,
695        ));
696    }
697    if raw_cmdline.len() > 1 {
698        let cmdline_size_pages = align_up_to_page_size(raw_cmdline.len() as u64) / HV_PAGE_SIZE;
699        importer
700            .import_pages(
701                CMDLINE_BASE / HV_PAGE_SIZE,
702                cmdline_size_pages,
703                "linux-commandline",
704                BootPageAcceptance::Exclusive,
705                raw_cmdline,
706            )
707            .map_err(Error::Importer)?;
708    }
709
710    import_default_gdt(importer, GDT_BASE / HV_PAGE_SIZE).map_err(Error::Importer)?;
711    import_identity_map(importer, snp_boot)?;
712
713    if acpi.tables.is_empty() {
714        return Err(Error::EmptyAcpiTables);
715    }
716    let acpi_tables_size_pages = align_up_to_page_size(acpi.tables.len() as u64) / HV_PAGE_SIZE;
717    importer
718        .import_pages(
719            RSDP_BASE / HV_PAGE_SIZE,
720            1,
721            "linux-rsdp",
722            BootPageAcceptance::Exclusive,
723            &acpi.rsdp,
724        )
725        .map_err(Error::Importer)?;
726    importer
727        .import_pages(
728            ACPI_TABLES_BASE / HV_PAGE_SIZE,
729            acpi_tables_size_pages,
730            "linux-acpi-tables",
731            BootPageAcceptance::Exclusive,
732            &acpi.tables,
733        )
734        .map_err(Error::Importer)?;
735
736    let requested_page_count = snp_boot.map_or(0, |_| SNP_BOOT_PAGE_COUNT);
737    let ZeroPageBuildResult {
738        mut boot_params,
739        additional_pages,
740    } = build_zero_page(
741        mem_layout,
742        acpi.tables.len(),
743        smbios.map_or(0, |s| s.structure_table.len()),
744        requested_page_count,
745        cmdline,
746        load_info.initrd.as_ref().map(|info| info.gpa).unwrap_or(0) as u32,
747        load_info.initrd.as_ref().map(|info| info.size).unwrap_or(0) as u32,
748        load_info.bzimage_setup_header.as_ref(),
749    )?;
750    if let Some(allocated_range) = additional_pages {
751        boot_params.hdr.setup_data = import_snp_boot_pages(importer, allocated_range)?.into();
752    }
753    importer
754        .import_pages(
755            ZERO_PAGE_BASE / HV_PAGE_SIZE,
756            1,
757            "linux-zeropage",
758            BootPageAcceptance::Exclusive,
759            boot_params.as_bytes(),
760        )
761        .map_err(Error::Importer)?;
762
763    // Set common X64 registers. Segments already set by default gdt.
764    import_long_mode_registers(importer)?;
765    let mut import_reg = |register| {
766        importer
767            .import_vp_register(register)
768            .map_err(Error::Importer)
769    };
770
771    // Set rip to entry point and rsi to zero page.
772    import_reg(X86Register::Rip(load_info.kernel.entrypoint))?;
773    import_reg(X86Register::Rsi(ZERO_PAGE_BASE))?;
774
775    if let Some(smbios) = smbios {
776        // The `_SM3_` entry point (anchor) goes in the F-segment for the
777        // kernel's DMI scan; its 64-bit pointer targets the structure table in
778        // the low reserved area just above the ACPI tables.
779        let anchor_pages = align_up_to_page_size(smbios.entry_point.len() as u64) / HV_PAGE_SIZE;
780        importer
781            .import_pages(
782                SMBIOS_FSEGMENT_BASE / HV_PAGE_SIZE,
783                anchor_pages,
784                "linux-smbios-anchor",
785                BootPageAcceptance::Exclusive,
786                &smbios.entry_point,
787            )
788            .map_err(Error::Importer)?;
789
790        let table_base = smbios_struct_table_base(acpi.tables.len());
791        let table_pages = align_up_to_page_size(smbios.structure_table.len() as u64) / HV_PAGE_SIZE;
792        importer
793            .import_pages(
794                table_base / HV_PAGE_SIZE,
795                table_pages,
796                "linux-smbios-tables",
797                BootPageAcceptance::Exclusive,
798                &smbios.structure_table,
799            )
800            .map_err(Error::Importer)?;
801    }
802
803    Ok(())
804}
805
806/// Imports the 4-GiB identity map at `CR3_BASE`, with the C-bit for SNP.
807fn import_identity_map(
808    importer: &mut impl ImageLoad<X86Register>,
809    snp_boot: Option<SnpBootConfig>,
810) -> Result<(), Error> {
811    let mut page_table_work_buffer: Vec<PageTable> =
812        vec![PageTable::new_zeroed(); PAGE_TABLE_MAX_COUNT];
813    let mut page_table: Vec<u8> = vec![0; PAGE_TABLE_MAX_BYTES];
814    let mut page_table_builder = IdentityMapBuilder::new(
815        CR3_BASE,
816        IdentityMapSize::Size4Gb,
817        page_table_work_buffer.as_mut_slice(),
818        page_table.as_mut_slice(),
819    )?;
820    if let Some(snp_boot) = snp_boot {
821        page_table_builder = page_table_builder.with_confidential_bit(snp_boot.c_bit.into());
822    }
823    let page_table = page_table_builder.build();
824    assert!((page_table.len() as u64).is_multiple_of(HV_PAGE_SIZE));
825    importer
826        .import_pages(
827            CR3_BASE / HV_PAGE_SIZE,
828            page_table.len() as u64 / HV_PAGE_SIZE,
829            "linux-pagetables",
830            BootPageAcceptance::Exclusive,
831            page_table,
832        )
833        .map_err(Error::Importer)
834}
835
836/// Imports the long-mode control registers, PAT, and MTRRs that use the GDT
837/// at `GDT_BASE` and the identity map at `CR3_BASE`.
838fn import_long_mode_registers(importer: &mut impl ImageLoad<X86Register>) -> Result<(), Error> {
839    let mut import_reg = |register| {
840        importer
841            .import_vp_register(register)
842            .map_err(Error::Importer)
843    };
844
845    import_reg(X86Register::Cr0(
846        x86defs::Cr0::new().with_pg(true).with_pe(true).into_bits(),
847    ))?;
848    import_reg(X86Register::Cr3(CR3_BASE))?;
849    import_reg(X86Register::Cr4(
850        x86defs::Cr4::new().with_pae(true).into_bits(),
851    ))?;
852    import_reg(X86Register::Efer(
853        x86defs::Efer::new()
854            .with_sce(true)
855            .with_lme(true)
856            .with_lma(true)
857            .with_nxe(true)
858            .into_bits(),
859    ))?;
860    import_reg(X86Register::Pat(x86defs::X86X_MSR_DEFAULT_PAT))?;
861
862    // No firmware will set MTRR values for the BSP.  Replicate what UEFI does here.
863    // (enable MTRRs, default MTRR is uncached, and set lowest 640KB as WB)
864    import_reg(X86Register::MtrrDefType(0xc00))?;
865    import_reg(X86Register::MtrrFix64k00000(0x0606060606060606))?;
866    import_reg(X86Register::MtrrFix16k80000(0x0606060606060606))?;
867    Ok(())
868}
869
870/// Imports the initial state for a 64-bit SEV-SNP boot stage that runs before
871/// Linux, such as a bootshim that starts the Linux EFI stub.
872///
873/// This imports a GDT, a 4-GiB identity map with the C-bit, the SEV-SNP guest
874/// pages, and the long-mode registers. It does not build a zero page. The
875/// caller sets RIP and any argument registers.
876///
877/// Returns the SNP guest pages and the end of the low memory that this uses.
878pub fn import_snp_boot_stage(
879    importer: &mut impl ImageLoad<X86Register>,
880    snp_boot: SnpBootConfig,
881) -> Result<(SnpGuestPages, u64), Error> {
882    import_default_gdt(importer, GDT_BASE / HV_PAGE_SIZE).map_err(Error::Importer)?;
883    import_identity_map(importer, Some(snp_boot))?;
884    let pages_base = align_up_to_page_size(LOW_METADATA_END);
885    let pages = import_snp_guest_pages(importer, pages_base)?;
886    import_long_mode_registers(importer)?;
887    Ok((pages, pages_base + 3 * HV_PAGE_SIZE))
888}
889
890/// Place the ACPI tables, SMBIOS tables, boot metadata, zero page, and initial
891/// registers for a Linux kernel that has *already* been loaded into guest
892/// memory (as described by `load_info`).
893///
894/// The loader owns the entire sub-1 MB memory map; callers supply only
895/// contents, never addresses:
896///
897/// * `cmdline` - the kernel command line.
898/// * `mem_layout` - the guest memory layout, used to build the e820 map.
899/// * `build_acpi` - a builder handed the nominal RSDP address; it must return
900///   ACPI tables self-consistent for placement one page above that address.
901///   The loader re-homes the RSDP to the fixed 0xe0000 legacy-scan location.
902/// * `smbios` - an optional SMBIOS identity; when present the loader assembles
903///   the `_SM3_` entry point and structure table into the F-segment.
904/// * `snp_boot` - optionally allocate SEV-SNP Linux boot protocol pages.
905pub fn load_config_x86(
906    importer: &mut impl ImageLoad<X86Register>,
907    load_info: &LoadInfo,
908    cmdline: &CString,
909    mem_layout: &MemoryLayout,
910    build_acpi: impl FnOnce(u64) -> AcpiTables,
911    smbios: Option<crate::smbios::SmbiosTables<'_>>,
912    snp_boot: Option<SnpBootConfig>,
913) -> Result<(), Error> {
914    // The builder lays out a nominal RSDP page at LOW_METADATA_END followed by
915    // the tables it points to; we keep only the tables (placed at
916    // ACPI_TABLES_BASE) and re-home the RSDP to the fixed scan location.
917    let acpi_tables = build_acpi(LOW_METADATA_END);
918
919    // Build the SMBIOS tables (if an identity was supplied) with the structure
920    // table addressed at its low-area home: the `_SM3_` anchor's 64-bit pointer
921    // references it there while the anchor itself lands in the F-segment for the
922    // kernel's DMI scan. See `smbios_struct_table_base` / `import_config`.
923    let smbios = smbios.map(|tables| {
924        crate::smbios::build(&tables, smbios_struct_table_base(acpi_tables.tables.len()))
925    });
926
927    import_config(
928        importer,
929        load_info,
930        cmdline,
931        mem_layout,
932        &acpi_tables,
933        smbios.as_ref(),
934        snp_boot,
935    )
936}
937
938/// Load a Linux kernel into VTL0 and place all of its supporting structures.
939///
940/// Loads the kernel (uncompressed ELF or bzImage) and optional initrd at the
941/// conventional 1 MB address, then delegates to [`load_config_x86`] to place
942/// the ACPI/SMBIOS tables, boot metadata, zero page, and initial registers.
943/// See [`load_config_x86`] for the `build_acpi`/`smbios` contract.
944pub fn load_x86<F>(
945    importer: &mut impl ImageLoad<X86Register>,
946    kernel_image: &mut F,
947    initrd: Option<InitrdConfig<'_>>,
948    cmdline: &CString,
949    mem_layout: &MemoryLayout,
950    build_acpi: impl FnOnce(u64) -> AcpiTables,
951    smbios: Option<crate::smbios::SmbiosTables<'_>>,
952    snp_boot: Option<SnpBootConfig>,
953) -> Result<LoadInfo, Error>
954where
955    F: Read + Seek,
956{
957    let load_info = load_kernel_and_initrd_x64(importer, kernel_image, KERNEL_BASE, initrd)?;
958    load_config_x86(
959        importer, &load_info, cmdline, mem_layout, build_acpi, smbios, snp_boot,
960    )?;
961    Ok(load_info)
962}
963
964open_enum::open_enum! {
965    #[derive(IntoBytes, Immutable, KnownLayout, FromBytes)]
966    pub enum Aarch64ImagePageSize: u64 {
967        UNSPECIFIED = 0,
968        PAGE4_K = 1,
969        PAGE16_K = 2,
970        PAGE64_K = 3,
971    }
972
973}
974
975impl Aarch64ImagePageSize {
976    const fn into_bits(self) -> u64 {
977        self.0
978    }
979
980    const fn from_bits(bits: u64) -> Self {
981        Self(bits)
982    }
983}
984
985/// Arm64 flat kernel `Image` flags.
986#[bitfield(u64)]
987struct Aarch64ImageFlags {
988    /// Bit 0:	Kernel endianness.  1 if BE, 0 if LE.
989    #[bits(1)]
990    pub big_endian: bool,
991    /// Bit 1-2:	Kernel Page size.
992    ///           0 - Unspecified.
993    ///           1 - 4K
994    ///           2 - 16K
995    ///           3 - 64K
996    #[bits(2)]
997    pub page_size: Aarch64ImagePageSize,
998    /// Bit 3:	Kernel physical placement
999    ///           0 - 2MB aligned base should be as close as possible
1000    ///               to the base of DRAM, since memory below it is not
1001    ///               accessible via the linear mapping
1002    ///           1 - 2MB aligned base may be anywhere in physical
1003    ///               memory
1004    #[bits(1)]
1005    pub any_start_address: bool,
1006    /// Bits 4-63:	Reserved.
1007    #[bits(60)]
1008    pub _padding: u64,
1009}
1010
1011// Kernel boot protocol is specified in the Linux kernel
1012// Documentation/arm64/booting.txt.
1013#[derive(Debug, IntoBytes, Immutable, KnownLayout, FromBytes)]
1014#[repr(C)]
1015struct Aarch64ImageHeader {
1016    /// Executable code
1017    _code0: u32,
1018    /// Executable code
1019    _code1: u32,
1020    /// Image load offset, little endian
1021    text_offset: u64,
1022    /// Effective Image size, little endian
1023    image_size: u64,
1024    /// kernel flags, little endian
1025    flags: u64,
1026    /// reserved
1027    _res2: u64,
1028    /// reserved
1029    _res3: u64,
1030    /// reserved
1031    _res4: u64,
1032    /// Magic number, little endian, "ARM\x64"
1033    magic: [u8; 4],
1034    /// reserved (used for PE COFF offset)
1035    _res5: u32,
1036}
1037
1038const AARCH64_MAGIC_NUMBER: &[u8] = b"ARM\x64";
1039
1040/// Load only an arm64 the flat Linux kernel `Image` and optional initrd.
1041/// This does not setup register state or any other config information.
1042///
1043/// # Arguments
1044///
1045/// * `importer` - The importer to use.
1046/// * `kernel_image` - Uncompressed ELF image for the kernel.
1047/// * `kernel_minimum_start_address` - The minimum address the kernel can load at.
1048///   It cannot contain an entrypoint or program headers that refer to memory below this address.
1049/// * `initrd` - The initrd config, optional.
1050/// * `device_tree_blob` - The device tree blob, optional.
1051pub fn load_kernel_and_initrd_arm64<F>(
1052    importer: &mut dyn ImageLoad<Aarch64Register>,
1053    kernel_image: &mut F,
1054    kernel_minimum_start_address: u64,
1055    initrd: Option<InitrdConfig<'_>>,
1056    device_tree_blob: Option<&[u8]>,
1057) -> Result<LoadInfo, Error>
1058where
1059    F: Read + Seek,
1060{
1061    tracing::trace!(kernel_minimum_start_address, "loading aarch64 kernel");
1062
1063    assert_eq!(
1064        kernel_minimum_start_address & ((1 << 21) - 1),
1065        0,
1066        "Start offset must be aligned on the 2MiB boundary"
1067    );
1068
1069    kernel_image
1070        .seek(SeekFrom::Start(0))
1071        .map_err(|_| Error::FlatLoader(FlatLoaderError::SeekKernelStart))?;
1072
1073    let mut header = Aarch64ImageHeader::new_zeroed();
1074    kernel_image
1075        .read_exact(header.as_mut_bytes())
1076        .map_err(|_| Error::FlatLoader(FlatLoaderError::ReadKernelImage))?;
1077
1078    tracing::debug!("aarch64 kernel header {header:x?}");
1079
1080    if header.magic != AARCH64_MAGIC_NUMBER {
1081        return Err(Error::FlatLoader(FlatLoaderError::BadImageMagic));
1082    }
1083
1084    let flags = Aarch64ImageFlags::from(header.flags);
1085    if flags.big_endian() {
1086        return Err(Error::FlatLoader(FlatLoaderError::BigEndianKernelImage));
1087    }
1088    if flags.page_size() != Aarch64ImagePageSize::PAGE4_K {
1089        return Err(Error::FlatLoader(
1090            FlatLoaderError::FourKibPageImageIsRequired,
1091        ));
1092    }
1093    if !flags.any_start_address() {
1094        return Err(Error::FlatLoader(FlatLoaderError::LowMemoryKernel));
1095    }
1096
1097    // The `Image` must be placed `text_offset` bytes from a 2MB aligned base
1098    // address anywhere in usable system RAM and called there.
1099
1100    kernel_image
1101        .seek(SeekFrom::Start(0))
1102        .map_err(|_| Error::FlatLoader(FlatLoaderError::SeekKernelStart))?;
1103
1104    let mut image = Vec::new();
1105    kernel_image
1106        .read_to_end(&mut image)
1107        .map_err(|_| Error::FlatLoader(FlatLoaderError::ReadKernelImage))?;
1108
1109    let kernel_load_offset = (kernel_minimum_start_address + header.text_offset) as usize;
1110    let kernel_size = if header.image_size != 0 {
1111        header.image_size
1112    } else {
1113        image.len() as u64
1114    };
1115
1116    let kernel_size = align_up_to_page_size(kernel_size);
1117    importer
1118        .import_pages(
1119            kernel_load_offset as u64 / HV_PAGE_SIZE,
1120            kernel_size / HV_PAGE_SIZE,
1121            "linux-kernel",
1122            BootPageAcceptance::Exclusive,
1123            &image,
1124        )
1125        .map_err(Error::Importer)?;
1126
1127    let next_addr = kernel_load_offset as u64 + kernel_size;
1128
1129    let (next_addr, dtb) = if let Some(device_tree_blob) = device_tree_blob {
1130        let dtb_addr = align_up_to_page_size(next_addr);
1131        tracing::trace!(dtb_addr, "loading device tree blob at {dtb_addr:x?}");
1132
1133        check_address_alignment(dtb_addr)?;
1134        let dtb_size_pages = align_up_to_page_size(device_tree_blob.len() as u64) / HV_PAGE_SIZE;
1135
1136        importer
1137            .import_pages(
1138                dtb_addr / HV_PAGE_SIZE,
1139                dtb_size_pages,
1140                "linux-device-tree",
1141                BootPageAcceptance::Exclusive,
1142                device_tree_blob,
1143            )
1144            .map_err(Error::Importer)?;
1145
1146        (
1147            dtb_addr + device_tree_blob.len() as u64,
1148            Some(dtb_addr..dtb_addr + device_tree_blob.len() as u64),
1149        )
1150    } else {
1151        (next_addr, None)
1152    };
1153
1154    let initrd_info = import_initrd(initrd, next_addr, importer)?;
1155
1156    Ok(LoadInfo {
1157        kernel: KernelInfo {
1158            gpa: kernel_minimum_start_address,
1159            size: kernel_size,
1160            entrypoint: kernel_load_offset as u64,
1161        },
1162        initrd: initrd_info,
1163        dtb,
1164        bzimage_setup_header: None,
1165    })
1166}
1167
1168/// Load the configuration info and registers for the Linux kernel based on the provided LoadInfo.
1169/// Parameters:
1170/// * `importer` - The importer to use.
1171/// * `load_info` - The kernel load info that contains information on where the kernel and initrd are.
1172/// * `vtl` - The target VTL.
1173pub fn set_direct_boot_registers_arm64(
1174    importer: &mut impl ImageLoad<Aarch64Register>,
1175    load_info: &LoadInfo,
1176) -> Result<(), Error> {
1177    let mut import_reg = |register| {
1178        importer
1179            .import_vp_register(register)
1180            .map_err(Error::Importer)
1181    };
1182
1183    import_reg(Aarch64Register::Pc(load_info.kernel.entrypoint))?;
1184    import_reg(Aarch64Register::Cpsr(
1185        Cpsr64::new()
1186            .with_sp(true)
1187            .with_el(1)
1188            .with_f(true)
1189            .with_i(true)
1190            .with_a(true)
1191            .with_d(true)
1192            .into(),
1193    ))?;
1194    import_reg(Aarch64Register::SctlrEl1(
1195        SctlrEl1::new()
1196            // MMU is disabled for EL1&0 stage 1 address translation.
1197            // The family of the `at` instructions and the `PAR_EL1` register are
1198            // useful for debugging MMU issues when it's on.
1199            .with_m(false)
1200            // Stage 1 Cacheability control, for data accesses.
1201            .with_c(true)
1202            // Stage 1 Cacheability control, for code.
1203            .with_i(true)
1204            // Reserved flags, must be set
1205            .with_eos(true)
1206            .with_tscxt(true)
1207            .with_eis(true)
1208            .with_span(true)
1209            .with_n_tlsmd(true)
1210            .with_lsmaoe(true)
1211            .into(),
1212    ))?;
1213    import_reg(Aarch64Register::TcrEl1(
1214        TranslationControlEl1::new()
1215            .with_t0sz(0x11)
1216            .with_irgn0(1)
1217            .with_orgn0(1)
1218            .with_sh0(3)
1219            .with_tg0(TranslationGranule0::TG_4KB)
1220            // Disable TTBR0_EL1 walks (i.e. the lower half).
1221            .with_epd0(1)
1222            // Disable TTBR1_EL1 walks (i.e. the upper half).
1223            .with_epd1(1)
1224            // Due to erratum #822227, need to set a valid TG1 regardless of EPD1.
1225            .with_tg1(TranslationGranule1::TG_4KB)
1226            .with_ips(IntermPhysAddrSize::IPA_48_BITS_256_TB)
1227            .into(),
1228    ))?;
1229    import_reg(Aarch64Register::Ttbr0El1(TranslationBaseEl1::new().into()))?;
1230    import_reg(Aarch64Register::Ttbr1El1(TranslationBaseEl1::new().into()))?;
1231    import_reg(Aarch64Register::VbarEl1(0))?;
1232
1233    if let Some(dtb) = &load_info.dtb {
1234        import_reg(Aarch64Register::X0(dtb.start))?;
1235    }
1236
1237    Ok(())
1238}
1239#[cfg(test)]
1240mod tests {
1241    use super::*;
1242    use crate::importer::IgvmParameterType;
1243    use crate::importer::IsolationConfig;
1244    use crate::importer::ParameterAreaIndex;
1245    use crate::importer::StartupMemoryType;
1246    use std::io::Cursor;
1247    use test_with_tracing::test;
1248    use zerocopy::FromBytes;
1249
1250    const MB: u64 = 0x100000;
1251    const GB: u64 = 0x4000_0000;
1252
1253    /// A guest memory layout with `ram_size` bytes of RAM and a 128 MB MMIO gap
1254    /// below 4 GiB (matching a typical x86_64 config). RAM up to the gap forms
1255    /// the first range `[0, min(ram_size, 4 GiB - 128 MB))`.
1256    fn make_layout(ram_size: u64) -> MemoryLayout {
1257        MemoryLayout::new(
1258            ram_size,
1259            &[MemoryRange::new(4 * GB - 128 * MB..4 * GB)],
1260            &[],
1261            &[],
1262            None,
1263        )
1264        .unwrap()
1265    }
1266
1267    /// Asserts that `map[..entries]` exactly covers `[0, first_ram_end)` with no
1268    /// gaps or overlaps and strictly ascending addresses, and that no entry is
1269    /// empty. The first entry must start at 0 and the last must end precisely at
1270    /// `first_ram_end`.
1271    fn assert_contiguous(p: &defs::boot_params, first_ram_end: u64) {
1272        let entries = p.e820_entries as usize;
1273        assert!(entries > 0);
1274        let mut expected_addr = 0u64;
1275        for i in 0..entries {
1276            let e = &p.e820_map[i];
1277            assert_ne!(u64::from(e.size), 0, "entry {i} is empty");
1278            assert_eq!(u64::from(e.addr), expected_addr, "gap/overlap at entry {i}");
1279            expected_addr = u64::from(e.addr) + u64::from(e.size);
1280        }
1281        assert_eq!(
1282            expected_addr, first_ram_end,
1283            "map ends at {expected_addr:#x}, expected {first_ram_end:#x}"
1284        );
1285    }
1286
1287    #[test]
1288    fn zero_page_layout_with_smbios() {
1289        let acpi_len = 0x1800; // aligns up to 0x2000
1290        let smbios_len = 0x100; // aligns up to 0x1000
1291        let p = build_zero_page(
1292            &make_layout(256 * MB),
1293            acpi_len,
1294            smbios_len,
1295            0,
1296            &CString::new("root=/dev/sda").unwrap(),
1297            0,
1298            0,
1299            None,
1300        )
1301        .unwrap()
1302        .boot_params;
1303
1304        let acpi_end = ACPI_TABLES_BASE + 0x2000;
1305        let smbios_end = acpi_end + 0x1000;
1306        let expected = [
1307            (0, ACPI_TABLES_BASE, defs::E820_RAM),
1308            (ACPI_TABLES_BASE, 0x2000, defs::E820_ACPI),
1309            (acpi_end, 0x1000, defs::E820_RESERVED),
1310            (smbios_end, RSDP_BASE - smbios_end, defs::E820_RAM),
1311            (RSDP_BASE, 0x100000 - RSDP_BASE, defs::E820_RESERVED),
1312            (0x100000, 256 * MB - 0x100000, defs::E820_RAM),
1313        ];
1314        assert_eq!(p.e820_entries as usize, expected.len());
1315        for (i, (addr, size, typ)) in expected.iter().enumerate() {
1316            let e = &p.e820_map[i];
1317            assert_eq!(u64::from(e.addr), *addr, "entry {i} addr");
1318            assert_eq!(u64::from(e.size), *size, "entry {i} size");
1319            assert_eq!(u32::from(e.typ), *typ, "entry {i} type");
1320        }
1321        assert_contiguous(&p, 256 * MB);
1322    }
1323
1324    #[test]
1325    fn zero_page_skips_empty_smbios_region() {
1326        // With no SMBIOS structure table, the reserved SMBIOS region collapses
1327        // to zero length and must not appear as an empty e820 entry.
1328        let p = build_zero_page(
1329            &make_layout(256 * MB),
1330            0x1800,
1331            0,
1332            0,
1333            &CString::new("").unwrap(),
1334            0,
1335            0,
1336            None,
1337        )
1338        .unwrap()
1339        .boot_params;
1340
1341        let acpi_end = ACPI_TABLES_BASE + 0x2000;
1342        let expected = [
1343            (0, ACPI_TABLES_BASE, defs::E820_RAM),
1344            (ACPI_TABLES_BASE, 0x2000, defs::E820_ACPI),
1345            (acpi_end, RSDP_BASE - acpi_end, defs::E820_RAM),
1346            (RSDP_BASE, 0x100000 - RSDP_BASE, defs::E820_RESERVED),
1347            (0x100000, 256 * MB - 0x100000, defs::E820_RAM),
1348        ];
1349        assert_eq!(p.e820_entries as usize, expected.len());
1350        for (i, (addr, size, typ)) in expected.iter().enumerate() {
1351            let e = &p.e820_map[i];
1352            assert_eq!(u64::from(e.addr), *addr, "entry {i} addr");
1353            assert_eq!(u64::from(e.size), *size, "entry {i} size");
1354            assert_eq!(u32::from(e.typ), *typ, "entry {i} type");
1355        }
1356        assert_contiguous(&p, 256 * MB);
1357    }
1358
1359    #[test]
1360    fn zero_page_multiple_ram_ranges() {
1361        // 8 GiB of RAM splits around the 4 GiB MMIO gap into two ranges; the
1362        // second appears after the six fixed low-memory entries.
1363        let p = build_zero_page(
1364            &make_layout(8 * GB),
1365            0x1000,
1366            0x1000,
1367            0,
1368            &CString::new("").unwrap(),
1369            0,
1370            0,
1371            None,
1372        )
1373        .unwrap()
1374        .boot_params;
1375        assert_eq!(p.e820_entries, 7);
1376        let last = &p.e820_map[6];
1377        assert_eq!(u64::from(last.addr), 4 * GB);
1378        assert_eq!(u32::from(last.typ), defs::E820_RAM);
1379        // The six fixed low-memory entries are contiguous from 0; the second
1380        // RAM range sits above the 4 GiB MMIO gap, so contiguity legitimately
1381        // breaks there.
1382        let below_gap = &p.e820_map[5];
1383        assert_eq!(
1384            u64::from(below_gap.addr) + u64::from(below_gap.size),
1385            4 * GB - 128 * MB
1386        );
1387    }
1388
1389    #[test]
1390    fn zero_page_tables_too_large() {
1391        // ACPI tables large enough to run past the RSDP reserved region.
1392        let result = build_zero_page(
1393            &make_layout(256 * MB),
1394            (RSDP_BASE - ACPI_TABLES_BASE) as usize + 0x1000,
1395            0,
1396            0,
1397            &CString::new("").unwrap(),
1398            0,
1399            0,
1400            None,
1401        );
1402        match result {
1403            Err(Error::LowTablesTooLarge(..)) => {}
1404            other => panic!("expected LowTablesTooLarge, got {:?}", other.err()),
1405        }
1406    }
1407
1408    /// An importer that records `import_pages` placements and accepts registers,
1409    /// panicking on any other entry point (none of which the Linux config path
1410    /// exercises).
1411    #[derive(Default)]
1412    struct RecordingImporter {
1413        /// `(debug_tag, page_base, page_count)` for each imported region.
1414        pages: Vec<(String, u64, u64)>,
1415        imports: Vec<ImportRecord>,
1416        vp_context_page: Option<u64>,
1417    }
1418
1419    #[derive(Debug)]
1420    struct ImportRecord {
1421        page_base: u64,
1422        page_count: u64,
1423        tag: String,
1424        acceptance: BootPageAcceptance,
1425        data: Vec<u8>,
1426    }
1427
1428    impl RecordingImporter {
1429        fn page_base(&self, tag: &str) -> Option<u64> {
1430            self.pages
1431                .iter()
1432                .find(|(t, ..)| t == tag)
1433                .map(|(_, base, _)| *base)
1434        }
1435    }
1436
1437    impl ImageLoad<X86Register> for RecordingImporter {
1438        fn isolation_config(&self) -> IsolationConfig {
1439            IsolationConfig {
1440                paravisor_present: false,
1441                isolation_type: crate::importer::IsolationType::None,
1442                shared_gpa_boundary_bits: None,
1443            }
1444        }
1445
1446        fn create_parameter_area(
1447            &mut self,
1448            _page_base: u64,
1449            _page_count: u32,
1450            _debug_tag: &str,
1451        ) -> anyhow::Result<ParameterAreaIndex> {
1452            unimplemented!()
1453        }
1454
1455        fn create_parameter_area_with_data(
1456            &mut self,
1457            _page_base: u64,
1458            _page_count: u32,
1459            _debug_tag: &str,
1460            _initial_data: &[u8],
1461        ) -> anyhow::Result<ParameterAreaIndex> {
1462            unimplemented!()
1463        }
1464
1465        fn import_parameter(
1466            &mut self,
1467            _parameter_area: ParameterAreaIndex,
1468            _byte_offset: u32,
1469            _parameter_type: IgvmParameterType,
1470        ) -> anyhow::Result<()> {
1471            unimplemented!()
1472        }
1473
1474        fn import_pages(
1475            &mut self,
1476            page_base: u64,
1477            page_count: u64,
1478            debug_tag: &'static str,
1479            acceptance: BootPageAcceptance,
1480            data: &[u8],
1481        ) -> anyhow::Result<()> {
1482            self.pages
1483                .push((debug_tag.to_string(), page_base, page_count));
1484            self.imports.push(ImportRecord {
1485                page_base,
1486                page_count,
1487                tag: debug_tag.to_string(),
1488                acceptance,
1489                data: data.to_vec(),
1490            });
1491            Ok(())
1492        }
1493
1494        fn import_vp_register(&mut self, _register: X86Register) -> anyhow::Result<()> {
1495            Ok(())
1496        }
1497
1498        fn verify_startup_memory_available(
1499            &mut self,
1500            _page_base: u64,
1501            _page_count: u64,
1502            _memory_type: StartupMemoryType,
1503        ) -> anyhow::Result<()> {
1504            Ok(())
1505        }
1506
1507        fn set_vp_context_page(&mut self, page_base: u64) -> anyhow::Result<()> {
1508            self.vp_context_page = Some(page_base);
1509            Ok(())
1510        }
1511
1512        fn relocation_region(
1513            &mut self,
1514            _gpa: u64,
1515            _size_bytes: u64,
1516            _relocation_alignment: u64,
1517            _minimum_relocation_gpa: u64,
1518            _maximum_relocation_gpa: u64,
1519            _apply_rip_offset: bool,
1520            _apply_gdtr_offset: bool,
1521            _vp_index: u16,
1522        ) -> anyhow::Result<()> {
1523            unimplemented!()
1524        }
1525
1526        fn page_table_relocation(
1527            &mut self,
1528            _page_table_gpa: u64,
1529            _size_pages: u64,
1530            _used_pages: u64,
1531            _vp_index: u16,
1532        ) -> anyhow::Result<()> {
1533            unimplemented!()
1534        }
1535
1536        fn set_imported_regions_config_page(&mut self, _page_base: u64) {
1537            unimplemented!()
1538        }
1539    }
1540
1541    fn test_load_info() -> LoadInfo {
1542        LoadInfo {
1543            kernel: KernelInfo {
1544                gpa: KERNEL_BASE,
1545                size: 0x1000,
1546                entrypoint: KERNEL_BASE,
1547            },
1548            initrd: None,
1549            dtb: None,
1550            bzimage_setup_header: None,
1551        }
1552    }
1553
1554    #[test]
1555    fn import_config_places_tables_at_fixed_addresses() {
1556        let acpi = AcpiTables {
1557            rsdp: vec![0u8; 0x1000],
1558            tables: vec![0u8; 0x1800],
1559        };
1560        let smbios = crate::smbios::BuiltSmbios {
1561            entry_point: vec![0u8; crate::smbios::ENTRY_POINT_SIZE],
1562            structure_table: vec![0u8; 0x100],
1563        };
1564        let mut importer = RecordingImporter::default();
1565        import_config(
1566            &mut importer,
1567            &test_load_info(),
1568            &CString::new("console=ttyS0").unwrap(),
1569            &make_layout(256 * MB),
1570            &acpi,
1571            Some(&smbios),
1572            None,
1573        )
1574        .unwrap();
1575
1576        // The RSDP is re-homed to the fixed legacy-scan address, while the
1577        // tables it points to stay at the loader's chosen base.
1578        assert_eq!(
1579            importer.page_base("linux-rsdp"),
1580            Some(RSDP_BASE / HV_PAGE_SIZE)
1581        );
1582        assert_eq!(
1583            importer.page_base("linux-acpi-tables"),
1584            Some(ACPI_TABLES_BASE / HV_PAGE_SIZE)
1585        );
1586        // The SMBIOS anchor lands in the F-segment; the structure table sits
1587        // just above the ACPI tables.
1588        assert_eq!(
1589            importer.page_base("linux-smbios-anchor"),
1590            Some(SMBIOS_FSEGMENT_BASE / HV_PAGE_SIZE)
1591        );
1592        assert_eq!(
1593            importer.page_base("linux-smbios-tables"),
1594            Some(smbios_struct_table_base(acpi.tables.len()) / HV_PAGE_SIZE)
1595        );
1596        // Boot metadata at its fixed low-memory homes.
1597        assert_eq!(
1598            importer.page_base("linux-zeropage"),
1599            Some(ZERO_PAGE_BASE / HV_PAGE_SIZE)
1600        );
1601        assert_eq!(
1602            importer.page_base("linux-commandline"),
1603            Some(CMDLINE_BASE / HV_PAGE_SIZE)
1604        );
1605        assert_eq!(
1606            importer.page_base("linux-pagetables"),
1607            Some(CR3_BASE / HV_PAGE_SIZE)
1608        );
1609    }
1610
1611    #[test]
1612    fn import_config_rejects_oversized_command_line() {
1613        let acpi = AcpiTables {
1614            rsdp: vec![0u8; 0x1000],
1615            tables: vec![0u8; 0x1000],
1616        };
1617        // One byte too long once the NUL terminator is added.
1618        let cmdline = CString::new(vec![b'a'; (CR3_BASE - CMDLINE_BASE) as usize]).unwrap();
1619        let mut importer = RecordingImporter::default();
1620        let err = import_config(
1621            &mut importer,
1622            &test_load_info(),
1623            &cmdline,
1624            &make_layout(256 * MB),
1625            &acpi,
1626            None,
1627            None,
1628        )
1629        .unwrap_err();
1630        assert!(matches!(err, Error::CommandLineTooLong(..)), "got {err:?}");
1631        assert!(importer.pages.is_empty(), "importer used before the check");
1632    }
1633
1634    #[test]
1635    fn import_config_sets_snp_c_bit_in_page_tables() {
1636        const C_BIT: u8 = 51;
1637        let acpi = AcpiTables {
1638            rsdp: vec![0u8; 0x1000],
1639            tables: vec![0u8; 0x1000],
1640        };
1641        let mut importer = RecordingImporter::default();
1642        import_config(
1643            &mut importer,
1644            &test_load_info(),
1645            &CString::new("").unwrap(),
1646            &make_layout(256 * MB),
1647            &acpi,
1648            None,
1649            Some(SnpBootConfig { c_bit: C_BIT }),
1650        )
1651        .unwrap();
1652
1653        let page_tables = importer
1654            .imports
1655            .iter()
1656            .find(|import| import.tag == "linux-pagetables")
1657            .unwrap();
1658        for entry in page_tables.data.chunks_exact(8).map(|entry| {
1659            u64::from_ne_bytes(entry.try_into().expect("page table entry is eight bytes"))
1660        }) {
1661            if entry & 1 != 0 {
1662                assert_ne!(entry & (1 << C_BIT), 0);
1663            }
1664        }
1665    }
1666
1667    #[test]
1668    fn import_config_rejects_empty_acpi_tables() {
1669        // Empty tables would import zero pages; the loader must reject them
1670        // rather than feed page_count == 0 into the importer.
1671        let acpi = AcpiTables {
1672            rsdp: vec![0u8; 0x1000],
1673            tables: Vec::new(),
1674        };
1675        let mut importer = RecordingImporter::default();
1676        let err = import_config(
1677            &mut importer,
1678            &test_load_info(),
1679            &CString::new("").unwrap(),
1680            &make_layout(256 * MB),
1681            &acpi,
1682            None,
1683            None,
1684        )
1685        .unwrap_err();
1686        assert!(matches!(err, Error::EmptyAcpiTables), "got {err:?}");
1687    }
1688
1689    #[test]
1690    fn imports_snp_boot_pages_with_linux_cc_blob() {
1691        let acpi_len = 0x1800;
1692        let smbios_len = 0x100;
1693        let ZeroPageBuildResult {
1694            boot_params,
1695            additional_pages,
1696        } = build_zero_page(
1697            &make_layout(256 * MB),
1698            acpi_len,
1699            smbios_len,
1700            SNP_BOOT_PAGE_COUNT,
1701            &CString::new("").unwrap(),
1702            0,
1703            0,
1704            None,
1705        )
1706        .unwrap();
1707        let allocated_range = additional_pages.unwrap();
1708        let mut importer = RecordingImporter::default();
1709
1710        let cc_setup_data_address = import_snp_boot_pages(&mut importer, allocated_range).unwrap();
1711
1712        assert_eq!(importer.imports.len(), 4);
1713        assert_eq!(
1714            allocated_range.start(),
1715            ACPI_TABLES_BASE
1716                + align_up_to_page_size(acpi_len as u64)
1717                + align_up_to_page_size(smbios_len as u64)
1718        );
1719        assert_eq!(
1720            importer.imports[0].page_base,
1721            allocated_range.start() / HV_PAGE_SIZE
1722        );
1723        assert_eq!(importer.imports[0].page_count, 1);
1724        assert_eq!(importer.imports[0].tag, "linux-snp-secrets");
1725        assert_eq!(
1726            importer.imports[0].acceptance,
1727            BootPageAcceptance::SecretsPage
1728        );
1729        assert_eq!(
1730            importer.imports[1].page_base,
1731            allocated_range.start() / HV_PAGE_SIZE + 1
1732        );
1733        assert_eq!(
1734            importer.imports[1].acceptance,
1735            BootPageAcceptance::CpuidPage
1736        );
1737        let cpuid_page =
1738            crate::cpuid::HV_PSP_CPUID_PAGE::read_from_bytes(&importer.imports[1].data).unwrap();
1739        assert_eq!(
1740            cpuid_page.count as usize,
1741            crate::cpuid::SNP_REQUIRED_CPUID_LEAF_LIST_PARAVISOR.len()
1742        );
1743        for (entry, leaf) in cpuid_page
1744            .cpuid_leaf_info
1745            .iter()
1746            .zip(crate::cpuid::SNP_REQUIRED_CPUID_LEAF_LIST_PARAVISOR)
1747        {
1748            assert_eq!(entry.eax_in, leaf.eax);
1749            assert_eq!(entry.ecx_in, leaf.ecx);
1750            assert_eq!(
1751                entry.xfem_in,
1752                u64::from(leaf.eax == CpuidFunction::ExtendedStateEnumeration.0 && leaf.ecx <= 1)
1753            );
1754            assert_eq!(entry.xss_in, 0);
1755        }
1756
1757        let cc_blob = defs::cc_blob_sev_info::read_from_bytes(&importer.imports[2].data).unwrap();
1758        assert_eq!(cc_blob.magic, defs::CC_BLOB_SEV_INFO_MAGIC);
1759        assert_eq!(cc_blob.version, 0);
1760        assert_eq!(cc_blob.secrets_phys, allocated_range.start());
1761        assert_eq!(cc_blob.secrets_len, HV_PAGE_SIZE as u32);
1762        assert_eq!(cc_blob.cpuid_phys, allocated_range.start() + HV_PAGE_SIZE);
1763        assert_eq!(cc_blob.cpuid_len, HV_PAGE_SIZE as u32);
1764
1765        let cc_setup_data =
1766            defs::cc_setup_data::read_from_bytes(&importer.imports[3].data).unwrap();
1767        assert_eq!(cc_setup_data.header.next, 0);
1768        assert_eq!(cc_setup_data.header.ty, defs::SETUP_CC_BLOB);
1769        assert_eq!(
1770            cc_setup_data.header.len,
1771            (size_of::<defs::cc_setup_data>() - size_of::<defs::setup_data>()) as u32
1772        );
1773        assert_eq!(
1774            cc_setup_data.cc_blob_address,
1775            u32::try_from(allocated_range.start() + 2 * HV_PAGE_SIZE).unwrap()
1776        );
1777        assert_eq!(
1778            importer.vp_context_page,
1779            Some(allocated_range.start() / HV_PAGE_SIZE + 4)
1780        );
1781        assert_eq!(
1782            allocated_range.end(),
1783            cc_setup_data_address + 2 * HV_PAGE_SIZE,
1784        );
1785        assert!(allocated_range.end() <= RSDP_BASE);
1786
1787        let smbios_reserved = &boot_params.e820_map[2];
1788        let acpi_end = ACPI_TABLES_BASE + align_up_to_page_size(acpi_len as u64);
1789        assert_eq!(u64::from(smbios_reserved.addr), acpi_end);
1790        assert_eq!(
1791            u64::from(smbios_reserved.size),
1792            align_up_to_page_size(smbios_len as u64)
1793        );
1794        let additional_reserved = &boot_params.e820_map[3];
1795        assert_eq!(u64::from(additional_reserved.addr), allocated_range.start());
1796        assert_eq!(u64::from(additional_reserved.size), allocated_range.len());
1797
1798        assert!(matches!(
1799            build_zero_page(
1800                &make_layout(256 * MB),
1801                (RSDP_BASE - ACPI_TABLES_BASE) as usize,
1802                0,
1803                SNP_BOOT_PAGE_COUNT,
1804                &CString::new("").unwrap(),
1805                0,
1806                0,
1807                None,
1808            ),
1809            Err(Error::LowTablesTooLarge(..))
1810        ));
1811    }
1812
1813    /// Builds a minimal little-endian x86-64 ELF executable with one `PT_LOAD`
1814    /// program header, and no file contents, for each `(paddr, memsz)` in
1815    /// `load_segments`.
1816    fn test_elf(entrypoint: u64, load_segments: &[(u64, u64)]) -> Cursor<Vec<u8>> {
1817        use object::LittleEndian;
1818        use object::U16;
1819        use object::U32;
1820        use object::U64;
1821        use object::elf;
1822
1823        let header_size = size_of::<elf::FileHeader64<LittleEndian>>();
1824        let header = elf::FileHeader64::<LittleEndian> {
1825            e_ident: elf::Ident {
1826                magic: elf::ELFMAG,
1827                class: elf::ELFCLASS64,
1828                data: elf::ELFDATA2LSB,
1829                version: elf::EV_CURRENT,
1830                os_abi: elf::ELFOSABI_NONE,
1831                abi_version: 0,
1832                padding: [0; 7],
1833            },
1834            e_type: U16::new(LittleEndian, elf::ET_EXEC),
1835            e_machine: U16::new(LittleEndian, elf::EM_X86_64),
1836            e_version: U32::new(LittleEndian, elf::EV_CURRENT.into()),
1837            e_entry: U64::new(LittleEndian, entrypoint),
1838            e_phoff: U64::new(LittleEndian, header_size as u64),
1839            e_shoff: U64::new(LittleEndian, 0),
1840            e_flags: U32::new(LittleEndian, 0),
1841            e_ehsize: U16::new(LittleEndian, header_size as u16),
1842            e_phentsize: U16::new(
1843                LittleEndian,
1844                size_of::<elf::ProgramHeader64<LittleEndian>>() as u16,
1845            ),
1846            e_phnum: U16::new(LittleEndian, load_segments.len().try_into().unwrap()),
1847            e_shentsize: U16::new(
1848                LittleEndian,
1849                size_of::<elf::SectionHeader64<LittleEndian>>() as u16,
1850            ),
1851            e_shnum: U16::new(LittleEndian, 0),
1852            e_shstrndx: U16::new(LittleEndian, 0),
1853        };
1854        let mut image = object::pod::bytes_of(&header).to_vec();
1855        for &(paddr, memsz) in load_segments {
1856            let program_header = elf::ProgramHeader64::<LittleEndian> {
1857                p_type: U32::new(LittleEndian, elf::PT_LOAD),
1858                p_flags: U32::new(LittleEndian, elf::PF_R | elf::PF_X),
1859                p_offset: U64::new(LittleEndian, 0),
1860                p_vaddr: U64::new(LittleEndian, paddr),
1861                p_paddr: U64::new(LittleEndian, paddr),
1862                p_filesz: U64::new(LittleEndian, 0),
1863                p_memsz: U64::new(LittleEndian, memsz),
1864                p_align: U64::new(LittleEndian, HV_PAGE_SIZE),
1865            };
1866            image.extend_from_slice(object::pod::bytes_of(&program_header));
1867        }
1868        Cursor::new(image)
1869    }
1870
1871    #[test]
1872    fn elf_without_load_segments_is_rejected() {
1873        let mut importer = RecordingImporter::default();
1874        let mut kernel_image = test_elf(KERNEL_BASE, &[]);
1875        let error = load_kernel_and_initrd_x64(&mut importer, &mut kernel_image, KERNEL_BASE, None)
1876            .unwrap_err();
1877        assert!(matches!(
1878            error,
1879            Error::ElfLoader(crate::elf::Error::NoLoadableSegments)
1880        ));
1881        assert!(importer.imports.is_empty());
1882    }
1883
1884    #[test]
1885    fn mptable_loader_rejects_elf_without_load_segments() {
1886        let mut importer = RecordingImporter::default();
1887        let mut kernel_image = test_elf(KERNEL_BASE, &[]);
1888        let config = mptable::MpTableConfig {
1889            apic_ids: &[0],
1890            level_triggered_irqs: &[],
1891        };
1892        let error = mptable_boot::load_x86_mptable(
1893            &mut importer,
1894            &mut kernel_image,
1895            None,
1896            &CString::new("").unwrap(),
1897            &make_layout(256 * MB),
1898            &config,
1899            &[],
1900        )
1901        .unwrap_err();
1902
1903        assert!(matches!(
1904            error,
1905            Error::ElfLoader(crate::elf::Error::NoLoadableSegments)
1906        ));
1907        assert!(importer.imports.is_empty());
1908    }
1909
1910    #[test]
1911    fn elf_with_only_empty_load_segment_is_rejected() {
1912        let mut importer = RecordingImporter::default();
1913        let mut kernel_image = test_elf(KERNEL_BASE + 1, &[(KERNEL_BASE + 1, 0)]);
1914        let error = load_kernel_and_initrd_x64(&mut importer, &mut kernel_image, KERNEL_BASE, None)
1915            .unwrap_err();
1916        assert!(matches!(
1917            error,
1918            Error::ElfLoader(crate::elf::Error::NoLoadableSegments)
1919        ));
1920        assert!(importer.imports.is_empty());
1921    }
1922
1923    #[test]
1924    fn elf_entrypoint_outside_load_segments_is_rejected() {
1925        let mut importer = RecordingImporter::default();
1926        let mut kernel_image = test_elf(
1927            KERNEL_BASE + HV_PAGE_SIZE,
1928            &[
1929                (KERNEL_BASE, HV_PAGE_SIZE),
1930                (KERNEL_BASE + 2 * HV_PAGE_SIZE, HV_PAGE_SIZE),
1931            ],
1932        );
1933        let error = load_kernel_and_initrd_x64(&mut importer, &mut kernel_image, KERNEL_BASE, None)
1934            .unwrap_err();
1935        assert!(matches!(
1936            error,
1937            Error::ElfLoader(crate::elf::Error::EntryPointNotInLoadableSegment { .. })
1938        ));
1939        assert!(importer.imports.is_empty());
1940    }
1941
1942    #[test]
1943    fn initrd_after_kernel_alignment_overflow_is_rejected() {
1944        let mut importer = RecordingImporter::default();
1945        let mut initrd = Cursor::new([0]);
1946        let error = import_initrd(
1947            Some(InitrdConfig {
1948                initrd_address: InitrdAddressType::AfterKernel,
1949                initrd: &mut initrd,
1950                size: 1,
1951            }),
1952            u64::MAX - HV_PAGE_SIZE + 1,
1953            &mut importer,
1954        )
1955        .unwrap_err();
1956        assert!(matches!(error, Error::InitrdAddressTooHigh(_)));
1957        assert!(importer.imports.is_empty());
1958    }
1959}