λ

lumine

UEFI x86_64 bootloader for linux kernel images

settings

src/luefi.zig

1943 bytes raw

//! lumine uefi abstractions
const std = @import("std");
const uefi = std.os.uefi;

const Path = @import("./Config.zig").Path;

pub fn posixPathToUefi(path: []u16) void {
    for (0..path.len) |i|
        switch (path[i]) {
            '/' => path[i] = '\\',
            else => {},
        };
}

pub fn fileOpenBoot(path: []const u8) !*uefi.protocol.File {
    const boot_svc = uefi.system_table.boot_services.?;
    const allocator = uefi.pool_allocator;

    const loaded_img = try boot_svc.openProtocol(uefi.protocol.LoadedImage, uefi.handle, .{
        .get_protocol = .{ .agent = uefi.handle },
    }) orelse unreachable;

    const device_handle = loaded_img.device_handle orelse unreachable;
    const simple_fs = try boot_svc.openProtocol(uefi.protocol.SimpleFileSystem, device_handle, .{
        .get_protocol = .{ .agent = uefi.handle },
    }) orelse unreachable;

    const root_fs = try simple_fs.openVolume();
    defer root_fs.close() catch unreachable;

    // is allocating a good idea?
    const utf16_path = try std.unicode.utf8ToUtf16LeAllocZ(allocator, path);
    defer allocator.free(utf16_path);

    posixPathToUefi(utf16_path);

    return root_fs.open(utf16_path, .read, .{});
}

pub fn fileOpen(path: Path) !*uefi.protocol.File {
    return switch (path) {
        .boot => |boot_path| fileOpenBoot(boot_path),
    };
}

pub fn fileSize(file: *uefi.protocol.File) !usize {
    const allocator = uefi.pool_allocator;

    const info_size = try file.getInfoSize(.file);
    const info_buf = try allocator.alignedAlloc(u8, .@"8", info_size);
    defer allocator.free(info_buf);

    const info = try file.getInfo(.file, info_buf);
    return info.file_size;
}

pub fn fileReadSlice(file: *uefi.protocol.File, slice: []u8) !void {
    var read: usize = 0;

    while (read < slice.len) {
        const chunk = try file.read(slice[read..]);
        if (chunk == 0) return error.ReadShort;
        read += chunk;
    }
}