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(x86defs::X64_CR0_PG | x86defs::X64_CR0_PE))?;
846    import_reg(X86Register::Cr3(CR3_BASE))?;
847    import_reg(X86Register::Cr4(x86defs::X64_CR4_PAE))?;
848    import_reg(X86Register::Efer(
849        x86defs::X64_EFER_SCE
850            | x86defs::X64_EFER_LME
851            | x86defs::X64_EFER_LMA
852            | x86defs::X64_EFER_NXE,
853    ))?;
854    import_reg(X86Register::Pat(x86defs::X86X_MSR_DEFAULT_PAT))?;
855
856    // No firmware will set MTRR values for the BSP.  Replicate what UEFI does here.
857    // (enable MTRRs, default MTRR is uncached, and set lowest 640KB as WB)
858    import_reg(X86Register::MtrrDefType(0xc00))?;
859    import_reg(X86Register::MtrrFix64k00000(0x0606060606060606))?;
860    import_reg(X86Register::MtrrFix16k80000(0x0606060606060606))?;
861    Ok(())
862}
863
864/// Imports the initial state for a 64-bit SEV-SNP boot stage that runs before
865/// Linux, such as a bootshim that starts the Linux EFI stub.
866///
867/// This imports a GDT, a 4-GiB identity map with the C-bit, the SEV-SNP guest
868/// pages, and the long-mode registers. It does not build a zero page. The
869/// caller sets RIP and any argument registers.
870///
871/// Returns the SNP guest pages and the end of the low memory that this uses.
872pub fn import_snp_boot_stage(
873    importer: &mut impl ImageLoad<X86Register>,
874    snp_boot: SnpBootConfig,
875) -> Result<(SnpGuestPages, u64), Error> {
876    import_default_gdt(importer, GDT_BASE / HV_PAGE_SIZE).map_err(Error::Importer)?;
877    import_identity_map(importer, Some(snp_boot))?;
878    let pages_base = align_up_to_page_size(LOW_METADATA_END);
879    let pages = import_snp_guest_pages(importer, pages_base)?;
880    import_long_mode_registers(importer)?;
881    Ok((pages, pages_base + 3 * HV_PAGE_SIZE))
882}
883
884/// Place the ACPI tables, SMBIOS tables, boot metadata, zero page, and initial
885/// registers for a Linux kernel that has *already* been loaded into guest
886/// memory (as described by `load_info`).
887///
888/// The loader owns the entire sub-1 MB memory map; callers supply only
889/// contents, never addresses:
890///
891/// * `cmdline` - the kernel command line.
892/// * `mem_layout` - the guest memory layout, used to build the e820 map.
893/// * `build_acpi` - a builder handed the nominal RSDP address; it must return
894///   ACPI tables self-consistent for placement one page above that address.
895///   The loader re-homes the RSDP to the fixed 0xe0000 legacy-scan location.
896/// * `smbios` - an optional SMBIOS identity; when present the loader assembles
897///   the `_SM3_` entry point and structure table into the F-segment.
898/// * `snp_boot` - optionally allocate SEV-SNP Linux boot protocol pages.
899pub fn load_config_x86(
900    importer: &mut impl ImageLoad<X86Register>,
901    load_info: &LoadInfo,
902    cmdline: &CString,
903    mem_layout: &MemoryLayout,
904    build_acpi: impl FnOnce(u64) -> AcpiTables,
905    smbios: Option<crate::smbios::SmbiosTables<'_>>,
906    snp_boot: Option<SnpBootConfig>,
907) -> Result<(), Error> {
908    // The builder lays out a nominal RSDP page at LOW_METADATA_END followed by
909    // the tables it points to; we keep only the tables (placed at
910    // ACPI_TABLES_BASE) and re-home the RSDP to the fixed scan location.
911    let acpi_tables = build_acpi(LOW_METADATA_END);
912
913    // Build the SMBIOS tables (if an identity was supplied) with the structure
914    // table addressed at its low-area home: the `_SM3_` anchor's 64-bit pointer
915    // references it there while the anchor itself lands in the F-segment for the
916    // kernel's DMI scan. See `smbios_struct_table_base` / `import_config`.
917    let smbios = smbios.map(|tables| {
918        crate::smbios::build(&tables, smbios_struct_table_base(acpi_tables.tables.len()))
919    });
920
921    import_config(
922        importer,
923        load_info,
924        cmdline,
925        mem_layout,
926        &acpi_tables,
927        smbios.as_ref(),
928        snp_boot,
929    )
930}
931
932/// Load a Linux kernel into VTL0 and place all of its supporting structures.
933///
934/// Loads the kernel (uncompressed ELF or bzImage) and optional initrd at the
935/// conventional 1 MB address, then delegates to [`load_config_x86`] to place
936/// the ACPI/SMBIOS tables, boot metadata, zero page, and initial registers.
937/// See [`load_config_x86`] for the `build_acpi`/`smbios` contract.
938pub fn load_x86<F>(
939    importer: &mut impl ImageLoad<X86Register>,
940    kernel_image: &mut F,
941    initrd: Option<InitrdConfig<'_>>,
942    cmdline: &CString,
943    mem_layout: &MemoryLayout,
944    build_acpi: impl FnOnce(u64) -> AcpiTables,
945    smbios: Option<crate::smbios::SmbiosTables<'_>>,
946    snp_boot: Option<SnpBootConfig>,
947) -> Result<LoadInfo, Error>
948where
949    F: Read + Seek,
950{
951    let load_info = load_kernel_and_initrd_x64(importer, kernel_image, KERNEL_BASE, initrd)?;
952    load_config_x86(
953        importer, &load_info, cmdline, mem_layout, build_acpi, smbios, snp_boot,
954    )?;
955    Ok(load_info)
956}
957
958open_enum::open_enum! {
959    #[derive(IntoBytes, Immutable, KnownLayout, FromBytes)]
960    pub enum Aarch64ImagePageSize: u64 {
961        UNSPECIFIED = 0,
962        PAGE4_K = 1,
963        PAGE16_K = 2,
964        PAGE64_K = 3,
965    }
966
967}
968
969impl Aarch64ImagePageSize {
970    const fn into_bits(self) -> u64 {
971        self.0
972    }
973
974    const fn from_bits(bits: u64) -> Self {
975        Self(bits)
976    }
977}
978
979/// Arm64 flat kernel `Image` flags.
980#[bitfield(u64)]
981struct Aarch64ImageFlags {
982    /// Bit 0:	Kernel endianness.  1 if BE, 0 if LE.
983    #[bits(1)]
984    pub big_endian: bool,
985    /// Bit 1-2:	Kernel Page size.
986    ///           0 - Unspecified.
987    ///           1 - 4K
988    ///           2 - 16K
989    ///           3 - 64K
990    #[bits(2)]
991    pub page_size: Aarch64ImagePageSize,
992    /// Bit 3:	Kernel physical placement
993    ///           0 - 2MB aligned base should be as close as possible
994    ///               to the base of DRAM, since memory below it is not
995    ///               accessible via the linear mapping
996    ///           1 - 2MB aligned base may be anywhere in physical
997    ///               memory
998    #[bits(1)]
999    pub any_start_address: bool,
1000    /// Bits 4-63:	Reserved.
1001    #[bits(60)]
1002    pub _padding: u64,
1003}
1004
1005// Kernel boot protocol is specified in the Linux kernel
1006// Documentation/arm64/booting.txt.
1007#[derive(Debug, IntoBytes, Immutable, KnownLayout, FromBytes)]
1008#[repr(C)]
1009struct Aarch64ImageHeader {
1010    /// Executable code
1011    _code0: u32,
1012    /// Executable code
1013    _code1: u32,
1014    /// Image load offset, little endian
1015    text_offset: u64,
1016    /// Effective Image size, little endian
1017    image_size: u64,
1018    /// kernel flags, little endian
1019    flags: u64,
1020    /// reserved
1021    _res2: u64,
1022    /// reserved
1023    _res3: u64,
1024    /// reserved
1025    _res4: u64,
1026    /// Magic number, little endian, "ARM\x64"
1027    magic: [u8; 4],
1028    /// reserved (used for PE COFF offset)
1029    _res5: u32,
1030}
1031
1032const AARCH64_MAGIC_NUMBER: &[u8] = b"ARM\x64";
1033
1034/// Load only an arm64 the flat Linux kernel `Image` and optional initrd.
1035/// This does not setup register state or any other config information.
1036///
1037/// # Arguments
1038///
1039/// * `importer` - The importer to use.
1040/// * `kernel_image` - Uncompressed ELF image for the kernel.
1041/// * `kernel_minimum_start_address` - The minimum address the kernel can load at.
1042///   It cannot contain an entrypoint or program headers that refer to memory below this address.
1043/// * `initrd` - The initrd config, optional.
1044/// * `device_tree_blob` - The device tree blob, optional.
1045pub fn load_kernel_and_initrd_arm64<F>(
1046    importer: &mut dyn ImageLoad<Aarch64Register>,
1047    kernel_image: &mut F,
1048    kernel_minimum_start_address: u64,
1049    initrd: Option<InitrdConfig<'_>>,
1050    device_tree_blob: Option<&[u8]>,
1051) -> Result<LoadInfo, Error>
1052where
1053    F: Read + Seek,
1054{
1055    tracing::trace!(kernel_minimum_start_address, "loading aarch64 kernel");
1056
1057    assert_eq!(
1058        kernel_minimum_start_address & ((1 << 21) - 1),
1059        0,
1060        "Start offset must be aligned on the 2MiB boundary"
1061    );
1062
1063    kernel_image
1064        .seek(SeekFrom::Start(0))
1065        .map_err(|_| Error::FlatLoader(FlatLoaderError::SeekKernelStart))?;
1066
1067    let mut header = Aarch64ImageHeader::new_zeroed();
1068    kernel_image
1069        .read_exact(header.as_mut_bytes())
1070        .map_err(|_| Error::FlatLoader(FlatLoaderError::ReadKernelImage))?;
1071
1072    tracing::debug!("aarch64 kernel header {header:x?}");
1073
1074    if header.magic != AARCH64_MAGIC_NUMBER {
1075        return Err(Error::FlatLoader(FlatLoaderError::BadImageMagic));
1076    }
1077
1078    let flags = Aarch64ImageFlags::from(header.flags);
1079    if flags.big_endian() {
1080        return Err(Error::FlatLoader(FlatLoaderError::BigEndianKernelImage));
1081    }
1082    if flags.page_size() != Aarch64ImagePageSize::PAGE4_K {
1083        return Err(Error::FlatLoader(
1084            FlatLoaderError::FourKibPageImageIsRequired,
1085        ));
1086    }
1087    if !flags.any_start_address() {
1088        return Err(Error::FlatLoader(FlatLoaderError::LowMemoryKernel));
1089    }
1090
1091    // The `Image` must be placed `text_offset` bytes from a 2MB aligned base
1092    // address anywhere in usable system RAM and called there.
1093
1094    kernel_image
1095        .seek(SeekFrom::Start(0))
1096        .map_err(|_| Error::FlatLoader(FlatLoaderError::SeekKernelStart))?;
1097
1098    let mut image = Vec::new();
1099    kernel_image
1100        .read_to_end(&mut image)
1101        .map_err(|_| Error::FlatLoader(FlatLoaderError::ReadKernelImage))?;
1102
1103    let kernel_load_offset = (kernel_minimum_start_address + header.text_offset) as usize;
1104    let kernel_size = if header.image_size != 0 {
1105        header.image_size
1106    } else {
1107        image.len() as u64
1108    };
1109
1110    let kernel_size = align_up_to_page_size(kernel_size);
1111    importer
1112        .import_pages(
1113            kernel_load_offset as u64 / HV_PAGE_SIZE,
1114            kernel_size / HV_PAGE_SIZE,
1115            "linux-kernel",
1116            BootPageAcceptance::Exclusive,
1117            &image,
1118        )
1119        .map_err(Error::Importer)?;
1120
1121    let next_addr = kernel_load_offset as u64 + kernel_size;
1122
1123    let (next_addr, dtb) = if let Some(device_tree_blob) = device_tree_blob {
1124        let dtb_addr = align_up_to_page_size(next_addr);
1125        tracing::trace!(dtb_addr, "loading device tree blob at {dtb_addr:x?}");
1126
1127        check_address_alignment(dtb_addr)?;
1128        let dtb_size_pages = align_up_to_page_size(device_tree_blob.len() as u64) / HV_PAGE_SIZE;
1129
1130        importer
1131            .import_pages(
1132                dtb_addr / HV_PAGE_SIZE,
1133                dtb_size_pages,
1134                "linux-device-tree",
1135                BootPageAcceptance::Exclusive,
1136                device_tree_blob,
1137            )
1138            .map_err(Error::Importer)?;
1139
1140        (
1141            dtb_addr + device_tree_blob.len() as u64,
1142            Some(dtb_addr..dtb_addr + device_tree_blob.len() as u64),
1143        )
1144    } else {
1145        (next_addr, None)
1146    };
1147
1148    let initrd_info = import_initrd(initrd, next_addr, importer)?;
1149
1150    Ok(LoadInfo {
1151        kernel: KernelInfo {
1152            gpa: kernel_minimum_start_address,
1153            size: kernel_size,
1154            entrypoint: kernel_load_offset as u64,
1155        },
1156        initrd: initrd_info,
1157        dtb,
1158        bzimage_setup_header: None,
1159    })
1160}
1161
1162/// Load the configuration info and registers for the Linux kernel based on the provided LoadInfo.
1163/// Parameters:
1164/// * `importer` - The importer to use.
1165/// * `load_info` - The kernel load info that contains information on where the kernel and initrd are.
1166/// * `vtl` - The target VTL.
1167pub fn set_direct_boot_registers_arm64(
1168    importer: &mut impl ImageLoad<Aarch64Register>,
1169    load_info: &LoadInfo,
1170) -> Result<(), Error> {
1171    let mut import_reg = |register| {
1172        importer
1173            .import_vp_register(register)
1174            .map_err(Error::Importer)
1175    };
1176
1177    import_reg(Aarch64Register::Pc(load_info.kernel.entrypoint))?;
1178    import_reg(Aarch64Register::Cpsr(
1179        Cpsr64::new()
1180            .with_sp(true)
1181            .with_el(1)
1182            .with_f(true)
1183            .with_i(true)
1184            .with_a(true)
1185            .with_d(true)
1186            .into(),
1187    ))?;
1188    import_reg(Aarch64Register::SctlrEl1(
1189        SctlrEl1::new()
1190            // MMU is disabled for EL1&0 stage 1 address translation.
1191            // The family of the `at` instructions and the `PAR_EL1` register are
1192            // useful for debugging MMU issues when it's on.
1193            .with_m(false)
1194            // Stage 1 Cacheability control, for data accesses.
1195            .with_c(true)
1196            // Stage 1 Cacheability control, for code.
1197            .with_i(true)
1198            // Reserved flags, must be set
1199            .with_eos(true)
1200            .with_tscxt(true)
1201            .with_eis(true)
1202            .with_span(true)
1203            .with_n_tlsmd(true)
1204            .with_lsmaoe(true)
1205            .into(),
1206    ))?;
1207    import_reg(Aarch64Register::TcrEl1(
1208        TranslationControlEl1::new()
1209            .with_t0sz(0x11)
1210            .with_irgn0(1)
1211            .with_orgn0(1)
1212            .with_sh0(3)
1213            .with_tg0(TranslationGranule0::TG_4KB)
1214            // Disable TTBR0_EL1 walks (i.e. the lower half).
1215            .with_epd0(1)
1216            // Disable TTBR1_EL1 walks (i.e. the upper half).
1217            .with_epd1(1)
1218            // Due to erratum #822227, need to set a valid TG1 regardless of EPD1.
1219            .with_tg1(TranslationGranule1::TG_4KB)
1220            .with_ips(IntermPhysAddrSize::IPA_48_BITS_256_TB)
1221            .into(),
1222    ))?;
1223    import_reg(Aarch64Register::Ttbr0El1(TranslationBaseEl1::new().into()))?;
1224    import_reg(Aarch64Register::Ttbr1El1(TranslationBaseEl1::new().into()))?;
1225    import_reg(Aarch64Register::VbarEl1(0))?;
1226
1227    if let Some(dtb) = &load_info.dtb {
1228        import_reg(Aarch64Register::X0(dtb.start))?;
1229    }
1230
1231    Ok(())
1232}
1233#[cfg(test)]
1234mod tests {
1235    use super::*;
1236    use crate::importer::IgvmParameterType;
1237    use crate::importer::IsolationConfig;
1238    use crate::importer::ParameterAreaIndex;
1239    use crate::importer::StartupMemoryType;
1240    use std::io::Cursor;
1241    use test_with_tracing::test;
1242    use zerocopy::FromBytes;
1243
1244    const MB: u64 = 0x100000;
1245    const GB: u64 = 0x4000_0000;
1246
1247    /// A guest memory layout with `ram_size` bytes of RAM and a 128 MB MMIO gap
1248    /// below 4 GiB (matching a typical x86_64 config). RAM up to the gap forms
1249    /// the first range `[0, min(ram_size, 4 GiB - 128 MB))`.
1250    fn make_layout(ram_size: u64) -> MemoryLayout {
1251        MemoryLayout::new(
1252            ram_size,
1253            &[MemoryRange::new(4 * GB - 128 * MB..4 * GB)],
1254            &[],
1255            &[],
1256            None,
1257        )
1258        .unwrap()
1259    }
1260
1261    /// Asserts that `map[..entries]` exactly covers `[0, first_ram_end)` with no
1262    /// gaps or overlaps and strictly ascending addresses, and that no entry is
1263    /// empty. The first entry must start at 0 and the last must end precisely at
1264    /// `first_ram_end`.
1265    fn assert_contiguous(p: &defs::boot_params, first_ram_end: u64) {
1266        let entries = p.e820_entries as usize;
1267        assert!(entries > 0);
1268        let mut expected_addr = 0u64;
1269        for i in 0..entries {
1270            let e = &p.e820_map[i];
1271            assert_ne!(u64::from(e.size), 0, "entry {i} is empty");
1272            assert_eq!(u64::from(e.addr), expected_addr, "gap/overlap at entry {i}");
1273            expected_addr = u64::from(e.addr) + u64::from(e.size);
1274        }
1275        assert_eq!(
1276            expected_addr, first_ram_end,
1277            "map ends at {expected_addr:#x}, expected {first_ram_end:#x}"
1278        );
1279    }
1280
1281    #[test]
1282    fn zero_page_layout_with_smbios() {
1283        let acpi_len = 0x1800; // aligns up to 0x2000
1284        let smbios_len = 0x100; // aligns up to 0x1000
1285        let p = build_zero_page(
1286            &make_layout(256 * MB),
1287            acpi_len,
1288            smbios_len,
1289            0,
1290            &CString::new("root=/dev/sda").unwrap(),
1291            0,
1292            0,
1293            None,
1294        )
1295        .unwrap()
1296        .boot_params;
1297
1298        let acpi_end = ACPI_TABLES_BASE + 0x2000;
1299        let smbios_end = acpi_end + 0x1000;
1300        let expected = [
1301            (0, ACPI_TABLES_BASE, defs::E820_RAM),
1302            (ACPI_TABLES_BASE, 0x2000, defs::E820_ACPI),
1303            (acpi_end, 0x1000, defs::E820_RESERVED),
1304            (smbios_end, RSDP_BASE - smbios_end, defs::E820_RAM),
1305            (RSDP_BASE, 0x100000 - RSDP_BASE, defs::E820_RESERVED),
1306            (0x100000, 256 * MB - 0x100000, defs::E820_RAM),
1307        ];
1308        assert_eq!(p.e820_entries as usize, expected.len());
1309        for (i, (addr, size, typ)) in expected.iter().enumerate() {
1310            let e = &p.e820_map[i];
1311            assert_eq!(u64::from(e.addr), *addr, "entry {i} addr");
1312            assert_eq!(u64::from(e.size), *size, "entry {i} size");
1313            assert_eq!(u32::from(e.typ), *typ, "entry {i} type");
1314        }
1315        assert_contiguous(&p, 256 * MB);
1316    }
1317
1318    #[test]
1319    fn zero_page_skips_empty_smbios_region() {
1320        // With no SMBIOS structure table, the reserved SMBIOS region collapses
1321        // to zero length and must not appear as an empty e820 entry.
1322        let p = build_zero_page(
1323            &make_layout(256 * MB),
1324            0x1800,
1325            0,
1326            0,
1327            &CString::new("").unwrap(),
1328            0,
1329            0,
1330            None,
1331        )
1332        .unwrap()
1333        .boot_params;
1334
1335        let acpi_end = ACPI_TABLES_BASE + 0x2000;
1336        let expected = [
1337            (0, ACPI_TABLES_BASE, defs::E820_RAM),
1338            (ACPI_TABLES_BASE, 0x2000, defs::E820_ACPI),
1339            (acpi_end, RSDP_BASE - acpi_end, defs::E820_RAM),
1340            (RSDP_BASE, 0x100000 - RSDP_BASE, defs::E820_RESERVED),
1341            (0x100000, 256 * MB - 0x100000, defs::E820_RAM),
1342        ];
1343        assert_eq!(p.e820_entries as usize, expected.len());
1344        for (i, (addr, size, typ)) in expected.iter().enumerate() {
1345            let e = &p.e820_map[i];
1346            assert_eq!(u64::from(e.addr), *addr, "entry {i} addr");
1347            assert_eq!(u64::from(e.size), *size, "entry {i} size");
1348            assert_eq!(u32::from(e.typ), *typ, "entry {i} type");
1349        }
1350        assert_contiguous(&p, 256 * MB);
1351    }
1352
1353    #[test]
1354    fn zero_page_multiple_ram_ranges() {
1355        // 8 GiB of RAM splits around the 4 GiB MMIO gap into two ranges; the
1356        // second appears after the six fixed low-memory entries.
1357        let p = build_zero_page(
1358            &make_layout(8 * GB),
1359            0x1000,
1360            0x1000,
1361            0,
1362            &CString::new("").unwrap(),
1363            0,
1364            0,
1365            None,
1366        )
1367        .unwrap()
1368        .boot_params;
1369        assert_eq!(p.e820_entries, 7);
1370        let last = &p.e820_map[6];
1371        assert_eq!(u64::from(last.addr), 4 * GB);
1372        assert_eq!(u32::from(last.typ), defs::E820_RAM);
1373        // The six fixed low-memory entries are contiguous from 0; the second
1374        // RAM range sits above the 4 GiB MMIO gap, so contiguity legitimately
1375        // breaks there.
1376        let below_gap = &p.e820_map[5];
1377        assert_eq!(
1378            u64::from(below_gap.addr) + u64::from(below_gap.size),
1379            4 * GB - 128 * MB
1380        );
1381    }
1382
1383    #[test]
1384    fn zero_page_tables_too_large() {
1385        // ACPI tables large enough to run past the RSDP reserved region.
1386        let result = build_zero_page(
1387            &make_layout(256 * MB),
1388            (RSDP_BASE - ACPI_TABLES_BASE) as usize + 0x1000,
1389            0,
1390            0,
1391            &CString::new("").unwrap(),
1392            0,
1393            0,
1394            None,
1395        );
1396        match result {
1397            Err(Error::LowTablesTooLarge(..)) => {}
1398            other => panic!("expected LowTablesTooLarge, got {:?}", other.err()),
1399        }
1400    }
1401
1402    /// An importer that records `import_pages` placements and accepts registers,
1403    /// panicking on any other entry point (none of which the Linux config path
1404    /// exercises).
1405    #[derive(Default)]
1406    struct RecordingImporter {
1407        /// `(debug_tag, page_base, page_count)` for each imported region.
1408        pages: Vec<(String, u64, u64)>,
1409        imports: Vec<ImportRecord>,
1410        vp_context_page: Option<u64>,
1411    }
1412
1413    #[derive(Debug)]
1414    struct ImportRecord {
1415        page_base: u64,
1416        page_count: u64,
1417        tag: String,
1418        acceptance: BootPageAcceptance,
1419        data: Vec<u8>,
1420    }
1421
1422    impl RecordingImporter {
1423        fn page_base(&self, tag: &str) -> Option<u64> {
1424            self.pages
1425                .iter()
1426                .find(|(t, ..)| t == tag)
1427                .map(|(_, base, _)| *base)
1428        }
1429    }
1430
1431    impl ImageLoad<X86Register> for RecordingImporter {
1432        fn isolation_config(&self) -> IsolationConfig {
1433            IsolationConfig {
1434                paravisor_present: false,
1435                isolation_type: crate::importer::IsolationType::None,
1436                shared_gpa_boundary_bits: None,
1437            }
1438        }
1439
1440        fn create_parameter_area(
1441            &mut self,
1442            _page_base: u64,
1443            _page_count: u32,
1444            _debug_tag: &str,
1445        ) -> anyhow::Result<ParameterAreaIndex> {
1446            unimplemented!()
1447        }
1448
1449        fn create_parameter_area_with_data(
1450            &mut self,
1451            _page_base: u64,
1452            _page_count: u32,
1453            _debug_tag: &str,
1454            _initial_data: &[u8],
1455        ) -> anyhow::Result<ParameterAreaIndex> {
1456            unimplemented!()
1457        }
1458
1459        fn import_parameter(
1460            &mut self,
1461            _parameter_area: ParameterAreaIndex,
1462            _byte_offset: u32,
1463            _parameter_type: IgvmParameterType,
1464        ) -> anyhow::Result<()> {
1465            unimplemented!()
1466        }
1467
1468        fn import_pages(
1469            &mut self,
1470            page_base: u64,
1471            page_count: u64,
1472            debug_tag: &'static str,
1473            acceptance: BootPageAcceptance,
1474            data: &[u8],
1475        ) -> anyhow::Result<()> {
1476            self.pages
1477                .push((debug_tag.to_string(), page_base, page_count));
1478            self.imports.push(ImportRecord {
1479                page_base,
1480                page_count,
1481                tag: debug_tag.to_string(),
1482                acceptance,
1483                data: data.to_vec(),
1484            });
1485            Ok(())
1486        }
1487
1488        fn import_vp_register(&mut self, _register: X86Register) -> anyhow::Result<()> {
1489            Ok(())
1490        }
1491
1492        fn verify_startup_memory_available(
1493            &mut self,
1494            _page_base: u64,
1495            _page_count: u64,
1496            _memory_type: StartupMemoryType,
1497        ) -> anyhow::Result<()> {
1498            Ok(())
1499        }
1500
1501        fn set_vp_context_page(&mut self, page_base: u64) -> anyhow::Result<()> {
1502            self.vp_context_page = Some(page_base);
1503            Ok(())
1504        }
1505
1506        fn relocation_region(
1507            &mut self,
1508            _gpa: u64,
1509            _size_bytes: u64,
1510            _relocation_alignment: u64,
1511            _minimum_relocation_gpa: u64,
1512            _maximum_relocation_gpa: u64,
1513            _apply_rip_offset: bool,
1514            _apply_gdtr_offset: bool,
1515            _vp_index: u16,
1516        ) -> anyhow::Result<()> {
1517            unimplemented!()
1518        }
1519
1520        fn page_table_relocation(
1521            &mut self,
1522            _page_table_gpa: u64,
1523            _size_pages: u64,
1524            _used_pages: u64,
1525            _vp_index: u16,
1526        ) -> anyhow::Result<()> {
1527            unimplemented!()
1528        }
1529
1530        fn set_imported_regions_config_page(&mut self, _page_base: u64) {
1531            unimplemented!()
1532        }
1533    }
1534
1535    fn test_load_info() -> LoadInfo {
1536        LoadInfo {
1537            kernel: KernelInfo {
1538                gpa: KERNEL_BASE,
1539                size: 0x1000,
1540                entrypoint: KERNEL_BASE,
1541            },
1542            initrd: None,
1543            dtb: None,
1544            bzimage_setup_header: None,
1545        }
1546    }
1547
1548    #[test]
1549    fn import_config_places_tables_at_fixed_addresses() {
1550        let acpi = AcpiTables {
1551            rsdp: vec![0u8; 0x1000],
1552            tables: vec![0u8; 0x1800],
1553        };
1554        let smbios = crate::smbios::BuiltSmbios {
1555            entry_point: vec![0u8; crate::smbios::ENTRY_POINT_SIZE],
1556            structure_table: vec![0u8; 0x100],
1557        };
1558        let mut importer = RecordingImporter::default();
1559        import_config(
1560            &mut importer,
1561            &test_load_info(),
1562            &CString::new("console=ttyS0").unwrap(),
1563            &make_layout(256 * MB),
1564            &acpi,
1565            Some(&smbios),
1566            None,
1567        )
1568        .unwrap();
1569
1570        // The RSDP is re-homed to the fixed legacy-scan address, while the
1571        // tables it points to stay at the loader's chosen base.
1572        assert_eq!(
1573            importer.page_base("linux-rsdp"),
1574            Some(RSDP_BASE / HV_PAGE_SIZE)
1575        );
1576        assert_eq!(
1577            importer.page_base("linux-acpi-tables"),
1578            Some(ACPI_TABLES_BASE / HV_PAGE_SIZE)
1579        );
1580        // The SMBIOS anchor lands in the F-segment; the structure table sits
1581        // just above the ACPI tables.
1582        assert_eq!(
1583            importer.page_base("linux-smbios-anchor"),
1584            Some(SMBIOS_FSEGMENT_BASE / HV_PAGE_SIZE)
1585        );
1586        assert_eq!(
1587            importer.page_base("linux-smbios-tables"),
1588            Some(smbios_struct_table_base(acpi.tables.len()) / HV_PAGE_SIZE)
1589        );
1590        // Boot metadata at its fixed low-memory homes.
1591        assert_eq!(
1592            importer.page_base("linux-zeropage"),
1593            Some(ZERO_PAGE_BASE / HV_PAGE_SIZE)
1594        );
1595        assert_eq!(
1596            importer.page_base("linux-commandline"),
1597            Some(CMDLINE_BASE / HV_PAGE_SIZE)
1598        );
1599        assert_eq!(
1600            importer.page_base("linux-pagetables"),
1601            Some(CR3_BASE / HV_PAGE_SIZE)
1602        );
1603    }
1604
1605    #[test]
1606    fn import_config_rejects_oversized_command_line() {
1607        let acpi = AcpiTables {
1608            rsdp: vec![0u8; 0x1000],
1609            tables: vec![0u8; 0x1000],
1610        };
1611        // One byte too long once the NUL terminator is added.
1612        let cmdline = CString::new(vec![b'a'; (CR3_BASE - CMDLINE_BASE) as usize]).unwrap();
1613        let mut importer = RecordingImporter::default();
1614        let err = import_config(
1615            &mut importer,
1616            &test_load_info(),
1617            &cmdline,
1618            &make_layout(256 * MB),
1619            &acpi,
1620            None,
1621            None,
1622        )
1623        .unwrap_err();
1624        assert!(matches!(err, Error::CommandLineTooLong(..)), "got {err:?}");
1625        assert!(importer.pages.is_empty(), "importer used before the check");
1626    }
1627
1628    #[test]
1629    fn import_config_sets_snp_c_bit_in_page_tables() {
1630        const C_BIT: u8 = 51;
1631        let acpi = AcpiTables {
1632            rsdp: vec![0u8; 0x1000],
1633            tables: vec![0u8; 0x1000],
1634        };
1635        let mut importer = RecordingImporter::default();
1636        import_config(
1637            &mut importer,
1638            &test_load_info(),
1639            &CString::new("").unwrap(),
1640            &make_layout(256 * MB),
1641            &acpi,
1642            None,
1643            Some(SnpBootConfig { c_bit: C_BIT }),
1644        )
1645        .unwrap();
1646
1647        let page_tables = importer
1648            .imports
1649            .iter()
1650            .find(|import| import.tag == "linux-pagetables")
1651            .unwrap();
1652        for entry in page_tables.data.chunks_exact(8).map(|entry| {
1653            u64::from_ne_bytes(entry.try_into().expect("page table entry is eight bytes"))
1654        }) {
1655            if entry & 1 != 0 {
1656                assert_ne!(entry & (1 << C_BIT), 0);
1657            }
1658        }
1659    }
1660
1661    #[test]
1662    fn import_config_rejects_empty_acpi_tables() {
1663        // Empty tables would import zero pages; the loader must reject them
1664        // rather than feed page_count == 0 into the importer.
1665        let acpi = AcpiTables {
1666            rsdp: vec![0u8; 0x1000],
1667            tables: Vec::new(),
1668        };
1669        let mut importer = RecordingImporter::default();
1670        let err = import_config(
1671            &mut importer,
1672            &test_load_info(),
1673            &CString::new("").unwrap(),
1674            &make_layout(256 * MB),
1675            &acpi,
1676            None,
1677            None,
1678        )
1679        .unwrap_err();
1680        assert!(matches!(err, Error::EmptyAcpiTables), "got {err:?}");
1681    }
1682
1683    #[test]
1684    fn imports_snp_boot_pages_with_linux_cc_blob() {
1685        let acpi_len = 0x1800;
1686        let smbios_len = 0x100;
1687        let ZeroPageBuildResult {
1688            boot_params,
1689            additional_pages,
1690        } = build_zero_page(
1691            &make_layout(256 * MB),
1692            acpi_len,
1693            smbios_len,
1694            SNP_BOOT_PAGE_COUNT,
1695            &CString::new("").unwrap(),
1696            0,
1697            0,
1698            None,
1699        )
1700        .unwrap();
1701        let allocated_range = additional_pages.unwrap();
1702        let mut importer = RecordingImporter::default();
1703
1704        let cc_setup_data_address = import_snp_boot_pages(&mut importer, allocated_range).unwrap();
1705
1706        assert_eq!(importer.imports.len(), 4);
1707        assert_eq!(
1708            allocated_range.start(),
1709            ACPI_TABLES_BASE
1710                + align_up_to_page_size(acpi_len as u64)
1711                + align_up_to_page_size(smbios_len as u64)
1712        );
1713        assert_eq!(
1714            importer.imports[0].page_base,
1715            allocated_range.start() / HV_PAGE_SIZE
1716        );
1717        assert_eq!(importer.imports[0].page_count, 1);
1718        assert_eq!(importer.imports[0].tag, "linux-snp-secrets");
1719        assert_eq!(
1720            importer.imports[0].acceptance,
1721            BootPageAcceptance::SecretsPage
1722        );
1723        assert_eq!(
1724            importer.imports[1].page_base,
1725            allocated_range.start() / HV_PAGE_SIZE + 1
1726        );
1727        assert_eq!(
1728            importer.imports[1].acceptance,
1729            BootPageAcceptance::CpuidPage
1730        );
1731        let cpuid_page =
1732            crate::cpuid::HV_PSP_CPUID_PAGE::read_from_bytes(&importer.imports[1].data).unwrap();
1733        assert_eq!(
1734            cpuid_page.count as usize,
1735            crate::cpuid::SNP_REQUIRED_CPUID_LEAF_LIST_PARAVISOR.len()
1736        );
1737        for (entry, leaf) in cpuid_page
1738            .cpuid_leaf_info
1739            .iter()
1740            .zip(crate::cpuid::SNP_REQUIRED_CPUID_LEAF_LIST_PARAVISOR)
1741        {
1742            assert_eq!(entry.eax_in, leaf.eax);
1743            assert_eq!(entry.ecx_in, leaf.ecx);
1744            assert_eq!(
1745                entry.xfem_in,
1746                u64::from(leaf.eax == CpuidFunction::ExtendedStateEnumeration.0 && leaf.ecx <= 1)
1747            );
1748            assert_eq!(entry.xss_in, 0);
1749        }
1750
1751        let cc_blob = defs::cc_blob_sev_info::read_from_bytes(&importer.imports[2].data).unwrap();
1752        assert_eq!(cc_blob.magic, defs::CC_BLOB_SEV_INFO_MAGIC);
1753        assert_eq!(cc_blob.version, 0);
1754        assert_eq!(cc_blob.secrets_phys, allocated_range.start());
1755        assert_eq!(cc_blob.secrets_len, HV_PAGE_SIZE as u32);
1756        assert_eq!(cc_blob.cpuid_phys, allocated_range.start() + HV_PAGE_SIZE);
1757        assert_eq!(cc_blob.cpuid_len, HV_PAGE_SIZE as u32);
1758
1759        let cc_setup_data =
1760            defs::cc_setup_data::read_from_bytes(&importer.imports[3].data).unwrap();
1761        assert_eq!(cc_setup_data.header.next, 0);
1762        assert_eq!(cc_setup_data.header.ty, defs::SETUP_CC_BLOB);
1763        assert_eq!(
1764            cc_setup_data.header.len,
1765            (size_of::<defs::cc_setup_data>() - size_of::<defs::setup_data>()) as u32
1766        );
1767        assert_eq!(
1768            cc_setup_data.cc_blob_address,
1769            u32::try_from(allocated_range.start() + 2 * HV_PAGE_SIZE).unwrap()
1770        );
1771        assert_eq!(
1772            importer.vp_context_page,
1773            Some(allocated_range.start() / HV_PAGE_SIZE + 4)
1774        );
1775        assert_eq!(
1776            allocated_range.end(),
1777            cc_setup_data_address + 2 * HV_PAGE_SIZE,
1778        );
1779        assert!(allocated_range.end() <= RSDP_BASE);
1780
1781        let smbios_reserved = &boot_params.e820_map[2];
1782        let acpi_end = ACPI_TABLES_BASE + align_up_to_page_size(acpi_len as u64);
1783        assert_eq!(u64::from(smbios_reserved.addr), acpi_end);
1784        assert_eq!(
1785            u64::from(smbios_reserved.size),
1786            align_up_to_page_size(smbios_len as u64)
1787        );
1788        let additional_reserved = &boot_params.e820_map[3];
1789        assert_eq!(u64::from(additional_reserved.addr), allocated_range.start());
1790        assert_eq!(u64::from(additional_reserved.size), allocated_range.len());
1791
1792        assert!(matches!(
1793            build_zero_page(
1794                &make_layout(256 * MB),
1795                (RSDP_BASE - ACPI_TABLES_BASE) as usize,
1796                0,
1797                SNP_BOOT_PAGE_COUNT,
1798                &CString::new("").unwrap(),
1799                0,
1800                0,
1801                None,
1802            ),
1803            Err(Error::LowTablesTooLarge(..))
1804        ));
1805    }
1806
1807    /// Builds a minimal little-endian x86-64 ELF executable with one `PT_LOAD`
1808    /// program header, and no file contents, for each `(paddr, memsz)` in
1809    /// `load_segments`.
1810    fn test_elf(entrypoint: u64, load_segments: &[(u64, u64)]) -> Cursor<Vec<u8>> {
1811        use object::LittleEndian;
1812        use object::U16;
1813        use object::U32;
1814        use object::U64;
1815        use object::elf;
1816
1817        let header_size = size_of::<elf::FileHeader64<LittleEndian>>();
1818        let header = elf::FileHeader64::<LittleEndian> {
1819            e_ident: elf::Ident {
1820                magic: elf::ELFMAG,
1821                class: elf::ELFCLASS64,
1822                data: elf::ELFDATA2LSB,
1823                version: elf::EV_CURRENT,
1824                os_abi: elf::ELFOSABI_NONE,
1825                abi_version: 0,
1826                padding: [0; 7],
1827            },
1828            e_type: U16::new(LittleEndian, elf::ET_EXEC),
1829            e_machine: U16::new(LittleEndian, elf::EM_X86_64),
1830            e_version: U32::new(LittleEndian, elf::EV_CURRENT.into()),
1831            e_entry: U64::new(LittleEndian, entrypoint),
1832            e_phoff: U64::new(LittleEndian, header_size as u64),
1833            e_shoff: U64::new(LittleEndian, 0),
1834            e_flags: U32::new(LittleEndian, 0),
1835            e_ehsize: U16::new(LittleEndian, header_size as u16),
1836            e_phentsize: U16::new(
1837                LittleEndian,
1838                size_of::<elf::ProgramHeader64<LittleEndian>>() as u16,
1839            ),
1840            e_phnum: U16::new(LittleEndian, load_segments.len().try_into().unwrap()),
1841            e_shentsize: U16::new(
1842                LittleEndian,
1843                size_of::<elf::SectionHeader64<LittleEndian>>() as u16,
1844            ),
1845            e_shnum: U16::new(LittleEndian, 0),
1846            e_shstrndx: U16::new(LittleEndian, 0),
1847        };
1848        let mut image = object::pod::bytes_of(&header).to_vec();
1849        for &(paddr, memsz) in load_segments {
1850            let program_header = elf::ProgramHeader64::<LittleEndian> {
1851                p_type: U32::new(LittleEndian, elf::PT_LOAD),
1852                p_flags: U32::new(LittleEndian, elf::PF_R | elf::PF_X),
1853                p_offset: U64::new(LittleEndian, 0),
1854                p_vaddr: U64::new(LittleEndian, paddr),
1855                p_paddr: U64::new(LittleEndian, paddr),
1856                p_filesz: U64::new(LittleEndian, 0),
1857                p_memsz: U64::new(LittleEndian, memsz),
1858                p_align: U64::new(LittleEndian, HV_PAGE_SIZE),
1859            };
1860            image.extend_from_slice(object::pod::bytes_of(&program_header));
1861        }
1862        Cursor::new(image)
1863    }
1864
1865    #[test]
1866    fn elf_without_load_segments_is_rejected() {
1867        let mut importer = RecordingImporter::default();
1868        let mut kernel_image = test_elf(KERNEL_BASE, &[]);
1869        let error = load_kernel_and_initrd_x64(&mut importer, &mut kernel_image, KERNEL_BASE, None)
1870            .unwrap_err();
1871        assert!(matches!(
1872            error,
1873            Error::ElfLoader(crate::elf::Error::NoLoadableSegments)
1874        ));
1875        assert!(importer.imports.is_empty());
1876    }
1877
1878    #[test]
1879    fn mptable_loader_rejects_elf_without_load_segments() {
1880        let mut importer = RecordingImporter::default();
1881        let mut kernel_image = test_elf(KERNEL_BASE, &[]);
1882        let config = mptable::MpTableConfig {
1883            apic_ids: &[0],
1884            level_triggered_irqs: &[],
1885        };
1886        let error = mptable_boot::load_x86_mptable(
1887            &mut importer,
1888            &mut kernel_image,
1889            None,
1890            &CString::new("").unwrap(),
1891            &make_layout(256 * MB),
1892            &config,
1893            &[],
1894        )
1895        .unwrap_err();
1896
1897        assert!(matches!(
1898            error,
1899            Error::ElfLoader(crate::elf::Error::NoLoadableSegments)
1900        ));
1901        assert!(importer.imports.is_empty());
1902    }
1903
1904    #[test]
1905    fn elf_with_only_empty_load_segment_is_rejected() {
1906        let mut importer = RecordingImporter::default();
1907        let mut kernel_image = test_elf(KERNEL_BASE + 1, &[(KERNEL_BASE + 1, 0)]);
1908        let error = load_kernel_and_initrd_x64(&mut importer, &mut kernel_image, KERNEL_BASE, None)
1909            .unwrap_err();
1910        assert!(matches!(
1911            error,
1912            Error::ElfLoader(crate::elf::Error::NoLoadableSegments)
1913        ));
1914        assert!(importer.imports.is_empty());
1915    }
1916
1917    #[test]
1918    fn elf_entrypoint_outside_load_segments_is_rejected() {
1919        let mut importer = RecordingImporter::default();
1920        let mut kernel_image = test_elf(
1921            KERNEL_BASE + HV_PAGE_SIZE,
1922            &[
1923                (KERNEL_BASE, HV_PAGE_SIZE),
1924                (KERNEL_BASE + 2 * HV_PAGE_SIZE, HV_PAGE_SIZE),
1925            ],
1926        );
1927        let error = load_kernel_and_initrd_x64(&mut importer, &mut kernel_image, KERNEL_BASE, None)
1928            .unwrap_err();
1929        assert!(matches!(
1930            error,
1931            Error::ElfLoader(crate::elf::Error::EntryPointNotInLoadableSegment { .. })
1932        ));
1933        assert!(importer.imports.is_empty());
1934    }
1935
1936    #[test]
1937    fn initrd_after_kernel_alignment_overflow_is_rejected() {
1938        let mut importer = RecordingImporter::default();
1939        let mut initrd = Cursor::new([0]);
1940        let error = import_initrd(
1941            Some(InitrdConfig {
1942                initrd_address: InitrdAddressType::AfterKernel,
1943                initrd: &mut initrd,
1944                size: 1,
1945            }),
1946            u64::MAX - HV_PAGE_SIZE + 1,
1947            &mut importer,
1948        )
1949        .unwrap_err();
1950        assert!(matches!(error, Error::InitrdAddressTooHigh(_)));
1951        assert!(importer.imports.is_empty());
1952    }
1953}