garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /boot/src/efi.rs

raw

//! As much of UEFI (Unified Extensible Firmware Interface 2.10) as the
//! loader calls: the system table, the boot services it uses, the console,
//! files on the volume it was started from, the screen, and the
//! configuration tables (ACPI's, the device tree).

use core::ffi::c_void;

pub type Handle = *mut c_void;
pub type Status = usize;
pub const SUCCESS: Status = 0;

#[repr(C)]
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Guid(pub u32, pub u16, pub u16, pub [u8; 8]);

pub const LOADED_IMAGE: Guid = Guid(
    0x5b1b31a1,
    0x9562,
    0x11d2,
    [0x8e, 0x3f, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b],
);
pub const SIMPLE_FILE_SYSTEM: Guid = Guid(
    0x964e5b22,
    0x6459,
    0x11d2,
    [0x8e, 0x39, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b],
);
pub const GRAPHICS_OUTPUT: Guid = Guid(
    0x9042a9de,
    0x23dc,
    0x4a38,
    [0x96, 0xfb, 0x7a, 0xde, 0xd0, 0x80, 0x51, 0x6a],
);
pub const DEVICE_TREE: Guid = Guid(
    0xb1b621d5,
    0xf19c,
    0x41a5,
    [0x83, 0x0b, 0xd9, 0x15, 0x2c, 0x69, 0xaa, 0xe0],
);
pub const ACPI_20: Guid = Guid(
    0x8868e871,
    0xe4f1,
    0x11d3,
    [0xbc, 0x22, 0x00, 0x80, 0xc7, 0x3c, 0x88, 0x81],
);
pub const ACPI_10: Guid = Guid(
    0xeb9d2d30,
    0x2d88,
    0x11d3,
    [0x9a, 0x16, 0x00, 0x90, 0x27, 0x3f, 0xc1, 0x4d],
);

#[repr(C)]
pub struct TableHeader {
    pub signature: u64,
    pub revision: u32,
    pub header_size: u32,
    pub crc32: u32,
    pub reserved: u32,
}

#[repr(C)]
pub struct SystemTable {
    pub header: TableHeader,
    pub firmware_vendor: *const u16,
    pub firmware_revision: u32,
    pub console_in_handle: Handle,
    pub console_in: *mut c_void,
    pub console_out_handle: Handle,
    pub console_out: *mut TextOutput,
    pub standard_error_handle: Handle,
    pub standard_error: *mut TextOutput,
    pub runtime: *mut c_void,
    pub boot: *mut BootServices,
    pub entries: usize,
    pub configuration: *const ConfigurationTable,
}

#[repr(C)]
pub struct ConfigurationTable {
    pub guid: Guid,
    pub table: *mut c_void,
}

#[repr(C)]
pub struct TextOutput {
    pub reset: extern "efiapi" fn(*mut TextOutput, bool) -> Status,
    pub output_string: extern "efiapi" fn(*mut TextOutput, *const u16) -> Status,
}

type Unused = usize;

#[repr(C)]
pub struct BootServices {
    pub header: TableHeader,
    raise_tpl: Unused,
    restore_tpl: Unused,
    pub allocate_pages: extern "efiapi" fn(u32, u32, usize, *mut u64) -> Status,
    pub free_pages: extern "efiapi" fn(u64, usize) -> Status,
    pub get_memory_map: extern "efiapi" fn(*mut usize, *mut u8, *mut usize, *mut usize, *mut u32) -> Status,
    allocate_pool: Unused,
    free_pool: Unused,
    // CreateEvent to UninstallProtocolInterface.
    events_and_protocols: [Unused; 9],
    pub handle_protocol: extern "efiapi" fn(Handle, *const Guid, *mut *mut c_void) -> Status,
    // Reserved to UnloadImage.
    images: [Unused; 9],
    pub exit_boot_services: extern "efiapi" fn(Handle, usize) -> Status,
    get_next_monotonic_count: Unused,
    stall: Unused,
    pub set_watchdog_timer: extern "efiapi" fn(usize, u64, usize, *const u16) -> Status,
    // ConnectController to LocateHandleBuffer.
    drivers: [Unused; 7],
    pub locate_protocol: extern "efiapi" fn(*const Guid, *mut c_void, *mut *mut c_void) -> Status,
}

pub const ALLOCATE_ANY: u32 = 0;
pub const ALLOCATE_BELOW: u32 = 1;
pub const LOADER_DATA: u32 = 2;

/// What a memory map's descriptor says, by type.
pub mod memory {
    pub const LOADER_CODE: u32 = 1;
    pub const LOADER_DATA: u32 = 2;
    pub const BOOT_SERVICES_CODE: u32 = 3;
    pub const BOOT_SERVICES_DATA: u32 = 4;
    pub const CONVENTIONAL: u32 = 7;
    pub const UNUSABLE: u32 = 8;
    pub const ACPI_RECLAIM: u32 = 9;
    pub const ACPI_NVS: u32 = 10;
}

#[repr(C)]
pub struct LoadedImage {
    pub revision: u32,
    pub parent: Handle,
    pub system_table: *mut SystemTable,
    pub device: Handle,
    pub file_path: *mut c_void,
    reserved: *mut c_void,
    pub load_options_size: u32,
    pub load_options: *mut c_void,
    pub image_base: *mut c_void,
    pub image_size: u64,
}

#[repr(C)]
pub struct SimpleFileSystem {
    pub revision: u64,
    pub open_volume: extern "efiapi" fn(*mut SimpleFileSystem, *mut *mut File) -> Status,
}

#[repr(C)]
pub struct File {
    pub revision: u64,
    pub open: extern "efiapi" fn(*mut File, *mut *mut File, *const u16, u64, u64) -> Status,
    pub close: extern "efiapi" fn(*mut File) -> Status,
    delete: Unused,
    pub read: extern "efiapi" fn(*mut File, *mut usize, *mut u8) -> Status,
    write: Unused,
    pub get_position: extern "efiapi" fn(*mut File, *mut u64) -> Status,
    pub set_position: extern "efiapi" fn(*mut File, u64) -> Status,
}

pub const FILE_READ: u64 = 1;

#[repr(C)]
pub struct GraphicsOutput {
    pub query_mode: extern "efiapi" fn(*mut GraphicsOutput, u32, *mut usize, *mut *const GraphicsInfo) -> Status,
    pub set_mode: extern "efiapi" fn(*mut GraphicsOutput, u32) -> Status,
    blt: Unused,
    pub mode: *const GraphicsMode,
}

#[repr(C)]
pub struct GraphicsMode {
    pub max_mode: u32,
    pub mode: u32,
    pub info: *const GraphicsInfo,
    pub size_of_info: usize,
    pub framebuffer: u64,
    pub framebuffer_size: usize,
}

#[repr(C)]
pub struct GraphicsInfo {
    pub version: u32,
    pub width: u32,
    pub height: u32,
    /// 0: red, green, blue, reserved bytes; 1: blue, green, red; 2: masks;
    /// 3: no framebuffer, only copies.
    pub pixel_format: u32,
    pub masks: [u32; 4],
    pub pixels_per_line: u32,
}

/// The firmware's services while the loader runs, and what it was
/// started from.
pub struct Firmware {
    pub image: Handle,
    pub system: *mut SystemTable,
}

impl Firmware {
    pub fn boot(&self) -> &BootServices {
        // SAFETY: the system table the firmware passed, and its boot
        // services, valid until they are left.
        unsafe { &*(*self.system).boot }
    }

    /// Writes `text` on the firmware's console (the screen, and the serial
    /// port where there is one).
    pub fn print(&self, text: &str) {
        let mut buffer = [0u16; 256];
        let mut n = 0;
        for c in text.chars() {
            if n + 3 >= buffer.len() {
                break;
            }
            if c == '\n' {
                buffer[n] = u16::from(b'\r');
                n += 1;
            }
            buffer[n] = if (c as u32) < 0x10000 {
                c as u16
            } else {
                u16::from(b'?')
            };
            n += 1;
        }
        buffer[n] = 0;
        // SAFETY: the console the system table names, and a terminated string.
        unsafe {
            let out = (*self.system).console_out;
            if !out.is_null() {
                ((*out).output_string)(out, buffer.as_ptr());
            }
        }
    }

    /// `pages` pages of loader data, below `below` when given.
    pub fn allocate(&self, pages: usize, below: Option<u64>) -> Option<u64> {
        let mut address = below.unwrap_or(0);
        let kind = if below.is_some() {
            ALLOCATE_BELOW
        } else {
            ALLOCATE_ANY
        };
        ((self.boot().allocate_pages)(kind, LOADER_DATA, pages, &mut address) == SUCCESS).then_some(address)
    }

    pub fn free(&self, address: u64, pages: usize) {
        (self.boot().free_pages)(address, pages);
    }

    /// The configuration table `guid` names, if the firmware has one.
    pub fn configuration(&self, guid: Guid) -> Option<*mut c_void> {
        // SAFETY: the system table's array of `entries` tables.
        unsafe {
            let s = &*self.system;
            (0..s.entries)
                .map(|i| &*s.configuration.add(i))
                .find(|t| t.guid == guid)
                .map(|t| t.table)
        }
    }

    pub fn protocol<T>(&self, handle: Handle, guid: Guid) -> Option<*mut T> {
        let mut out = core::ptr::null_mut();
        ((self.boot().handle_protocol)(handle, &guid, &mut out) == SUCCESS && !out.is_null())
            .then_some(out.cast())
    }

    pub fn locate<T>(&self, guid: Guid) -> Option<*mut T> {
        let mut out = core::ptr::null_mut();
        ((self.boot().locate_protocol)(&guid, core::ptr::null_mut(), &mut out) == SUCCESS && !out.is_null())
            .then_some(out.cast())
    }

    /// Reads the file at `path` (`\PINNACLE\KERNEL`) on the volume this
    /// loader was started from, into pages of its own (below `below` when
    /// given): their address and the file's size.
    pub fn read_file(&self, path: &str, below: Option<u64>) -> Option<(u64, usize)> {
        let loaded: *mut LoadedImage = self.protocol(self.image, LOADED_IMAGE)?;
        // SAFETY: the protocols the firmware answered with, used as UEFI
        // defines them.
        unsafe {
            let fs: *mut SimpleFileSystem = self.protocol((*loaded).device, SIMPLE_FILE_SYSTEM)?;
            let mut root = core::ptr::null_mut();
            if ((*fs).open_volume)(fs, &mut root) != SUCCESS {
                return None;
            }
            let mut name = [0u16; 128];
            for (n, c) in name.iter_mut().zip(path.encode_utf16()) {
                *n = c;
            }
            name[path.len().min(127)] = 0;
            let mut file = core::ptr::null_mut();
            let opened = ((*root).open)(root, &mut file, name.as_ptr(), FILE_READ, 0) == SUCCESS;
            ((*root).close)(root);
            if !opened {
                return None;
            }
            let mut size = 0u64;
            ((*file).set_position)(file, u64::MAX);
            ((*file).get_position)(file, &mut size);
            ((*file).set_position)(file, 0);
            let pages = (size as usize).div_ceil(4096).max(1);
            let Some(at) = self.allocate(pages, below) else {
                ((*file).close)(file);
                return None;
            };
            let mut done = 0usize;
            while done < size as usize {
                let mut n = (size as usize - done).min(16 << 20);
                if ((*file).read)(file, &mut n, (at as usize + done) as *mut u8) != SUCCESS || n == 0 {
                    break;
                }
                done += n;
            }
            ((*file).close)(file);
            (done == size as usize).then_some((at, done))
        }
    }

    /// The memory map, into `buffer`: its length, the key that leaving the
    /// boot services needs, and each descriptor's size.
    pub fn memory_map(&self, buffer: &mut [u8]) -> Option<(usize, usize, usize)> {
        let (mut size, mut key, mut descriptor, mut version) = (buffer.len(), 0, 0, 0);
        ((self.boot().get_memory_map)(
            &mut size,
            buffer.as_mut_ptr(),
            &mut key,
            &mut descriptor,
            &mut version,
        ) == SUCCESS)
            .then_some((size, key, descriptor))
    }

    /// Leaves the boot services: from now on the firmware does nothing.
    pub fn exit(&self, key: usize) -> bool {
        (self.boot().exit_boot_services)(self.image, key) == SUCCESS
    }
}