diff --git a/loader/src/args.rs b/loader/src/args.rs index dd3dd8486..2fa9a9416 100644 --- a/loader/src/args.rs +++ b/loader/src/args.rs @@ -8,11 +8,42 @@ macro_rules! make_type { }}; } +#[repr(C)] +/// This is a representation of tag data *on disk*. It can be located at any 4-byte +/// alignment within the argument list. +pub struct Tag { + /// Ascii-printable name, not null-terminated, in little endian format. + pub tag: u32, + + /// CRC16 of the data section, using CCITT polynomial. + pub crc16: u16, + + /// Size of the data section, in 4-byte words. + pub size: u16, +} + +#[repr(C)] +pub struct XargArg { + tag: Tag, + /// Full length of the entire argument structure (not just this argument) + /// reported in units of u32. + arg_size_u32: u32, + version: u32, + ram_start: u32, + ram_size: u32, + ram_name: u32, +} + +/// KernelArguments is a self-extracting structure which handles variable-length fields +/// that only needs a pointer to its start to derive the rest of its structure. #[derive(Clone, Copy)] pub struct KernelArguments { pub base: *const u32, } +/// The arguments iterator is constructed by reading into kernel arguments structure, assuming +/// it is a well-formed structure where the first meta-tag is placed correctly, allowing the +/// extraction of a `size` field. pub struct KernelArgumentsIterator { base: *const u32, size: usize, @@ -27,11 +58,24 @@ impl KernelArguments { } pub fn size(self) -> usize { - let s = unsafe { self.base.add(2).read() * 4 }; - s as usize + // Add a rudimentary check to make sure that KernelArguments are pointed to the correct + // structure, by checking for the right magic number in the first field. + let tag = unsafe { (self.base as *const Tag).as_ref().unwrap() }; + if tag.tag != u32::from_le_bytes(*b"XArg") { + crate::println!("FATAL: Couldn't find XArg magic number on kernel tags."); + panic!(); // nothing we can do to repair this defect. + } + let xarg_tag = unsafe { (self.base as *const XargArg).as_ref().unwrap() }; + xarg_tag.arg_size_u32 as usize * size_of::() } } +/// KernelArgument is a stack-allocated structure that describes a pointer to tagged data. +/// It effectively decompressed the tag name + size field and converts the embedded variable-length +/// data into a slice. +/// +/// It is constructed by referring to the base of the tag structure, and then providing an +/// offset. The base + offset should point to the top of a Tag structure. pub struct KernelArgument { pub name: u32, @@ -44,10 +88,15 @@ pub struct KernelArgument { impl KernelArgument { pub fn new(base: *const u32, offset: u32) -> Self { - let name = unsafe { base.add(offset as usize / 4).read() }; - let size = unsafe { (base.add(offset as usize / 4 + 1) as *const u16).add(1).read() } as u32; - let data = unsafe { core::slice::from_raw_parts(base.add(offset as usize / 4 + 2), size as usize) }; - KernelArgument { name, size: size * 4, data } + let tag = unsafe { (base.add(offset as usize / size_of::()) as *const Tag).as_ref().unwrap() }; + let name = tag.tag; + let size = tag.size as u32; + // adding 1 to the tag yields the address immediately after the tag data. + let data = + unsafe { core::slice::from_raw_parts((tag as *const Tag).add(1) as *const u32, size as usize) }; + // Return the stack-allocated KernelArgument, which embeds a reference to the now base/bounds + // protected data slice. + KernelArgument { name, size: size * size_of::() as u32, data } } } diff --git a/loader/src/main.rs b/loader/src/main.rs index f4eeeaa51..c9753e7f2 100644 --- a/loader/src/main.rs +++ b/loader/src/main.rs @@ -107,6 +107,13 @@ const SDBG: bool = false; // swap debug #[cfg(test)] mod test; +#[global_allocator] +#[cfg(feature = "swap")] +static ALLOCATOR: linked_list_allocator::LockedHeap = linked_list_allocator::LockedHeap::empty(); +// just a small heap, big enough for us to use alloc to simplify argument processing +#[cfg(feature = "swap")] +const HEAP_LEN: usize = 4096; + #[repr(C)] pub struct MemoryRegionExtra { start: u32, @@ -160,29 +167,6 @@ pub unsafe extern "C" fn rust_entry(signed_buffer: *const usize, signature: u32) loop {} }; - #[cfg(feature = "bao1x")] - { - use bao1x_api::signatures::FunctionCode; - // validate using the bao1x signature scheme - match bao1x_hal::sigcheck::validate_image( - bao1x_api::KERNEL_START as *const u32, - bao1x_api::LOADER_START as *const u32, - bao1x_api::LOADER_REVOCATION_OFFSET, - &[ - FunctionCode::Kernel as u32, - FunctionCode::UpdatedKernel as u32, - FunctionCode::Developer as u32, - ], - false, - ) { - Ok(k) => println!("Kernel signature check by key @ {} OK", k), - Err(e) => { - println!("Kernel failed signature check. Dying: {:?}", e); - bao1x_hal::sigcheck::die_no_std(); - } - } - } - #[cfg(all(feature = "vexii-test", not(feature = "verilator-only")))] { // fake the prehash @@ -262,9 +246,6 @@ fn boot_sequence(args: KernelArguments, _signature: u32, fs_prehash: [u8; 64], _ // Store the initial boot config on the stack. We don't know // where in heap this memory will go. #[allow(clippy::cast_ptr_alignment)] // This test only works on 32-bit systems - #[cfg(feature = "platform-tests")] - platform::platform_tests(); - let mut cfg = BootConfig { base_addr: args.base as *const usize, args, ..Default::default() }; #[cfg(feature = "swap")] println!("Size of BootConfig: {:x}", core::mem::size_of::()); @@ -285,10 +266,34 @@ fn boot_sequence(args: KernelArguments, _signature: u32, fs_prehash: [u8; 64], _ println!("No suspend marker found, doing a cold boot!"); #[cfg(feature = "simulation-only")] println!("Configured for simulation. Skipping RAM clear!"); - #[cfg(not(any(feature = "bao1x")))] - // bao1x target clears RAM with assembly routine on boot clear_ram(&mut cfg); phase_1(&mut cfg); + + #[cfg(feature = "bao1x")] + { + // this is the soonest we can run the image validation because we need to + // have the heap setup first. + use bao1x_api::signatures::FunctionCode; + // validate using the bao1x signature scheme + match bao1x_hal::sigcheck::validate_image( + bao1x_api::KERNEL_START as *const u32, + bao1x_api::LOADER_START as *const u32, + bao1x_api::LOADER_REVOCATION_OFFSET, + &[ + FunctionCode::Kernel as u32, + FunctionCode::UpdatedKernel as u32, + FunctionCode::Developer as u32, + ], + false, + ) { + Ok(k) => println!("*** Kernel signature check by key @ {} OK ***", k), + Err(e) => { + println!("Kernel failed signature check. Dying: {:?}", e); + bao1x_hal::sigcheck::die_no_std(); + } + } + } + phase_2(&mut cfg, &fs_prehash); #[cfg(any(feature = "debug-print", feature = "swap"))] if VDBG || SDBG { @@ -647,7 +652,7 @@ fn check_resume(cfg: &mut BootConfig) -> (bool, bool, u32) { /// Clears all of RAM. This is a must for systems that have suspend-to-RAM for security. /// It is configured to be skipped in simulation only, to accelerate the simulation times /// since we can initialize the RAM to zero in simulation. -#[cfg(all(not(feature = "simulation-only"), not(feature = "bao1x")))] +#[cfg(all(not(feature = "simulation-only")))] fn clear_ram(cfg: &mut BootConfig) { // clear RAM on a cold boot. // RAM is persistent and battery-backed. This means secret material could potentially @@ -655,7 +660,7 @@ fn clear_ram(cfg: &mut BootConfig) { // to a cold boot, but it's probably worth it. Note that it doesn't happen on a suspend/resume. let ram: *mut u32 = cfg.sram_start as *mut u32; #[cfg(feature = "swap")] - let clear_limit = ((2 * 4096 + core::mem::size_of::()) + 4095) & !4095; + let clear_limit = GUARD_MEMORY_BYTES; #[cfg(not(feature = "swap"))] let clear_limit = ((4096 + core::mem::size_of::()) + 4095) & !4095; if VDBG { diff --git a/loader/src/phase1.rs b/loader/src/phase1.rs index e1810b207..d1d009efe 100644 --- a/loader/src/phase1.rs +++ b/loader/src/phase1.rs @@ -42,6 +42,20 @@ pub fn phase_1(cfg: &mut BootConfig) { cfg.init_size += GUARD_MEMORY_BYTES; println!("Loader runtime stack should not exceed: {:x}", cfg.get_top() as usize); + // Initialize the allocator with heap memory range + #[cfg(any(feature = "bao1x", feature = "swap"))] + { + crate::println!( + "Setting up heap @ {:x}-{:x}", + cfg.get_top() as usize, + cfg.get_top() as usize + HEAP_LEN + ); + cfg.init_size += HEAP_LEN; + unsafe { + ALLOCATOR.lock().init(cfg.get_top() as *mut u8, HEAP_LEN); + } + } + // The first region is defined as being "main RAM", which will be used // to keep track of allocations. println!("Allocating regions"); diff --git a/loader/src/platform/bao1x/bao1x.rs b/loader/src/platform/bao1x/bao1x.rs index 38279f477..b642b3e63 100644 --- a/loader/src/platform/bao1x/bao1x.rs +++ b/loader/src/platform/bao1x/bao1x.rs @@ -5,9 +5,6 @@ use bao1x_hal::iox::Iox; use bao1x_hal::udma; use utralib::generated::*; -#[global_allocator] -static ALLOCATOR: linked_list_allocator::LockedHeap = linked_list_allocator::LockedHeap::empty(); - // Notes about the reset vector location // This can be set using fuses in the IFR (also called 'info') region // The offset is an 8-bit value, which is shifted into a final location @@ -29,10 +26,6 @@ pub const FLASH_BASE: usize = utralib::generated::HW_RERAM_MEM; // location of kernel, as offset from the base of RRAM. pub const KERNEL_OFFSET: usize = bao1x_api::offsets::KERNEL_START - utralib::generated::HW_RERAM_MEM; -const DATA_SIZE_BYTES: usize = 0x6000; -pub const HEAP_START: usize = RAM_BASE + DATA_SIZE_BYTES; -pub const HEAP_LEN: usize = 1024 * 256; - #[allow(dead_code)] pub fn delay(quantum: usize) { use utralib::{CSR, utra}; @@ -138,23 +131,12 @@ pub fn early_init_hw() -> u32 { glbl_csr.wo(utra::sce_glbsfr::SFR_FFEN, 0x30); glbl_csr.wo(utra::sce_glbsfr::SFR_FFCLR, 0xff05); - setup_alloc(); - // this should go to the serial console, because boot1 setup the console for us crate::println!("\n\r~~ Xous Loader ~~\n\r"); perclk } -pub fn setup_alloc() { - // Initialize the allocator with heap memory range - crate::println!("Setting up heap @ {:x}-{:x}", HEAP_START, HEAP_START + HEAP_LEN); - crate::println!("Stack @ {:x}-{:x}", HEAP_START + HEAP_LEN, RAM_BASE + RAM_SIZE); - unsafe { - ALLOCATOR.lock().init(HEAP_START as *mut u8, HEAP_LEN); - } -} - // returns the actual per_clk #[cfg(not(feature = "simulation-only"))] #[allow(dead_code)]