//! QEMU virt ARM64 Image handoff with a bounded, owned BootInfo V1 payload. use core::arch::asm; use core::ptr::{copy_nonoverlapping, read_unaligned, write_bytes}; use r_efi::efi; use crate::{MapSnapshot, OWNED_MAP, serial, serial_hex}; use turkos_bootinfo::{ BOOT_INFO_MAP_CAPACITY, BOOT_INFO_PAGE_BYTES, BootInfoV1, validate_boot_info_pointer, }; const KERNEL_PHYS: u64 = 0x4008_0000; const IMAGE_TEXT_OFFSET: u64 = 0x80000; const MAX_IMAGE_MEMORY_BYTES: u64 = 8 * 1024 * 1024; const MAX_DTB_BYTES: u32 = 1024 * 1024; #[derive(Clone, Copy)] pub struct Handoff { entry: u64, dtb: u64, dtb_bytes: u64, kernel_file_bytes: u64, boot_info_page: u64, memory_map_page: u64, memory_map_bytes: u64, } fn disjoint(a: u64, a_end: u64, b: u64, b_end: u64) -> bool { a_end <= b || b_end <= a } fn u64_le(bytes: &[u8], offset: usize) -> Option { let slice = bytes.get(offset..offset + 8)?; Some(u64::from_le_bytes(slice.try_into().ok()?)) } fn u32_le(bytes: &[u8], offset: usize) -> Option { let slice = bytes.get(offset..offset + 4)?; Some(u32::from_le_bytes(slice.try_into().ok()?)) } fn dtb_from_configuration_table(table: *mut efi::SystemTable) -> Result<(u64, u32), efi::Status> { // SAFETY: the UEFI ABI passes a live SystemTable until ExitBootServices. let (count, entries) = unsafe { ( (*table).number_of_table_entries, (*table).configuration_table, ) }; if count <= 256 && !entries.is_null() { for index in 0..count { // SAFETY: count comes from the firmware table, capped above. let entry = unsafe { &*entries.add(index) }; if entry.vendor_guid != efi::DTB_TABLE_GUID { continue; } if entry.vendor_table.is_null() { return Err(efi::Status::COMPROMISED_DATA); } let ptr = entry.vendor_table.cast::(); // SAFETY: UEFI DTB table GUID designates at least the FDT header. let magic = unsafe { u32::from_be(read_unaligned(ptr.cast::())) }; let bytes = unsafe { u32::from_be(read_unaligned(ptr.add(4).cast::())) }; if magic != 0xd00d_feed || !(40..=MAX_DTB_BYTES).contains(&bytes) { return Err(efi::Status::COMPROMISED_DATA); } serial("TURKOS/UEFI-DTB-SOURCE: CONFIG-TABLE\n"); return Ok((ptr as u64, bytes)); } } // QEMU virt passes the bare-metal DTB at RAM start. This EDK2 build did // not expose EFI_DTB_TABLE_GUID; this is a QEMU-only fallback. let ptr = 0x4000_0000usize as *const u8; let magic = unsafe { u32::from_be(read_unaligned(ptr.cast::())) }; let bytes = unsafe { u32::from_be(read_unaligned(ptr.add(4).cast::())) }; if magic != 0xd00d_feed || !(40..=MAX_DTB_BYTES).contains(&bytes) { return Err(efi::Status::NOT_FOUND); } serial("TURKOS/UEFI-DTB-SOURCE: QEMU-RAM\n"); Ok((ptr as u64, bytes)) } fn clean_and_invalidate_instruction_range(start: u64, bytes: u64) { let end = start + bytes; let mut address = start & !63; while address < end { // SAFETY: these addresses belong to the allocated kernel destination. unsafe { asm!("dc civac, {addr}", addr = in(reg) address, options(nostack, preserves_flags)) }; address += 64; } unsafe { asm!("dsb sy", options(nostack, preserves_flags)) }; address = start & !63; while address < end { unsafe { asm!("ic ivau, {addr}", addr = in(reg) address, options(nostack, preserves_flags)) }; address += 64; } unsafe { asm!("dsb sy", "isb", options(nostack, preserves_flags)) }; } pub fn prepare( table: *mut efi::SystemTable, services: *mut efi::BootServices, image: &[u8], ) -> Result { if u64_le(image, 8) != Some(IMAGE_TEXT_OFFSET) || u32_le(image, 56) != Some(0x644d_5241) { return Err(efi::Status::LOAD_ERROR); } let memory_bytes = u64_le(image, 16).ok_or(efi::Status::LOAD_ERROR)?; if memory_bytes < image.len() as u64 || memory_bytes > MAX_IMAGE_MEMORY_BYTES { return Err(efi::Status::BAD_BUFFER_SIZE); } let (dtb_source, dtb_bytes) = dtb_from_configuration_table(table)?; serial("TURKOS/UEFI-DTB: phys=0x"); serial_hex(dtb_source); serial(" bytes=0x"); serial_hex(u64::from(dtb_bytes)); serial("\n"); if dtb_source < 0x4000_0000 || dtb_source.checked_add(u64::from(dtb_bytes)).is_none() { return Err(efi::Status::COMPROMISED_DATA); } let kernel_end = KERNEL_PHYS .checked_add(memory_bytes) .ok_or(efi::Status::BAD_BUFFER_SIZE)?; let mut dtb = 0u64; let dtb_pages = u64::from(dtb_bytes).div_ceil(4096) as usize; // SAFETY: firmware chooses a non-overlapping LOADER_DATA range before exit. let dtb_status = unsafe { ((*services).allocate_pages)( efi::ALLOCATE_ANY_PAGES, efi::LOADER_DATA, dtb_pages, &mut dtb, ) }; if dtb_status != efi::Status::SUCCESS { return Err(dtb_status); } if dtb < 0x4000_0000 || dtb.checked_add(u64::from(dtb_bytes)).is_none() || (dtb < kernel_end && dtb + u64::from(dtb_bytes) > KERNEL_PHYS) { return Err(efi::Status::COMPROMISED_DATA); } // SAFETY: the FDT header bounded source length and AllocatePages reserved // enough destination bytes. The original QEMU bare-metal DTB may overlap // the fixed Image link address, so this copy must happen first. unsafe { copy_nonoverlapping(dtb_source as *const u8, dtb as *mut u8, dtb_bytes as usize) }; serial("TURKOS/UEFI-DTB-COPY: phys=0x"); serial_hex(dtb); serial(" bytes=0x"); serial_hex(u64::from(dtb_bytes)); serial(" PASS\n"); let pages = memory_bytes.div_ceil(4096) as usize; let mut address = KERNEL_PHYS; // SAFETY: BootServices is valid and AllocateAddress reserves exactly the // linked physical range, refusing firmware or loader-owned overlap. let status = unsafe { ((*services).allocate_pages)(efi::ALLOCATE_ADDRESS, efi::LOADER_DATA, pages, &mut address) }; if status != efi::Status::SUCCESS { return Err(status); } if address != KERNEL_PHYS { return Err(efi::Status::COMPROMISED_DATA); } // SAFETY: the allocation covers declared image memory, which includes the file. unsafe { copy_nonoverlapping(image.as_ptr(), KERNEL_PHYS as *mut u8, image.len()); write_bytes( (KERNEL_PHYS as *mut u8).add(image.len()), 0, memory_bytes as usize - image.len(), ); } clean_and_invalidate_instruction_range(KERNEL_PHYS, memory_bytes); serial("TURKOS/UEFI-KERNEL-STAGE: phys=0x"); serial_hex(KERNEL_PHYS); serial(" file=0x"); serial_hex(image.len() as u64); serial(" memory=0x"); serial_hex(memory_bytes); serial(" dtb=0x"); serial_hex(dtb); serial(" dtb-bytes=0x"); serial_hex(u64::from(dtb_bytes)); serial(" PASS\n"); // Reserve both the V1 header and a fixed-capacity map before asking for // the final map key. No BootServices allocation is allowed after that key. let mut boot_info_page = 0u64; let info_status = unsafe { ((*services).allocate_pages)( efi::ALLOCATE_ANY_PAGES, efi::LOADER_DATA, 1, &mut boot_info_page, ) }; if info_status != efi::Status::SUCCESS { return Err(info_status); } let boot_info_end = boot_info_page .checked_add(BOOT_INFO_PAGE_BYTES) .ok_or(efi::Status::COMPROMISED_DATA)?; let dtb_end = dtb .checked_add(u64::from(dtb_bytes)) .ok_or(efi::Status::COMPROMISED_DATA)?; if boot_info_page < 0x4000_0000 || boot_info_page % 4096 != 0 || validate_boot_info_pointer(boot_info_page).is_err() || !disjoint(boot_info_page, boot_info_end, KERNEL_PHYS, kernel_end) || !disjoint(boot_info_page, boot_info_end, dtb, dtb_end) { return Err(efi::Status::COMPROMISED_DATA); } serial("TURKOS/UEFI-BOOTINFO-PAGE: phys=0x"); serial_hex(boot_info_page); serial(" bytes=0x"); serial_hex(BOOT_INFO_PAGE_BYTES); serial(" RESERVED\n"); let mut memory_map_page = 0u64; let map_status = unsafe { ((*services).allocate_pages)( efi::ALLOCATE_ANY_PAGES, efi::LOADER_DATA, (BOOT_INFO_MAP_CAPACITY / 4096) as usize, &mut memory_map_page, ) }; if map_status != efi::Status::SUCCESS { return Err(map_status); } let map_end = memory_map_page .checked_add(BOOT_INFO_MAP_CAPACITY) .ok_or(efi::Status::COMPROMISED_DATA)?; if memory_map_page < 0x4000_0000 || memory_map_page % 4096 != 0 || !disjoint(memory_map_page, map_end, boot_info_page, boot_info_end) || !disjoint(memory_map_page, map_end, KERNEL_PHYS, kernel_end) || !disjoint(memory_map_page, map_end, dtb, dtb_end) { return Err(efi::Status::COMPROMISED_DATA); } serial("TURKOS/UEFI-BOOTINFO-MAP-PAGE: phys=0x"); serial_hex(memory_map_page); serial(" bytes=0x"); serial_hex(BOOT_INFO_MAP_CAPACITY); serial(" RESERVED\n"); Ok(Handoff { entry: KERNEL_PHYS, dtb, dtb_bytes: u64::from(dtb_bytes), kernel_file_bytes: image.len() as u64, boot_info_page, memory_map_page, memory_map_bytes: 0, }) } /// Runs only after successful ExitBootServices; copies the final owned map /// without allocating or calling firmware, then publishes the V1 header. pub fn finalize(mut handoff: Handoff, map: MapSnapshot) -> Result { if map.bytes == 0 || map.bytes > BOOT_INFO_MAP_CAPACITY as usize { return Err(efi::Status::COMPROMISED_DATA); } let source = core::ptr::addr_of!(OWNED_MAP).cast::(); // SAFETY: prepare reserved the destination; get_owned_map filled the // static source with exactly map.bytes bytes before the successful exit. let source_bytes = unsafe { core::slice::from_raw_parts(source, map.bytes) }; let target_bytes = unsafe { core::slice::from_raw_parts_mut( handoff.memory_map_page as *mut u8, BOOT_INFO_MAP_CAPACITY as usize, ) }; turkos_bootinfo::copy_owned_memory_map(source_bytes, target_bytes, map.descriptor_bytes) .map_err(|_| efi::Status::COMPROMISED_DATA)?; let mut info = BootInfoV1::empty(); info.memory_map_ptr = handoff.memory_map_page; info.memory_map_bytes = map.bytes as u64; info.descriptor_bytes = map.descriptor_bytes as u32; info.descriptor_version = map.descriptor_version; info.kernel_phys_start = handoff.entry; info.kernel_file_bytes = handoff.kernel_file_bytes; info.dtb_phys_addr = handoff.dtb; if info.validate_header().is_err() || info.validate_memory_map_metadata().is_err() { return Err(efi::Status::COMPROMISED_DATA); } // These mutually exclusive test builds corrupt the payload only after the // production header and final map have been validated. They never ship in // the release EFI binary; the kernel must reject each before FreeMap use. #[cfg(feature = "bad-handoff-magic-test")] { info.magic[0] ^= 1; serial("TURKOS/UEFI-BOOTINFO-FAULT: MAGIC\n"); } #[cfg(feature = "bad-handoff-version-test")] { info.version += 1; serial("TURKOS/UEFI-BOOTINFO-FAULT: VERSION\n"); } #[cfg(feature = "bad-handoff-size-test")] { info.struct_bytes -= 8; serial("TURKOS/UEFI-BOOTINFO-FAULT: SIZE\n"); } #[cfg(feature = "bad-handoff-stride-test")] { info.descriptor_bytes = 16; serial("TURKOS/UEFI-BOOTINFO-FAULT: STRIDE\n"); } #[cfg(feature = "bad-handoff-map-length-test")] { info.memory_map_bytes -= 1; serial("TURKOS/UEFI-BOOTINFO-FAULT: MAP-LENGTH\n"); } #[cfg(feature = "bad-handoff-descriptor-test")] { // EFI_MEMORY_DESCRIPTOR.NumberOfPages at byte 24 of the first row. unsafe { write_bytes((handoff.memory_map_page as *mut u8).add(24), 0, 8) }; serial("TURKOS/UEFI-BOOTINFO-FAULT: DESCRIPTOR\n"); } #[cfg(feature = "bad-handoff-range-test")] { info.memory_map_ptr = handoff.boot_info_page; serial("TURKOS/UEFI-BOOTINFO-FAULT: RANGE\n"); } // SAFETY: prepare reserved and aligned this physical page. The loader and // kernel use the same repr(C) V1 layout; caches are cleaned before branch. unsafe { core::ptr::write_volatile(handoff.boot_info_page as *mut BootInfoV1, info) }; handoff.memory_map_bytes = map.bytes as u64; serial("TURKOS/UEFI-BOOTINFO-HANDOFF: phys=0x"); serial_hex(handoff.boot_info_page); serial(" map=0x"); serial_hex(handoff.memory_map_page); serial(" bytes=0x"); serial_hex(handoff.memory_map_bytes); serial(" PASS\n"); Ok(handoff) } fn clean_data_range(start: u64, bytes: u64) { let end = start + bytes; let mut address = start & !63; while address < end { unsafe { asm!("dc civac, {addr}", addr = in(reg) address, options(nostack, preserves_flags)) }; address += 64; } unsafe { asm!("dsb sy", options(nostack, preserves_flags)) }; } /// SAFETY: only after successful ExitBootServices, with the Image at its linked /// physical address and a validated persistent DTB. QEMU virt identity maps the /// executing loader while we turn off firmware translation and caches. pub unsafe fn jump(handoff: Handoff) -> ! { clean_data_range(handoff.dtb, handoff.dtb_bytes); clean_data_range(handoff.memory_map_page, handoff.memory_map_bytes); clean_data_range( handoff.boot_info_page, core::mem::size_of::() as u64, ); unsafe { asm!( "msr daifset, #0xf", "mov x16, x0", "mov x17, x1", "mov x19, x2", "mrs x9, CurrentEL", "cmp x9, #4", "b.eq 2f", "cmp x9, #8", "b.eq 3f", "b 4f", "2:", "mrs x9, sctlr_el1", "bic x9, x9, #1", "bic x9, x9, #4", "msr sctlr_el1, x9", "isb", "b 4f", "3:", "mrs x9, sctlr_el2", "bic x9, x9, #1", "bic x9, x9, #4", "msr sctlr_el2, x9", "isb", "4:", "mov x0, x17", "mov x1, x19", "mov x2, xzr", "mov x3, xzr", "br x16", in("x0") handoff.entry, in("x1") handoff.dtb, in("x2") handoff.boot_info_page, options(noreturn), ) } }