Unnamed: 0
int64
0
0
repo_id
stringlengths
5
186
file_path
stringlengths
15
223
content
stringlengths
1
32.8M
0
repos
repos/georgios/README.md
# Georgios ![Screenshot of text mode](misc/screenshot1.png) Georgios (Greek version of the name George, said like *GORE-GEE-OS*) is an operating system I'm making for fun which currently targets i386/IA-32. The purpose of this project is to serve as a learning experience. Work in progress graphics mode: https://user-images.githubusercontent.com/5941194/180702578-91270793-c91c-4f24-b7e1-f86bc2b48c53.mp4 ## Features ### Working on at least some minimal level - Kernel console that supports UTF-8 (specifically the subset needed for [Code page 437](https://en.wikipedia.org/wiki/Code_page_437) subset) and some basic ANSI escape codes - Support for multiple mounted filesystems: - Ext2 accessed using an ATA Driver (read only) - In-memory filesystem mounted at boot (read/write) - Basic preemptive multitasking between processes that can be loaded from ELF files - ACPI shutdown using [ACPICA](https://www.acpica.org/) ### Started on, but not really working yet - A graphics mode using VESA BIOS Extensions (VBE) - This will use [libx86emu](https://github.com/wfeldt/libx86emu) to invoke the BIOS code required to switch to VBE graphics modes. This doesn't really work yet though. - This can be bypassed with `make multiboot_vbe=true`, which has GRUB set a fixed VBE graphics mode. This is how the demo above was ran. This is not the default for a number of reasons: - The major reason is the graphics are slow. This can be seen in the demo, especially when the Apollo earthrise picture takes a moment to get drawn on the screen. - It's a fixed graphics mode when the kernel starts and so nothing gets printed to the screen until the graphical console is ready. So an error before this wouldn't get printed, which is a problem when running on real hardware. - The graphical console is mostly done but missing things like the cursor and text rendering is a bit off. - USB 2.0 stack - Porting real applications written in Zig and C - The applications currently written in Zig are "real" as in they are compiled and ran separately from the kernel, are running in x86 ring3, and can't take the whole system down (for the most part). The issue is they are compiled using the freestanding target. To be able to use a Zig or C hello world program without any modification, the standard libraries would have to be ported and toolchains would have to be modified to target Georgios properly. - Freeing the OS from the need of a boot CD - PS/2 Mouse support - Can be tried out by building with `make mouse=true` and running `test-mouse`. This isn't enabled by default becuase currently the keyboard and mouse cross talk when being used at the same time. ## Building Building Georgios requires a Unix-like environment with: - [Zig](https://ziglang.org/) 0.9.1 - Python 3 - [Bridle](https://github.com/iguessthislldo/bridle) - Is a submodule, but it needs to be installed using `pip install --user scripts/codegen/bridle`. - GRUB2 - Requires i686 Support (`grub-pc-bin` package on Ubuntu) - xorriso (`xorriso` package on Ubuntu) Georgios can be built as a bootable ISO (called `georgios.iso`) by running `make`. If installed, QEMU and Bochs can be run by running `make qemu` or `make bochs` respectively. On Ubuntu, Bochs requires `apt-get install bochs bochsbios bochs-sdl bochs-x vgabios`. For the moment it assumes the existence of an IDE disk with certain files on it. ## Resources Used - [OSDev Wiki](http://wiki.osdev.org/) - Very popular, fairly large set of resources in one place, but rough or just plain unhelpful in many places. - [The little book about OS development](https://littleosbook.github.io/) - Polished, but limited intro into x86 OS development. Provided me with the initial start. - [Intel x86 Software Development Manuals](https://software.intel.com/en-us/articles/intel-sdm) - [xv6](https://github.com/mit-pdos/xv6-public) - [The Design and Implementation of the 4.4 BSD Operating System](https://www.amazon.com/Implementation-Operating-paperback-Addison-wesley-Systems/dp/0132317923) - [FYSOS: Media Storage Devices](https://www.amazon.com/dp/1514111888/) - [UNIX Internals: The New Frontiers](https://www.amazon.com/UNIX-Internals-Frontiers-Uresh-Vahalia/dp/0131019082)
0
repos
repos/georgios/build.zig
const std = @import("std"); const FileSource = std.build.FileSource; const builtin = @import("builtin"); const utils = @import("libs/utils/utils.zig"); const t_path = "tmp/"; const k_path = "kernel/"; const p_path = k_path ++ "platform/"; const root_path = t_path ++ "root/"; const boot_path = root_path ++ "boot/"; const bin_path = root_path ++ "bin/"; const utils_pkg = std.build.Pkg{ .name = "utils", .path = .{.path = "libs/utils/utils.zig"}, }; const georgios_pkg = std.build.Pkg{ .name = "georgios", .path = .{.path = "libs/georgios/georgios.zig"}, .dependencies = &[_]std.build.Pkg { utils_pkg, }, }; const tinyishlisp_pkg = std.build.Pkg{ .name = "TinyishLisp", .path = .{.path = "libs/tinyishlisp/TinyishLisp.zig"}, .dependencies = &[_]std.build.Pkg { utils_pkg, }, }; var b: *std.build.Builder = undefined; var target: std.zig.CrossTarget = undefined; var alloc: std.mem.Allocator = undefined; var kernel: *std.build.LibExeObjStep = undefined; var test_step: *std.build.Step = undefined; const program_link_script = FileSource{.path = "programs/linking.ld"}; fn format(comptime fmt: []const u8, args: anytype) []u8 { return std.fmt.allocPrint(alloc, fmt, args) catch unreachable; } fn add_tests(source: []const u8) void { const tests = b.addTest(source); tests.addPackage(utils_pkg); tests.addPackage(georgios_pkg); test_step.dependOn(&tests.step); } pub fn build(builder: *std.build.Builder) void { b = builder; var arena_alloc = std.heap.ArenaAllocator.init(std.heap.page_allocator); alloc = arena_alloc.allocator(); const multiboot_vbe = b.option(bool, "multiboot_vbe", \\Ask the bootloader to switch to a graphics mode for us. ) orelse false; // TODO: Change default to true when Georgios can properly switch to VBE // itself. const vbe = b.option(bool, "vbe", \\Use VBE Graphics if possible. ) orelse multiboot_vbe; const debug_log = b.option(bool, "debug_log", \\Print debug information by default ) orelse true; const wait_for_anykey = b.option(bool, "wait_for_anykey", \\Wait for key press at important events ) orelse false; const direct_disk = b.option(bool, "direct_disk", \\Do not cache disk operations, use disk directly. ) orelse false; const run_rc = b.option(bool, "run_rc", \\Run /etc/rc on start ) orelse true; const halt_when_done = b.option(bool, "halt_when_done", \\Halt instead of shutting down. ) orelse false; // TODO: Change default to true when mouse and keyboard don't conflict. const mouse = b.option(bool, "mouse", \\Enable Mouse Support ) orelse false; target = b.standardTargetOptions(.{ .default_target = std.zig.CrossTarget.parse(.{ .arch_os_abi = "i386-freestanding-gnu", .cpu_features = "pentiumpro" // TODO: This is to forbid SSE code. See SSE init code in // kernel_start_x86_32.zig for details. }) catch @panic("Failed Making Default Target"), }); const platform = switch (target.cpu_arch.?) { .i386 => "x86_32", else => { std.debug.print("Unsupported Platform: {s}\n", .{@tagName(target.cpu_arch.?)}); @panic("Unsupported Platform"); }, }; // Set install prefix to root // TODO: Might break in the future? b.resolveInstallPrefix(root_path, .{}); // Tests test_step = b.step("test", "Run Tests"); add_tests("libs/utils/test.zig"); add_tests("libs/georgios/test.zig"); add_tests("libs/tinyishlisp/test.zig"); add_tests("kernel/test.zig"); // Kernel const root_file = format("{s}kernel_start_{s}.zig", .{k_path, platform}); kernel = b.addExecutable("kernel.elf", root_file); kernel.override_dest_dir = std.build.InstallDir{.custom = "boot"}; kernel.setLinkerScriptPath(std.build.FileSource.relative(p_path ++ "linking.ld")); kernel.setTarget(target); const kernel_options = b.addOptions(); kernel_options.addOption(bool, "multiboot_vbe", multiboot_vbe); kernel_options.addOption(bool, "vbe", vbe); kernel_options.addOption(bool, "debug_log", debug_log); kernel_options.addOption(bool, "wait_for_anykey", wait_for_anykey); kernel_options.addOption(bool, "direct_disk", direct_disk); kernel_options.addOption(bool, "run_rc", run_rc); kernel_options.addOption(bool, "halt_when_done", halt_when_done); kernel_options.addOption(bool, "mouse", mouse); kernel_options.addOption(bool, "is_kernel", true); kernel.addOptions("build_options", kernel_options); // Packages kernel.addPackage(utils_pkg); kernel.addPackage(georgios_pkg); // System Calls var generate_system_calls_step = b.addSystemCommand(&[_][]const u8{ "scripts/codegen/generate_system_calls.py" }); kernel.step.dependOn(&generate_system_calls_step.step); // IDL Files const idl_files = [_][]const u8 { "libs/georgios/fs.idl", }; for (idl_files) |idl_file| { const step = b.addSystemCommand(&[_][]const u8{"scripts/codegen/genif.py", idl_file}); kernel.step.dependOn(&step.step); } // bios_int/libx86emu build_bios_int(); // ACPICA build_acpica(); kernel.install(); // Generate Font generate_builtin_font("kernel/builtin_font.bdf") catch @panic("generate_builtin_font failed"); // Programs var programs_dir = std.fs.cwd().openDir("programs", .{.iterate = true}) catch unreachable; var programs_dir_it = programs_dir.iterate(); while (programs_dir_it.next() catch unreachable) |entry| { if (entry.kind == .Directory) { build_program(entry.name); } } } const disable_ubsan = "-fsanitize-blacklist=misc/clang-sanitize-blacklist.txt"; fn build_bios_int() void { var bios_int = b.addObject("bios_int", null); bios_int.setTarget(target); const bios_int_path = p_path ++ "bios_int/"; const libx86emu_path = bios_int_path ++ "libx86emu/"; const pub_inc = bios_int_path ++ "public_include/"; bios_int.addIncludeDir(libx86emu_path ++ "include/"); bios_int.addIncludeDir(bios_int_path ++ "private_include/"); bios_int.addIncludeDir(pub_inc); const sources = [_][]const u8 { libx86emu_path ++ "api.c", libx86emu_path ++ "decode.c", libx86emu_path ++ "mem.c", libx86emu_path ++ "ops2.c", libx86emu_path ++ "ops.c", libx86emu_path ++ "prim_ops.c", bios_int_path ++ "bios_int.c", }; for (sources) |source| { bios_int.addCSourceFile(source, &[_][]const u8{disable_ubsan}); } kernel.addObject(bios_int); kernel.addIncludeDir(pub_inc); } fn build_acpica() void { var acpica = b.addObject("acpica", null); acpica.setTarget(target); const components = [_][]const u8 { "dispatcher", "events", "executer", "hardware", "namespace", "parser", "resources", "tables", "utilities", }; const acpica_path = p_path ++ "acpica/"; const source_path = acpica_path ++ "acpica/source/"; // Configure Source var configure_step = b.addSystemCommand(&[_][]const u8{ acpica_path ++ "prepare_source.py", acpica_path}); acpica.step.dependOn(&configure_step.step); // Includes for ([_]*std.build.LibExeObjStep{kernel, acpica}) |obj| { obj.addIncludeDir(acpica_path ++ "include"); obj.addIncludeDir(source_path ++ "include"); obj.addIncludeDir(source_path ++ "include/platform"); } // Add Sources for (components) |component| { const component_path = std.fs.path.join(alloc, &[_][]const u8{source_path, "components", component}) catch unreachable; var component_dir = std.fs.cwd().openDir(component_path, .{.iterate = true}) catch unreachable; defer component_dir.close(); var walker = component_dir.walk(alloc) catch unreachable; while (walker.next() catch unreachable) |i| { const path = i.path; if (std.mem.endsWith(u8, path, ".c") and !std.mem.endsWith(u8, path, "dump.c")) { const full_path = std.fs.path.join(alloc, &[_][]const u8{component_path, path}) catch unreachable; // std.debug.print("acpica source: {s}\n", .{full_path}); acpica.addCSourceFile(b.dupe(full_path), &[_][]const u8{disable_ubsan}); } } } kernel.addObject(acpica); // var crt0 = b.addObject("crt0", "libs/georgios/georgios.zig"); // crt0.addBuildOption(bool, "is_crt", true); // crt0.override_dest_dir = std.build.InstallDir{.Custom = "lib"}; // crt0.setTarget(target); // crt0.addPackage(utils_pkg); // crt0.install(); } fn build_program(name: []const u8) void { const elf = format("{s}.elf", .{name}); const zig = format("programs/{s}/{s}.zig", .{name, name}); const prog = b.addExecutable(elf, zig); prog.setLinkerScriptPath(program_link_script); prog.setTarget(target); prog.addPackage(georgios_pkg); prog.addPackage(tinyishlisp_pkg); prog.install(); } fn build_zig_program(name: []const u8) void { const elf = format("{s}.elf", .{name}); const zig = format("programs/{s}/{s}.zig", .{name, name}); const prog = b.addExecutable(elf, zig); prog.setLinkerScriptPath(program_link_script); prog.setTarget( std.zig.CrossTarget.parse(.{ .arch_os_abi = "i386-georgios-gnu", .cpu_features = "pentiumpro" }) catch @panic("Failed Making Default Target") ); prog.install(); } // fn add_libc(what: *std.build.LibExeObjStep) void { // what.addLibPath("/data/development/os/newlib/newlib/i386-pc-georgios/newlib"); // what.addSystemIncludeDir("/data/development/os/newlib/newlib/newlib/libc/include"); // what.linkSystemLibraryName("c"); // } fn build_c_program(name: []const u8) void { const elf = format("{s}.elf", .{name}); const c = format("programs/{s}/{s}.c", .{name, name}); const prog = b.addExecutable(elf, null); prog.addCSourceFile(c, &[_][]const u8{"--libc /data/development/os/georgios/newlib"}); // add_libc(prog); prog.setLinkerScriptPath(program_link_script); prog.setTarget( std.zig.CrossTarget.parse(.{ .arch_os_abi = "i386-georgios-gnu", .cpu_features = "pentiumpro" }) catch @panic("Failed Making Default Target") ); prog.install(); } fn generate_builtin_font(bdf_path: []const u8) !void { const dir: std.fs.Dir = std.fs.cwd(); // For reading the BDF File const bdf_file = try dir.openFile(bdf_path, .{.read = true}); defer bdf_file.close(); const reader = bdf_file.reader(); var buffer: [512]u8 = undefined; var got: usize = 1; // For parsing the BDF File var chunk: []const u8 = buffer[0..0]; var chunk_pos: usize = 0; var parser = utils.Bdf.Parser{}; // For writing the generated font file const font_file = try dir.createFile("kernel/builtin_font_data.zig", .{}); defer font_file.close(); const writer = font_file.writer(); var glyphs: []utils.Bdf.Glyph = undefined; var glyph_count: usize = 0; while (true) { const result = try parser.feed_input(chunk, &chunk_pos); if (result.done) break; if (result.glyph) |glyph| { glyphs[glyph_count] = glyph; glyph_count += 1; } if (result.need_more_input) { got = try reader.read(buffer[0..]); chunk = buffer[0..got]; chunk_pos = 0; } if (result.need_buffer) |buffer_size| { glyphs = try alloc.alloc(utils.Bdf.Glyph, parser.font.glyph_count); parser.buffer = try alloc.alloc(u8, buffer_size); } } try writer.print( \\// THIS CAN NOT BE EDITED: This is generated by build.zig \\const utils = @import("utils"); \\ \\const BitmapFont = @import("BitmapFont.zig"); \\ \\pub const bdf = utils.Bdf{{ \\ .bounds = .{{.size = .{{.x = {}, .y = {}}}}}, \\ .glyph_count = {}, \\ .default_codepoint = {}, \\}}; \\ \\pub const glyph_indices = [_]BitmapFont.GlyphIndex{{ \\ , .{ parser.font.bounds.size.x, parser.font.bounds.size.y, parser.font.glyph_count, parser.font.default_codepoint, }); for (glyphs) |glyph, n| { try writer.print(" .{{.codepoint = {}, .index = {}}},\n", .{glyph.codepoint, n}); } try writer.print( \\}}; \\ \\pub const bitmaps = [_]u8{{ \\ , .{}); var newline: bool = undefined; for (parser.buffer.?) |elem, i| { newline = false; if (i % 8 == 0) { try writer.print(" ", .{}); } else { try writer.print(" ", .{}); } try writer.print("0x{x:0>2},", .{elem}); if (i % 8 == 7) { newline = true; try writer.print("\n", .{}); } } if (!newline) { try writer.print("\n", .{}); } try writer.print("{s}\n", .{"};"}); }
0
repos/georgios
repos/georgios/kernel/kernel_start_x86_32.zig
// Multiboot stuff for bootloader to find, entry point, and setup for // kernel_main(). // // This replaced an assembly file I used since the beginning and is based on // Andrew Kelly's neat example: // https://github.com/andrewrk/HellOS/blob/master/hellos.zig // // It is here instead of in the x86_32 specific location because I think it // needs to be the root zig file and I don't think the root zig file can be in // a subdirectory of a zig package. I'm fine with such an important file being // an exception for platforms. const std = @import("std"); const builtin = @import("builtin"); const build_options = @import("build_options"); pub const kernel = @import("kernel.zig"); pub const kernel_main = kernel.kernel_main; const utils = @import("utils"); // pub const sse_enabled: bool = blk: { // for (builtin.cpu.arch.allFeaturesList()) |feature, index_usize| { // const index = @intCast(std.Target.Cpu.Feature.Set.Index, index_usize); // if (builtin.cpu.features.isEnabled(index)) { // if (feature.name.len >= 3 and std.mem.eql(u8, feature.name[0..3], "sse")) { // break :blk true; // } // } // } // break :blk false; // }; pub fn panic(msg: []const u8, trace: ?*std.builtin.StackTrace) noreturn { kernel.panic(msg, trace); } // TODO: Maybe refactor when struct fields get custom alignment const Multiboot2Header = packed struct { const magic_value: u32 = 0xe85250d6; const architecture_x86_32: u32 = 0; const architecture_value: u32 = architecture_x86_32; const tag_kind_end = 0; const tag_kind_info_request = 1; const tag_kind_framebuffer = 5; const tag_flag_must_understand: u16 = 0; const tag_flag_optional: u16 = 1; const VgaMode = if (build_options.multiboot_vbe) packed struct { const InfoRequestTag = packed struct { kind: u16 = tag_kind_info_request, flags: u16 = tag_flag_must_understand, size: u32 = @sizeOf(@This()), tag0: u32 = 7, // VBE }; const FramebufferTag = packed struct { kind: u16 = tag_kind_framebuffer, flags: u16 = tag_flag_must_understand, size: u32 = @sizeOf(@This()), width: u32 = 800, height: u32 = 600, depth: u32 = 24, }; info_request_tag: InfoRequestTag = InfoRequestTag{}, padding0: u32 = 0, framebuffer_tag: FramebufferTag = FramebufferTag{}, padding1: u32 = 0, } else void; magic: u32 = magic_value, architecture: u32 = architecture_value, header_length: u32 = @sizeOf(@This()), checksum: u32 = @bitCast(u32, -(@bitCast(i32, magic_value + architecture_value + @sizeOf(@This())))), vga_mode: VgaMode = VgaMode{}, end_tag_kind: u16 = tag_kind_end, end_tag_flags: u16 = tag_flag_must_understand, end_tag_size: u32 = 8, }; export var multiboot2_header align(8) linksection(".multiboot") = Multiboot2Header{}; /// Real Address of multiboot_info extern var low_multiboot_info: []u32; /// Real Address of kernel_range_start_available extern var low_kernel_range_start_available: u32; /// Real Address of kernel_page_table_count extern var low_kernel_page_table_count: u32; /// Real Address of kernel_page_tables extern var low_kernel_page_tables: []u32; /// Real Address of page_directory extern var low_page_directory: [utils.Ki(1)]u32; /// Stack for kernel_main_wrapper(). This will be reclaimed later as a frame /// when the memory system is initialized. pub export var temp_stack: [utils.Ki(4)]u8 align(utils.Ki(4)) linksection(".low_bss") = undefined; /// Stack for kernel_main() export var stack: [utils.Ki(8)]u8 align(16) linksection(".bss") = undefined; /// Entry Point export fn kernel_start() linksection(".low_text") callconv(.Naked) noreturn { @setRuntimeSafety(false); // Save location of Multiboot2 Info low_multiboot_info.ptr = asm volatile ( // Check for the Multiboot2 magic value in eax. It is a fatal error if // we don't have it, but we can't report it yet so set the pointer to 0 // and we will panic later when we first try to use it. // \\ cmpl $0x36d76289, %%eax \\ je passed_multiboot_check \\ mov $0, %%ebx \\ passed_multiboot_check: : [rv] "={ebx}" (-> [*]u32) ); // This just forces Zig to include multiboot2_header, which export isn't // doing for some reason. TODO: Report as bug? if (multiboot2_header.magic != 0xe85250d6) { asm volatile ("nop"); } // Not using @newStackCall as it seems to assume there is an existing // stack. asm volatile ( \\ mov %[temp_stack_end], %%esp \\ jmp kernel_main_wrapper :: [temp_stack_end] "{eax}" ( @ptrToInt(&temp_stack[0]) + temp_stack.len) ); unreachable; } extern var _VIRTUAL_OFFSET: u32; extern var _REAL_START: u32; extern var _REAL_END: u32; extern var _FRAME_SIZE: u32; fn align_down(value: u32, align_by: u32) linksection(".low_text") u32 { return value & -%(align_by); } fn align_up(value: u32, align_by: u32) linksection(".low_text") u32 { return align_down(value + align_by - 1, align_by); } /// Get setup for kernel_main export fn kernel_main_wrapper() linksection(".low_text") noreturn { @setRuntimeSafety(false); // Otherwise Zig inserts a call to a high kernel linked internal function // called __zig_probe_stack at the start. Runtime safety doesn't do much // good before kernel_main anyway. // TODO: Report as bug? const offset = @ptrToInt(&_VIRTUAL_OFFSET); const kernel_end = @ptrToInt(&_REAL_END); const frame_size = @ptrToInt(&_FRAME_SIZE); const after_kernel = align_up(kernel_end, frame_size); const pages_per_table = 1 << 10; // If we have it, copy Multiboot information because we could accidentally // overwrite it. Otherwise continue to defer the error. var page_tables_start: u32 = after_kernel; if (@ptrToInt(low_multiboot_info.ptr) != 0) { const multiboot_info_size = low_multiboot_info[0]; low_multiboot_info.len = multiboot_info_size >> 2; var multiboot_info_dest = after_kernel; for (low_multiboot_info) |*ptr, i| { @intToPtr([*]u32, multiboot_info_dest)[i] = ptr.*; } low_multiboot_info.ptr = @intToPtr([*]u32, multiboot_info_dest + offset); const multiboot_info_end = multiboot_info_dest + multiboot_info_size; page_tables_start = align_up(multiboot_info_end, frame_size); } // Create Page Tables for First 1MiB + Kernel + Multiboot + Page Tables // This is an iterative process for now. Start with 1 table, see if that's // enough. If not add another table. var frame_count: usize = (page_tables_start / frame_size) + 1; while (true) { low_kernel_page_table_count = align_up(frame_count, pages_per_table) / pages_per_table; if (frame_count <= low_kernel_page_table_count * pages_per_table) { break; } frame_count += 1; } const low_page_tables_end = page_tables_start + low_kernel_page_table_count * frame_size; // Set the start of what the memory system can work with. low_kernel_range_start_available = low_page_tables_end; // Get Slice for the Initial Page Tables low_kernel_page_tables.ptr = @intToPtr([*]u32, @intCast(usize, page_tables_start)); low_kernel_page_tables.len = pages_per_table * low_kernel_page_table_count; // Initialize Paging Structures to Zeros for (low_page_directory[0..]) |*ptr| { ptr.* = 0; } for (low_kernel_page_tables[0..]) |*ptr| { ptr.* = 0; } // Virtually Map Kernel to the Real Location and the Kernel Offset var table_i: usize = 0; while (table_i < low_kernel_page_table_count) { const table_start = &low_kernel_page_tables[table_i * utils.Ki(1)]; const entry = (@ptrToInt(table_start) & 0xFFFFF000) | 1; low_page_directory[table_i] = entry; low_page_directory[(offset >> 22) + table_i] = entry; // Div by 4MiB table_i += 1; } for (low_kernel_page_tables[0..frame_count]) |*ptr, i| { ptr.* = i * utils.Ki(4) + 1; } low_kernel_page_tables[0] = 0; // Translate for high mode low_kernel_page_tables.ptr = @intToPtr([*]u32, @ptrToInt(low_kernel_page_tables.ptr) + offset); // Use that Paging Scheme asm volatile ( \\ // Set Page Directory \\ mov $low_page_directory, %%eax \\ mov %%eax, %%cr3 \\ // Enable Paging \\ mov %%cr0, %%eax \\ or $0x80000001, %%eax \\ mov %%eax, %%cr0 ::: "eax" ); // Zig 0.6 will try to use SSE in normal generated code, at least while // setting an array to undefined in debug mode. Enable SSE to allow that to // work. // This also allows us to explicitly take advantage of it. // Based on the initialization code in https://wiki.osdev.org/SSE // TODO: Disabled for now in build.zig because we need to support saving // and restoring SSE registers first. // if (sse_enabled) { // asm volatile ( // \\ mov %%cr0, %%eax // \\ and $0xFFFB, %%ax // \\ or $0x0002, %%ax // \\ mov %%eax, %%cr0 // \\ mov %%cr4, %%eax // \\ or $0x0600, %%ax // \\ mov %%eax, %%cr4 // ::: // "eax" // ); // } // Start the generic main function, jumping to high memory kernel at the // same time. asm volatile ( \\mov %[stack_end], %%esp :: [stack_end] "{eax}" ( @ptrToInt(&stack[0]) + stack.len) ); kernel_main(); unreachable; }
0
repos/georgios
repos/georgios/kernel/map.zig
const memory = @import("memory.zig"); const print = @import("print.zig"); /// Map implemented using a simple binary tree. /// /// TODO: Replace with Balancing Tree /// /// For Reference See: /// https://en.wikipedia.org/wiki/Binary_search_tree pub fn Map(comptime KeyType: type, comptime ValueType: type, comptime eql: fn(a: KeyType, b: KeyType) bool, comptime cmp: fn(a: KeyType, b: KeyType) bool) type { return struct { const Self = @This(); pub const Node = struct { left: ?*Node, right: ?*Node, parent: ?*Node, key: KeyType, value: ValueType, pub fn replace_child(self: *Node, current_child: *Node, new_child: ?*Node) void { if (self.left == current_child) { self.left = new_child; } else if (self.right == current_child) { self.right = new_child; } else { @panic("Map.replace_child: Not a child of node!"); } if (new_child) |node| node.parent = self; } pub fn get_child(self: *const Node, right: bool) ?*Node { return if (right) self.right else self.left; } }; alloc: *memory.Allocator, root: ?*Node = null, len: usize = 0, const FindParentResult = struct { parent: *Node, leaf: *?*Node, }; fn find_parent(self: *Self, key: KeyType, start_node: *Node) FindParentResult { _ = self; var i = start_node; while (true) { if (cmp(key, i.key)) { if (i.right == null or eql(key, i.right.?.key)) { return FindParentResult{.parent = i, .leaf = &i.right}; } else { i = i.right.?; } } else { if (i.left == null or eql(key, i.left.?.key)) { return FindParentResult{.parent = i, .leaf = &i.left}; } else { i = i.left.?; } } } } pub fn insert_node(self: *Self, node: *Node) void { if (self.root == null) { node.parent = null; self.root = node; } else { const r = self.find_parent(node.key, self.root.?); node.parent = r.parent; r.leaf.* = node; } self.len += 1; } pub fn insert(self: *Self, key: KeyType, value: ValueType) memory.MemoryError!*Node { const node = try self.alloc.alloc(Node); node.left = null; node.right = null; node.key = key; node.value = value; self.insert_node(node); return node; } pub fn find_node(self: *Self, key: KeyType) ?*Node { if (self.root == null) { return null; } if (eql(key, self.root.?.key)) { return self.root; } return self.find_parent(key, self.root.?).leaf.*; } pub fn find(self: *Self, key: KeyType) ?ValueType { if (self.find_node(key)) |node| { return node.value; } return null; } fn replace_node(self: *Self, current: *Node, new: ?*Node) void { if (current == self.root) { self.root = new; } else { current.parent.?.replace_child(current, new); } } pub fn remove_node(self: *Self, node: *Node) void { const right_null = node.right == null; const left_null = node.left == null; if (right_null and left_null) { self.replace_node(node, null); } else if (right_null and !left_null) { self.replace_node(node, node.left); } else if (!right_null and left_null) { self.replace_node(node, node.right); } else { const replacement = node.left.?; const reattach = node.right.?; self.replace_node(node, replacement); const r = self.find_parent(reattach.key, replacement); reattach.parent = r.parent; r.leaf.* = reattach; } self.len -= 1; } pub fn dump_node(self: *Self, node: ?*Node) void { if (node == null) { print.string("null"); } else { print.format("({} (", .{node.?.key}); if (node.?.parent == null) { print.string("null): "); } else { print.format("{}): ", .{node.?.parent.?.key}); } self.dump_node(node.?.left); print.string(", "); self.dump_node(node.?.right); print.string(")"); } } pub fn dump(self: *Self) void { self.dump_node(self.root); } pub fn remove(self: *Self, key: KeyType) memory.MemoryError!bool { if (self.find_node(key)) |node| { self.remove_node(node); try self.alloc.free(node); return true; } return false; } /// Iterator that uses Morris Traversal pub const Iterator = struct { next_node: ?*Node = null, pub fn init(self: *Iterator, root: ?*Node) void { if (root == null) return; self.next_node = root; while (self.next_node.?.left) |node| { self.next_node = node; } } pub fn next(self: *Iterator) ?*Node { if (self.next_node == null) { return null; } const rv = self.next_node.?; if (rv.right != null) { self.next_node = rv.right; while (self.next_node.?.left) |node| { self.next_node = node; } return rv; } while (true) { const node = self.next_node.?; if (node.parent) |parent| { defer self.next_node = parent; if (parent.left == self.next_node) break; } else { self.next_node = null; break; } } return rv; } }; pub fn iterate(self: *Self) Iterator { var rv = Iterator{}; rv.init(self.root); return rv; } }; } fn usize_eql(a: usize, b: usize) bool { return a == b; } fn usize_cmp(a: usize, b: usize) bool { return a > b; } test "Map" { const std = @import("std"); var alloc = memory.UnitTestAllocator{}; const equal = std.testing.expectEqual; alloc.init(); defer alloc.done(); const UsizeUsizeMap = Map(usize, usize, usize_eql, usize_cmp); var map = UsizeUsizeMap{.alloc = &alloc.allocator}; const nil: ?usize = null; const niln: ?*UsizeUsizeMap.Node = null; // Empty try equal(@as(usize, 0), map.len); try equal(nil, map.find(45)); // Insert Some Values _ = try map.insert(4, 65); try equal(@as(usize, 1), map.len); _ = try map.insert(1, 44); _ = try map.insert(10, 12345); _ = try map.insert(23, 5678); _ = try map.insert(7, 53); try equal(@as(usize, 5), map.len); // Find Them try equal(@as(usize, 12345), map.find(10).?); try equal(@as(usize, 44), map.find(1).?); try equal(@as(usize, 5678), map.find(23).?); try equal(@as(usize, 65), map.find(4).?); try equal(@as(usize, 53), map.find(7).?); var it = map.iterate(); try equal(@as(usize, 1), it.next().?.key); try equal(@as(usize, 4), it.next().?.key); try equal(@as(usize, 7), it.next().?.key); try equal(@as(usize, 10), it.next().?.key); try equal(@as(usize, 23), it.next().?.key); try equal(niln, it.next()); // Try to Find Non-Existent Key try equal(nil, map.find(45)); try equal(false, try map.remove(45)); // Remove Node with Two Children try equal(true, try map.remove(10)); try equal(@as(usize, 4), map.len); try equal(@as(usize, 4), map.find_node(7).?.parent.?.key); // Remove the Rest try equal(true, try map.remove(1)); try equal(true, try map.remove(23)); try equal(true, try map.remove(4)); try equal(true, try map.remove(7)); try equal(@as(usize, 0), map.len); // Try to Find Keys That Once Existed try equal(nil, map.find(1)); try equal(nil, map.find(4)); }
0
repos/georgios
repos/georgios/kernel/BitmapFont.zig
const Self = @This(); const std = @import("std"); const utils = @import("utils"); const Bdf = utils.Bdf; const Glyph = Bdf.Glyph; const kernel = @import("kernel.zig"); const Allocator = kernel.memory.Allocator; pub const Codepoint = u32; pub const GlyphIndex = struct { codepoint: Codepoint, index: usize, }; const GlyphIndexMap = std.AutoArrayHashMap(Codepoint, usize); bdf_font: *const Bdf, glyph_index_map: GlyphIndexMap, raw_bitmaps: []const u8, pub fn init(self: *Self, bdf_font: *const Bdf, glyph_indices: []const GlyphIndex, raw_bitmaps: []const u8) !void { self.* = .{ .bdf_font = bdf_font, .glyph_index_map = GlyphIndexMap.init(kernel.alloc.std_allocator()), .raw_bitmaps = raw_bitmaps, }; for (glyph_indices) |glyph_index| { try self.glyph_index_map.put(glyph_index.codepoint, glyph_index.index); } } const GlyphHolder = struct { glyph: Glyph, raw_bitmaps: []const u8, pub fn iter_pixels(self: *const GlyphHolder) Glyph.Iterator { return self.glyph.iter_pixels(self.raw_bitmaps); } }; pub fn get(self: *const Self, codepoint: Codepoint) GlyphHolder { var index: usize = 0; if (self.glyph_index_map.get(codepoint)) |cp_index| { index = cp_index; } else { index = self.glyph_index_map.get(self.bdf_font.default_codepoint).?; } return .{.glyph = Glyph.new(self.bdf_font, index), .raw_bitmaps = self.raw_bitmaps}; } pub fn done(self: *Self) void { self.glyph_bitmap_offset_map.deinit(); }
0
repos/georgios
repos/georgios/kernel/mapped_list.zig
const memory = @import("memory.zig"); const Map = @import("map.zig").Map; const List = @import("list.zig").List; pub fn MappedList(comptime KeyType: type, comptime ValueType: type, comptime eql: fn(a: KeyType, b: KeyType) bool, comptime cmp: fn(a: KeyType, b: KeyType) bool) type { return struct { const Self = @This(); const MapType = Map(KeyType, *Node, eql, cmp); const ListType = List(*Node); const Node = struct { map: MapType.Node, list: ListType.Node, value: ValueType, }; alloc: *memory.Allocator, map: MapType = MapType{.alloc = undefined}, list: ListType = ListType{.alloc = undefined}, pub fn len(self: *Self) usize { if (self.map.len != self.list.len) { @panic("MappedList len out of sync!"); } return self.map.len; } pub fn find(self: *Self, key: KeyType) ?ValueType { const node_maybe = self.map.find_node(key); if (node_maybe == null) { return null; } return node_maybe.?.value.value; } pub fn push_front(self: *Self, key: KeyType, value: ValueType) memory.MemoryError!void { const node = try self.alloc.alloc(Node); node.map.right = null; node.map.left = null; node.map.key = key; node.map.value = node; node.list.value = node; node.value = value; self.map.insert_node(&node.map); self.list.push_front_node(&node.list); } pub fn pop_front(self: *Self) memory.MemoryError!?ValueType { const node_maybe = self.list.pop_front_node(); if (node_maybe == null) { return null; } const node = node_maybe.?.value; self.map.remove_node(&node.map); const value = node.value; try self.alloc.free(node); return value; } pub fn find_bump_to_front(self: *Self, key: KeyType) ?ValueType { const node_maybe = self.map.find_node(key); if (node_maybe == null) { return null; } const node = node_maybe.?.value; self.list.bump_node_to_front(&node.list); return node.value; } pub fn push_back(self: *Self, key: KeyType, value: ValueType) memory.MemoryError!void { const node = try self.alloc.alloc(Node); node.map.right = null; node.map.left = null; node.map.key = key; node.map.value = node; node.list.value = node; node.value = value; self.map.insert_node(&node.map); self.list.push_back_node(&node.list); } pub fn pop_back(self: *Self) memory.MemoryError!?ValueType { const node_maybe = self.list.pop_back_node(); if (node_maybe == null) { return null; } const node = node_maybe.?.value; self.map.remove_node(&node.map); const value = node.value; try self.alloc.free(node); return value; } pub fn find_bump_to_back(self: *Self, key: KeyType) ?ValueType { const node_maybe = self.map.find_node(key); if (node_maybe == null) { return null; } const node = node_maybe.?.value; self.list.bump_node_to_back(&node.list); return node.value; } pub fn find_remove(self: *Self, key: KeyType) memory.MemoryError!?ValueType { const node_maybe = self.map.find_node(key); if (node_maybe == null) { return null; } const node = node_maybe.?.value; self.list.remove_node(&node.list); self.map.remove_node(&node.map); const value = node.value; try self.alloc.free(node); return value; } }; } fn usize_eql(a: usize, b: usize) bool { return a == b; } fn usize_cmp(a: usize, b: usize) bool { return a > b; } test "MappedList" { const std = @import("std"); const equal = std.testing.expectEqual; var alloc = memory.UnitTestAllocator{}; alloc.init(); defer alloc.done(); const UsizeUsizeMappedList = MappedList(usize, usize, usize_eql, usize_cmp); var ml = UsizeUsizeMappedList{.alloc = &alloc.allocator}; const nil: ?usize = null; // Empty try equal(@as(usize, 0), ml.len()); try equal(nil, ml.find(100)); // Push and Pop from Front try ml.push_front(1, 2); try equal(@as(usize, 1), ml.len()); try equal(@as(usize, 2), ml.find(1).?); try equal(@as(usize, 2), (try ml.pop_front()).?); try equal(@as(usize, 0), ml.len()); // Empty try equal(@as(usize, 0), ml.len()); try equal(nil, ml.find(1)); // Push and Pop from Back try ml.push_back(5, 7); try equal(@as(usize, 1), ml.len()); try equal(@as(usize, 7), ml.find(5).?); try equal(@as(usize, 7), (try ml.pop_back()).?); try equal(@as(usize, 0), ml.len()); // Empty try equal(@as(usize, 0), ml.len()); try equal(nil, ml.find(5)); // Push and Pop Several Times From Both Directions try ml.push_front(11, 1); try ml.push_front(22, 2); try ml.push_back(123, 456); try ml.push_back(33, 3); try ml.push_front(44, 4); try ml.push_back(55, 5); // 44: 4, 22: 2, 11: 1, 123: 456, 33: 3, 55: 5 try equal(@as(usize, 456), (try ml.find_remove(123)).?); // 44: 4, 22: 2, 11: 1, 33: 3, 55: 5 try equal(@as(usize, 5), ml.len()); try equal(@as(usize, 1), ml.find(11).?); try equal(@as(usize, 2), ml.find(22).?); try equal(@as(usize, 3), ml.find(33).?); try equal(@as(usize, 4), ml.find(44).?); try equal(@as(usize, 5), ml.find(55).?); try equal(nil, ml.find(5)); try equal(@as(usize, 4), ml.find_bump_to_front(44).?); try equal(@as(usize, 5), ml.find_bump_to_back(55).?); try equal(@as(usize, 4), (try ml.pop_front()).?); // 22: 2, 11: 1, 33: 3, 55: 5 try equal(@as(usize, 5), (try ml.pop_back()).?); // 22: 2, 11: 1, 33: 3 try equal(@as(usize, 2), ml.find_bump_to_back(22).?); // 11: 1, 33: 3, 22: 2 try ml.push_back(66, 6); // 11: 1, 33: 3, 22: 2, 66: 6 try equal(@as(usize, 3), ml.find_bump_to_front(33).?); // 33: 3, 11: 1, 22: 2, 66: 6 try equal(@as(usize, 3), ml.find(33).?); try equal(@as(usize, 4), ml.len()); try equal(@as(usize, 6), (try ml.pop_back()).?); // 33: 3, 11: 1, 22: 2 try equal(@as(usize, 2), (try ml.pop_back()).?); // 33: 3, 11: 1 try equal(@as(usize, 1), (try ml.pop_back()).?); // 33: 3 try equal(@as(usize, 3), (try ml.pop_back()).?); // Empty try equal(@as(usize, 0), ml.len()); try equal(nil, ml.find(5)); try equal(nil, ml.find(55)); try equal(nil, try ml.pop_back()); try equal(nil, try ml.pop_front()); }
0
repos/georgios
repos/georgios/kernel/io.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const utils = @import("utils"); const georgios = @import("georgios"); const io = georgios.io; pub const File = io.File; pub const FileError = io.FileError; pub const BufferFile = io.BufferFile; pub const AddressType = u64; pub const Block = struct { // NOTE: In BLOCKS, not bytes. address: AddressType, data: ?[]u8 = null, }; /// Abstract Block I/O Interface pub const BlockStore = struct { const Self = @This(); page_alloc: Allocator, block_size: usize, max_address: ?AddressType = null, create_block_impl: fn(*BlockStore, *Block) FileError!void = alloc_data, destroy_block_impl: fn(*BlockStore, *Block) void = free_data, read_block_impl: fn(*BlockStore, *Block) FileError!void = default.read_block_impl, write_block_impl: fn(*BlockStore, *Block) FileError!void = default.write_block_impl, flush_impl: fn(*BlockStore) FileError!void = default.flush_impl, pub fn alloc_data(self: *BlockStore, block: *Block) FileError!void { if (block.data == null) { block.data = try self.page_alloc.alloc(u8, self.block_size); } } pub fn free_data(self: *BlockStore, block: *Block) void { if (block.data) |data| { self.page_alloc.free(data); block.data = null; } } pub fn create_block(self: *BlockStore, block: *Block) FileError!void { try self.create_block_impl(self, block); } pub fn destroy_block(self: *BlockStore, block: *Block) void { self.destroy_block_impl(self, block); } pub const default = struct { pub fn read_block_impl(self: *BlockStore, block: *Block) FileError!void { _ = self; _ = block; return FileError.Unsupported; } pub fn write_block_impl(self: *BlockStore, block: *Block) FileError!void { _ = self; _ = block; return FileError.Unsupported; } pub fn flush_impl(self: *BlockStore) FileError!void { _ = self; } }; fn check_block(self: *const BlockStore, block: *const Block) FileError!void { if (self.max_address) |max_address| { if (block.address > max_address) return FileError.OutOfBounds; } if (block.data == null) { @panic("check_block: block.data is null"); } else if (block.data.?.len != self.block_size) { @panic("check_block: block.data is the same size as the block size"); } } pub fn read_block(self: *BlockStore, block: *Block) FileError!void { try self.check_block(block); try self.read_block_impl(self, block); } // NOTE: address is in BYTES, not blocks pub fn read(self: *BlockStore, address: AddressType, to: []u8) FileError!void { // Also note that Block.address is in blocks const start_block = address / self.block_size; var src_offset = @intCast(usize, address % self.block_size); const block_count = utils.div_round_up(AddressType, @intCast(AddressType, src_offset + to.len), self.block_size); const end_block = start_block + block_count; var dest_offset: usize = 0; var block = Block{.address = start_block}; try self.create_block(&block); defer self.destroy_block(&block); while (block.address < end_block) { const size = @minimum( @intCast(usize, self.block_size) - src_offset, to.len - dest_offset); try self.read_block(&block); const new_dest_offset = dest_offset + size; _ = utils.memory_copy_truncate( to[dest_offset..new_dest_offset], block.data.?[src_offset..]); src_offset = 0; dest_offset = new_dest_offset; block.address += 1; } } pub fn expect_read(self: *BlockStore, address: AddressType, expected: []const u8, buffer: []u8) !void { try self.read(address, buffer); try utils.expect_equal_bytes(expected, buffer); } pub fn write_block(self: *BlockStore, block: *Block) FileError!void { try self.check_block(block); try self.write_block_impl(self, block); } // NOTE: address is in BYTES, not blocks pub fn write_for_test(self: *BlockStore, address: AddressType, data: []const u8) FileError!void { var block = Block{.address = address}; try self.create_block(&block); defer self.destroy_block(&block); if (data.len < self.block_size) { for (block.data.?[data.len..]) |*b| { b.* = 0; } } _ = utils.memory_copy_truncate(block.data.?, data); try self.write_block(&block); } pub fn flush(self: *BlockStore) FileError!void { try self.flush_impl(self); } }; pub fn simple_block_store_test(alloc: Allocator, bs: *BlockStore, block_count: usize) !void { if (block_count < 3) @panic("simple_block_store_test: block_count needs to be at least 3"); var block = Block{.address = 0}; try bs.create_block(&block); defer bs.destroy_block(&block); // Write in whole blocks const Int = u16; var int: Int = 0; while (block.address < block_count) { for (std.mem.bytesAsSlice(Int, block.data.?)) |*value| { value.* = int; int += 1; } try bs.write_block(&block); block.address += 1; } // Read in whole blocks block.address = 0; int = 0; while (block.address < block_count) { try bs.read_block(&block); for (std.mem.bytesAsSlice(Int, block.data.?)) |value| { try std.testing.expectEqual(int, value); int += 1; } block.address += 1; } // Read partial blocks (Ending half of block, whole block, starting half of block) const expected = try alloc.alloc(u8, bs.block_size * 2); defer alloc.free(expected); for (std.mem.bytesAsSlice(Int, expected)) |*value, i| { value.* = @intCast(u16, i + bs.block_size / @sizeOf(Int) / 2); } const partial_blocks = try alloc.alloc(u8, bs.block_size * 2); defer alloc.free(partial_blocks); try bs.read(bs.block_size / 2, partial_blocks); for (std.mem.bytesAsSlice(Int, partial_blocks)) |value, i| { try std.testing.expectEqual(@intCast(u16, i + bs.block_size / @sizeOf(Int) / 2), value); } } /// BlockStore that stores blocks in memory, optionally as cache to another /// BlockStore. pub const MemoryBlockStore = struct { const BlockInfo = struct { block: Block, changed: bool = false, list_node: ?*BlockList.Node = null, }; const BlockList = utils.List(*BlockInfo); const BlockMap = std.AutoHashMap(AddressType, *BlockInfo); alloc: Allocator = undefined, cached_block_store: ?*BlockStore = null, cached_block_limit: ?usize = null, block_map: BlockMap = undefined, block_list: BlockList = undefined, block_store_if: BlockStore = undefined, pub fn init(self: *MemoryBlockStore, alloc: Allocator, page_alloc: Allocator, block_size: usize) void { self.alloc = alloc; self.block_map = BlockMap.init(alloc); self.block_list = .{.alloc = alloc}; self.block_store_if = .{ .page_alloc = page_alloc, .block_size = block_size, .create_block_impl = create_block_impl, .destroy_block_impl = destroy_block_impl, .read_block_impl = read_block_impl, .write_block_impl = write_block_impl, .flush_impl = flush_impl, }; } pub fn init_as_cache(self: *MemoryBlockStore, alloc: Allocator, cached_block_store: *BlockStore, limit: usize) void { self.init(alloc, undefined, cached_block_store.block_size); self.cached_block_store = cached_block_store; self.cached_block_limit = limit; self.block_store_if.max_address = cached_block_store.max_address; // TODO: Preallocate capacity for block_map? // TODO: Preallocate block data for block_map? } pub fn clear(self: *MemoryBlockStore) void { var it = self.block_map.iterator(); while (it.next()) |kv| { self.block_store_if.destroy_block(&kv.value_ptr.*.block); self.alloc.destroy(kv.value_ptr.*); } self.block_map.clearAndFree(); self.block_list.clear(); } pub fn done(self: *MemoryBlockStore) void { self.clear(); self.block_map.deinit(); } fn create_block_impl(bs: *BlockStore, block: *Block) FileError!void { const self = @fieldParentPtr(MemoryBlockStore, "block_store_if", bs); if (self.cached_block_store) |cached_block_store| { try cached_block_store.create_block(block); } else { try self.block_store_if.alloc_data(block); } } fn destroy_block_impl(bs: *BlockStore, block: *Block) void { const self = @fieldParentPtr(MemoryBlockStore, "block_store_if", bs); if (self.cached_block_store) |cached_block_store| { cached_block_store.destroy_block(block); } else { self.block_store_if.free_data(block); } } fn flush_block(self: *MemoryBlockStore, block_info: *BlockInfo) FileError!void { if (block_info.changed) { try self.cached_block_store.?.write_block(&block_info.block); block_info.changed = false; } } fn flush_impl(bs: *BlockStore) FileError!void { const self = @fieldParentPtr(MemoryBlockStore, "block_store_if", bs); if (self.cached_block_store) |cached_block_store| { var it = self.block_map.iterator(); while (it.next()) |kv| { try self.flush_block(kv.value_ptr.*); } try cached_block_store.flush(); } } const GetBlockMode = enum { GetForRead, GetOrCreateForRead, GetOrCreateForWrite, }; const GetBlockResult = struct { block: ?*Block = null, created: bool = false, }; pub fn block_count(self: *const MemoryBlockStore) usize { return self.block_map.count(); } fn get_block(self: *MemoryBlockStore, address: AddressType, mode: GetBlockMode) FileError!GetBlockResult { // TODO: Optimize if cached is returning all zeros? var result = GetBlockResult{}; if (mode == .GetForRead) { result.block = if (self.block_map.getPtr(address)) |block_info| &block_info.*.block else null; return result; } const r = try self.block_map.getOrPut(address); const block_info_ptr_ptr = r.value_ptr; var block_info: *BlockInfo = undefined; result.created = !r.found_existing; if (result.created) { block_info = try self.alloc.create(BlockInfo); block_info.* = .{.block = .{.address = address}}; block_info_ptr_ptr.* = block_info; if (self.cached_block_store) |cached_block_store| { // If there's too many blocked stored then flush and discard // the oldest one. if (self.block_count() > self.cached_block_limit.?) { const popped_block_info = self.block_list.pop_back().?; const popped_block = &popped_block_info.block; try self.flush_block(popped_block_info); cached_block_store.destroy_block(popped_block); _ = self.block_map.remove(popped_block.address); self.alloc.destroy(popped_block_info); } try self.block_list.push_front(block_info); block_info.list_node = self.block_list.head.?; } try self.block_store_if.create_block(&block_info.block); } else { block_info = block_info_ptr_ptr.*; if (self.cached_block_store != null) { self.block_list.bump_node_to_front(block_info.list_node.?); } } if (mode == .GetOrCreateForWrite) block_info.changed = true; result.block = &block_info.block; return result; } fn read_block_impl(bs: *BlockStore, block: *Block) FileError!void { const self = @fieldParentPtr(MemoryBlockStore, "block_store_if", bs); const result = try self.get_block(block.address, if (self.cached_block_store == null) .GetForRead else .GetOrCreateForRead); if (result.block) |stored_block| { if (result.created) { try self.cached_block_store.?.read_block(stored_block); } _ = try utils.memory_copy_error(block.data.?, stored_block.data.?); } else { for (block.data.?) |*byte| { byte.* = 0; } } } fn write_block_impl(bs: *BlockStore, block: *Block) FileError!void { const self = @fieldParentPtr(MemoryBlockStore, "block_store_if", bs); const stored_block = (try self.get_block(block.address, .GetOrCreateForWrite)).block.?; _ = try utils.memory_copy_error(stored_block.data.?, block.data.?); } }; fn memory_block_store_test(mbs: *MemoryBlockStore, cached_mbs: ?*MemoryBlockStore) !void { const expectEqual = std.testing.expectEqual; const bs = &mbs.block_store_if; const block_size = bs.block_size; _ = cached_mbs; try expectEqual(@as(usize, 0), mbs.block_count()); // Make sure we read zeros before anything is written. { var e = [_]u8{0} ** 4; var b: [e.len]u8 = undefined; try bs.expect_read(0, e[0..], b[0..]); } { // VVV V // 01234567 89abcdef var e = [_]u8{0} ** 4; var b: [e.len]u8 = undefined; try bs.expect_read(5, e[0..], b[0..]); } { var e = [_]u8{0} ** 18; var b: [e.len]u8 = undefined; try bs.expect_read(0, e[0..], b[0..]); } if (cached_mbs) |cmbs| { try expectEqual(@as(usize, 3), mbs.block_count()); try expectEqual(@as(usize, 0), cmbs.block_count()); // Nothing's been changed yet, so flushing the cache shouldn't add // blocks to the underlying store. try bs.flush(); try expectEqual(@as(usize, 0), cmbs.block_count()); } else { try expectEqual(@as(usize, 0), mbs.block_count()); } // Can read and write data. { var e = [_]u8{0} ** 16; for (e) |*b, i| { b.* = @truncate(u8, i); } try bs.write_for_test(0, e[0..8]); try bs.write_for_test(1, e[8..16]); var b: [e.len]u8 = undefined; try bs.expect_read(0, e[0..], b[0..]); } { // VVV V // 01234567 89abcdef var e = [_]u8{5, 6, 7, 8}; var b: [e.len]u8 = undefined; try bs.expect_read(5, e[0..], b[0..]); } if (cached_mbs) |cmbs| { try expectEqual(@as(usize, 3), mbs.block_count()); try expectEqual(@as(usize, 0), cmbs.block_count()); try bs.flush(); try expectEqual(@as(usize, 2), cmbs.block_count()); } else { try expectEqual(@as(usize, 2), mbs.block_count()); } // Reading just past the written blocks should return zeros. { var e = [_]u8{0} ** 8; var b: [e.len]u8 = undefined; try bs.expect_read(block_size * 2, e[0..], b[0..]); } // But setting a max address and trying again should cause an error. bs.max_address = 1; { var e = [_]u8{0} ** 8; try std.testing.expectError(FileError.OutOfBounds, bs.write_for_test(2, e[0..])); var b: [e.len]u8 = undefined; try std.testing.expectError(FileError.OutOfBounds, bs.read(block_size * 2, b[0..])); } bs.max_address = null; if (cached_mbs) |cmbs| { try expectEqual(@as(usize, 3), mbs.block_count()); try expectEqual(@as(usize, 2), cmbs.block_count()); // Block 2 is at front, but reading 1 will bring it back to the front again try expectEqual(@as(AddressType, 2), mbs.block_list.front().?.block.address); try expectEqual(@as(AddressType, 1), mbs.block_list.head.?.next.?.value.block.address); { var e = [_]u8{0} ** 8; for (e) |*b, i| { b.* = @truncate(u8, i + 8); } var b: [e.len]u8 = undefined; try bs.expect_read(8, e[0..], b[0..]); } try expectEqual(@as(AddressType, 1), mbs.block_list.front().?.block.address); // Writing past the cache limit will flush the oldest block from mbs to // cmbs and discard it. { var e = [_]u8{0} ** 16; for (e) |*b, i| { b.* = @truncate(u8, 0x10 + i); } try bs.write_for_test(3, e[0..8]); try expectEqual(@as(usize, 4), mbs.block_count()); try expectEqual(@as(usize, 2), cmbs.block_count()); try bs.flush(); try expectEqual(@as(usize, 3), cmbs.block_count()); // Block 0 should be next to be discarded try expectEqual(@as(AddressType, 0), mbs.block_list.back().?.block.address); try bs.write_for_test(4, e[8..16]); try expectEqual(@as(usize, 4), mbs.block_count()); try expectEqual(@as(usize, 3), cmbs.block_count()); try bs.flush(); try expectEqual(@as(usize, 4), cmbs.block_count()); } // Block 0 was discarded, now 4 is at the front and 2 is at the back try expectEqual(@as(AddressType, 4), mbs.block_list.front().?.block.address); try expectEqual(@as(AddressType, 2), mbs.block_list.back().?.block.address); // Write to 2 to bring it to the front const hello = " Hello! "; try bs.write_for_test(2, hello); try expectEqual(@as(AddressType, 2), mbs.block_list.front().?.block.address); try std.testing.expectEqualStrings(hello, mbs.block_list.front().?.block.data.?); // Do read from the flushed and discarded block 0 { const e = "\x00\x01\x02\x03\x04\x05\x06\x07"; var b: [e.len]u8 = undefined; try bs.expect_read(0, e[0..], b[0..]); } try expectEqual(@as(AddressType, 0), mbs.block_list.front().?.block.address); } else { try expectEqual(@as(usize, 2), mbs.block_count()); } } test "MemoryBlockStore" { var ta = utils.TestAlloc{}; defer ta.deinit(.Panic); errdefer ta.deinit(.NoPanic); const alloc = ta.alloc(); var mbs = MemoryBlockStore{}; mbs.init(alloc, alloc, 8); defer mbs.done(); try memory_block_store_test(&mbs, null); try simple_block_store_test(alloc, &mbs.block_store_if, 16); } test "MemoryBlockStore as cache" { var ta = utils.TestAlloc{}; defer ta.deinit(.Panic); errdefer ta.deinit(.NoPanic); const alloc = ta.alloc(); var mbs = MemoryBlockStore{}; mbs.init(alloc, alloc, 8); defer mbs.done(); var cache = MemoryBlockStore{}; cache.init_as_cache(alloc, &mbs.block_store_if, 4); defer cache.done(); try memory_block_store_test(&cache, &mbs); try simple_block_store_test(alloc, &cache.block_store_if, 16); } pub const StdFileBlockStore = struct { file: *const std.fs.File = undefined, block_store_if: BlockStore = undefined, pub fn init(self: *StdFileBlockStore, page_alloc: Allocator, file: *const std.fs.File, block_size: usize) void { self.* = .{ .file = file, .block_store_if = .{ .page_alloc = page_alloc, .block_size = block_size, .read_block_impl = read_block_impl, .write_block_impl = write_block_impl, }, }; } fn seek_to(self: *StdFileBlockStore, block: *Block) FileError!void { const stream = self.file.seekableStream(); stream.seekTo(block.address * self.block_store_if.block_size) catch return FileError.OutOfBounds; } fn read_block_impl(bs: *BlockStore, block: *Block) FileError!void { const self = @fieldParentPtr(StdFileBlockStore, "block_store_if", bs); try self.seek_to(block); _ = self.file.reader().read(block.data.?) catch return FileError.Internal; } fn write_block_impl(bs: *BlockStore, block: *Block) FileError!void { const self = @fieldParentPtr(StdFileBlockStore, "block_store_if", bs); try self.seek_to(block); _ = self.file.writer().write(block.data.?) catch return FileError.Internal; } }; test "StdFileBlockStore read only" { var ta = utils.TestAlloc{}; defer ta.deinit(.Panic); errdefer ta.deinit(.NoPanic); const alloc = ta.alloc(); const dir: std.fs.Dir = std.fs.cwd(); const file = try dir.openFile("kernel/io.zig", .{}); defer file.close(); const block_size = 32; const end = block_size * 2; var fbs = StdFileBlockStore{}; fbs.init(alloc, &file, block_size); const file_contents = @embedFile("io.zig"); const fc0 = file_contents[0..block_size]; const fc1 = file_contents[block_size..end]; const fc01 = file_contents[0..end]; var buffer: [end]u8 = undefined; const b0 = buffer[0..block_size]; const b1 = buffer[block_size..end]; const b01 = buffer[0..end]; try fbs.block_store_if.read(0, b0); try std.testing.expectEqualStrings(fc0, b0); try fbs.block_store_if.read(block_size, b1); try std.testing.expectEqualStrings(fc1, b1); try fbs.block_store_if.read(0, b01); try std.testing.expectEqualStrings(fc01, b01); } test "StdFileBlockStore read and write" { var ta = utils.TestAlloc{}; defer ta.deinit(.Panic); errdefer ta.deinit(.NoPanic); const alloc = ta.alloc(); const dir: std.fs.Dir = std.fs.cwd(); const file = try dir.createFile("tmp/StdFileBlockStore-test", .{.read = true}); defer file.close(); const block_size = 32; var fbs = StdFileBlockStore{}; fbs.init(alloc, &file, block_size); try simple_block_store_test(alloc, &fbs.block_store_if, block_size); }
0
repos/georgios
repos/georgios/kernel/print.zig
// These are wrappers of what is in fprint.zig for convenience. See there for // the implementations. const builtin = @import("builtin"); const fprint = @import("fprint.zig"); const io = @import("io.zig"); var console_file: ?*io.File = null; pub var debug_print = false; pub fn init(file: ?*io.File, debug: bool) void { console_file = file; debug_print = debug; } pub fn get_console_file() ?*io.File { return console_file; } pub fn char(ch: u8) void { if (console_file) |o| { fprint.char(o, ch) catch unreachable; } } pub fn nstring(str: [*]const u8, size: usize) void { if (console_file) |o| { fprint.nstring(o, str, size) catch unreachable; } } pub fn string(str: []const u8) void { if (console_file) |o| { fprint.string(o, str) catch unreachable; } } pub fn cstring(str: [*]const u8) void { if (console_file) |o| { fprint.cstring(o, str) catch unreachable; } } pub fn stripped_string(str: [*]const u8, size: usize) void { if (console_file) |o| { fprint.stripped_string(o, str, size) catch unreachable; } } pub fn uint(value: usize) void { if (console_file) |o| { fprint.uint(o, value) catch unreachable; } } pub fn uint64(value: u64) void { if (console_file) |o| { fprint.uint64(o, value) catch unreachable; } } pub fn int(value: isize) void { if (console_file) |o| { fprint.int(o, value) catch unreachable; } } pub fn int_sign(value: usize) void { if (console_file) |o| { fprint.int_sign(o, value) catch unreachable; } } pub fn hex(value: usize) void { if (console_file) |o| { fprint.hex(o, value) catch unreachable; } } pub fn address(value: usize) void { if (console_file) |o| { fprint.address(o, value) catch unreachable; } } pub fn byte(value: u8) void { if (console_file) |o| { fprint.byte(o, value) catch unreachable; } } pub fn boolean(value: bool) void { if (console_file) |o| { fprint.boolean(o, value) catch unreachable; } } pub fn any(value: anytype) void { if (console_file) |o| { fprint.any(o, value) catch unreachable; } } pub fn format(comptime fmtstr: []const u8, args: anytype)void { if (console_file) |o| { fprint.format(o, fmtstr, args) catch unreachable; } } pub fn dump_memory(ptr: usize, size: usize) void { if (console_file) |o| { fprint.dump_memory(o, ptr, size) catch unreachable; } } pub fn dump_bytes(byteslice: []const u8) void { if (console_file) |o| { fprint.dump_bytes(o, byteslice) catch unreachable; } } pub fn dump_raw_object(comptime Type: type, value: *const Type) void { if (console_file) |o| { fprint.dump_raw_object(o, Type, value) catch unreachable; } } // print.string("0x0 -> "); // print.hex(0x0); // print.char('\n'); // print.string("0x1 -> "); // print.hex(0x1); // print.char('\n'); // print.string("0x9 -> "); // print.hex(0x9); // print.char('\n'); // print.string("0xA -> "); // print.hex(0xA); // print.char('\n'); // print.string("0xF -> "); // print.hex(0xF); // print.char('\n'); // print.string("0x10 -> "); // print.hex(0x10); // print.char('\n'); // print.string("0xABCDEF -> "); // print.hex(0xABCDEF); // print.char('\n'); // print.byte(0x00); // print.char('\n'); // print.byte(0x01); // print.char('\n'); // print.byte(0x0F); // print.char('\n'); // print.byte(0xFF); // print.char('\n'); // var b: bool = false; // var x: u16 = 0xABCD; // print.format("Hello {} {}\n", @intCast(usize, 10), b); // print.format("Strings {} {}\n", "Hello1", c"Hello2"); // print.format("{{These braces are escaped}}\n"); // print.format("{:x}\n", x); pub fn debug_char(ch: u8) void { if (debug_print) { char(ch); } } pub fn debug_nstring(str: [*]const u8, size: usize) void { if (debug_print) { nstring(str, size); } } pub fn debug_string(str: []const u8) void { if (debug_print) { string(str); } } pub fn debug_cstring(str: [*]const u8) void { if (debug_print) { cstring(str); } } pub fn debug_stripped_string(str: [*]const u8) void { if (debug_print) { stripped_string(str); } } pub fn debug_uint(value: usize) void { if (debug_print) { uint(value); } } pub fn debug_uint64(value: u64) void { if (debug_print) { uint64(value); } } pub fn debug_int(value: isize) void { if (debug_print) { int(value); } } pub fn debug_int_sign(value: usize, show_positive: bool) void { if (debug_print) { int_sign(value, show_positive); } } pub fn debug_hex(value: usize) void { if (debug_print) { hex(value); } } pub fn debug_address(value: usize) void { if (debug_print) { address(value); } } pub fn debug_byte(value: u8) void { if (debug_print) { byte(value); } } pub fn debug_boolean(value: bool) void { if (debug_print) { boolean(value); } } pub fn debug_any(value: anytype) void { if (debug_print) { any(value); } } pub fn debug_format(comptime fmtstr: []const u8, args: anytype)void { if (debug_print) { format(fmtstr, args); } } pub fn debug_dump_memory(ptr: usize, size: usize) void { if (debug_print) { dump_memory(ptr, size); } } pub fn debug_dump_bytes(byteslice: []const u8) void { if (debug_print) { dump_bytes(byteslice); } } pub fn debug_dump_raw_object(comptime Type: type, value: *const Type) void { if (debug_print) { dump_raw_object(Type, value); } }
0
repos/georgios
repos/georgios/kernel/test.zig
test "kernel test root" { _ = @import("fprint.zig"); _ = @import("buddy_allocator.zig"); _ = @import("list.zig"); _ = @import("map.zig"); _ = @import("mapped_list.zig"); _ = @import("log.zig"); _ = @import("fs.zig"); _ = @import("fs/Ext2.zig"); _ = @import("fs/RamDisk.zig"); _ = @import("sync.zig"); _ = @import("io.zig"); }
0
repos/georgios
repos/georgios/kernel/devices.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const utils = @import("utils"); const kernel = @import("kernel.zig"); const BlockStore = kernel.io.BlockStore; pub const Error = Allocator.Error; pub const Class = enum (u32) { Unknown, Root, Other, Bus, Disk, const strings = [@typeInfo(Class).Enum.fields.len][]const u8{ "unknown", "device root", "other", "bus", "disk", }; pub fn to_string(self: Class) []const u8 { return strings[@enumToInt(self)]; } }; pub const Id = u32; pub const Device = struct { const ChildDevices = std.StringHashMap(*Device); class: Class, deinit_impl: fn(self: *Device) void, desc_impl: ?fn(self: *Device) []const u8 = null, as_block_store_impl: ?fn(self: *Device) *BlockStore = null, alloc: Allocator = undefined, id: Id = undefined, name: []const u8 = undefined, child_devices: ChildDevices = undefined, next_child_id: Id = 0, pub fn init(self: *Device, alloc: Allocator, id: Id) void { self.alloc = alloc; self.id = id; self.child_devices = ChildDevices.init(alloc); } pub fn deinit(self: *Device) void { var it = self.devices.iterator(); while (it.next()) |kv| { kv.value_ptr.deinit() catch unreachable; } self.devices.deinit(); self.deinit_impl(self); self.alloc.free(self.name); } pub fn desc(self: *Device) ?[]const u8 { if (self.desc_impl) |desc_impl| { return desc_impl(self); } return null; } pub fn add_child_device(self: *Device, device: *Device, prefix: []const u8) Error!void { device.init(self.alloc, self.next_child_id); var sw = utils.StringWriter.init(self.alloc); try sw.writer().print("{s}{}", .{prefix, device.id}); device.name = sw.get(); self.next_child_id += 1; try self.child_devices.putNoClobber(device.name, device); } pub fn get(self: *Device, path: []const []const u8) ?*Device { if (path.len > 0) { if (self.child_devices.get(path[0])) |child| { return child.get(path[1..]); } return null; } return self; } pub fn print(self: *Device, writer: anytype, depth: usize) anyerror!void { if (depth > 0) { const d = depth - 1; var i: usize = 0; while (i < d) { try writer.print(" ", .{}); i += 1; } try writer.print("{}: {s}: {s}", .{self.id, self.class.to_string(), self.name}); if (self.desc()) |descr| { try writer.print(": {s}", .{descr}); } try writer.print("\n", .{}); } var it = self.child_devices.iterator(); while (it.next()) |kv| { try kv.value_ptr.*.print(writer, depth + 1); } } pub fn as_block_store(self: *Device) ?*BlockStore { if (self.as_block_store_impl) |as_block_store_impl| { return as_block_store_impl(self); } return null; } }; pub const Manager = struct { root_device: Device = .{ .class = .Root, .deinit_impl = root_deinit_impl, }, pub fn init(self: *Manager, alloc: Allocator) void { self.root_device.init(alloc, undefined); } pub fn deinit(self: *Manager) void { self.root_device.deinit(); } pub fn get(self: *Manager, path: []const []const u8) ?*Device { return self.root_device.get(path); } pub fn print_tree(self: *Manager, writer: anytype) anyerror!void { try self.root_device.print(writer, 0); } fn root_deinit_impl(device: *Device) void { _ = device; } };
0
repos/georgios
repos/georgios/kernel/fprint.zig
const builtin = @import("std").builtin; const utils = @import("utils"); const io = @import("io.zig"); const File = io.File; const FileError = io.FileError; /// Print a char pub fn char(file: *File, ch: u8) FileError!void { _ = try file.write(([_]u8{ch})[0..]); } /// Print a string. pub fn string(file: *File, str: []const u8) FileError!void { _ = try file.write(str); } /// Print a string with a null terminator. pub fn cstring(file: *File, str: [*]const u8) FileError!void { var i: usize = 0; while (str[i] > 0) { try char(file, str[i]); i += 1; } } /// Print string stripped of trailing whitespace. pub fn stripped_string(file: *File, str: [*]const u8, size: usize) FileError!void { try string(file, str[0..utils.stripped_string_size(str[0..size])]); } fn uint_recurse(comptime uint_type: type, file: *File, value: uint_type) FileError!void { const digit: u8 = @intCast(u8, value % 10); const next = value / 10; if (next > 0) { try uint_recurse(uint_type, file, next); } try char(file, '0' + digit); } /// Print a unsigned integer pub fn uint(file: *File, value: usize) FileError!void { if (value == 0) { try char(file, '0'); return; } try uint_recurse(usize, file, value); } pub fn uint64(file: *File, value: u64) FileError!void { if (value == 0) { try char(file, '0'); return; } try uint_recurse(u64, file, value); } /// Print a signed integer pub fn int(file: *File, value: isize) FileError!void { var x = value; if (value < 0) { try char(file, '-'); x = -value; } try uint(file, @intCast(usize, x)); } /// Print a signed integer with an optional '+' sign. pub fn int_sign(file: *File, value: usize, show_positive: bool) FileError!void { if (value > 0 and show_positive) { try char(file, '+'); } try int(file, value); } fn nibble(file: *File, value: u4) FileError!void { try char(file, utils.nibble_char(value)); } fn hex_recurse(file: *File, value: usize) FileError!void { const next = value / 0x10; if (next > 0) { try hex_recurse(file, next); } try nibble(file, @intCast(u4, value % 0x10)); } /// Print a unsigned integer as a hexadecimal number with a "0x" prefix pub fn hex(file: *File, value: usize) FileError!void { try string(file, "0x"); if (value == 0) { try char(file, '0'); return; } try hex_recurse(file, value); } /// Print a unsigned integer as a hexadecimal number a padded to usize and /// prefixed with "@0x". pub fn address(file: *File, value: usize) FileError!void { const prefix = "@0x"; // For 32b: @0xXXXXXXXX // For 64b: @0xXXXXXXXXXXXXXXXX const nibble_count = @sizeOf(usize) * 2; const char_count = prefix.len + nibble_count; var buffer: [char_count]u8 = undefined; for (prefix) |c, i| { buffer[i] = c; } for (buffer[prefix.len..]) |*ptr, i| { const nibble_index: usize = (nibble_count - 1) - i; ptr.* = utils.nibble_char(utils.select_nibble(usize, value, nibble_index)); } try string(file, buffer[0..]); } test "address" { const std = @import("std"); const BufferFile = io.BufferFile; var file_buffer: [128]u8 = undefined; utils.memory_set(file_buffer[0..], 0); var buffer_file = BufferFile{}; buffer_file.init(file_buffer[0..]); const file = &buffer_file.file; try address(file, 0x7bc75e39); const length = utils.string_length(file_buffer[0..]); const expected = if (@sizeOf(usize) == 4) "@0x7bc75e39" else if (@sizeOf(usize) == 8) "@0x000000007bc75e39" else @compileError("usize size missing in this test"); try std.testing.expectEqualSlices(u8, expected[0..], file_buffer[0..length]); } /// Print a hexadecimal representation of a byte (no "0x" prefix) pub fn byte(file: *File, value: u8) FileError!void { var buffer: [2]u8 = undefined; utils.byte_buffer(buffer[0..], value); try string(file, buffer); } /// Print a boolean as "true" or "false". pub fn boolean(file: *File, value: bool) FileError!void { try string(file, if (value) "true" else "false"); } /// Try to guess how to print a value based on its type. pub fn any(file: *File, value: anytype) FileError!void { const Type = @TypeOf(value); const Traits = @typeInfo(Type); switch (Traits) { builtin.TypeId.Int => |int_type| { if (int_type.signedness == .signed) { try int(file, value); } else { if (int_type.bits * 8 > @sizeOf(usize)) { try uint64(file, value); } else { try uint(file, value); } } }, builtin.TypeId.Bool => try boolean(file, value), builtin.TypeId.Array => |array_type| { const t = array_type.child; if (t == u8) { try string(file, value[0..]); } else { comptime var i: usize = 0; inline while (i < array_type.len) { try format(file, "[{}] = {},", .{i, value[i]}); i += 1; } } }, builtin.TypeId.Pointer => |ptr_type| { const t = ptr_type.child; if (ptr_type.is_allowzero and value == 0) { try string(file, "null"); } else if (t == u8) { if (ptr_type.size == builtin.TypeInfo.Pointer.Size.Slice) { try string(file, value); } else { try cstring(file, value); } } else { try any(file, value.*); // @compileError("Can't Print Pointer to " ++ @typeName(t)); } }, builtin.TypeId.Struct => |struct_type| { inline for (struct_type.fields) |field| { try string(file, field.name); try string(file, ": "); try any(file, @field(value, field.name)); try string(file, "\n"); } }, builtin.TypeId.Enum => { if (utils.enum_name(Type, value)) |name| { try string(file, name); } else { try string(file, "<Invalid Value For " ++ @typeName(Type) ++ ">"); } }, else => @compileError("Can't Print " ++ @typeName(Type)), } } /// Print Using Format String, meant to work somewhat like Zig's /// `std.fmt.format`. /// /// Layout of a valid format marker is `{[specifier:]}`. /// /// TODO: Match std.fmt.format instead of Python string.format and use /// {[specifier]:...} /// /// `specifier`: /// None /// Insert next argument using default formating and `fprint.any()`. /// `x` and `X` /// Insert next argument using hexadecimal format. It must be an /// unsigned integer. The case of the letters A-F of the result depends /// on if `x` or `X` was used as the specifier (TODO). /// 'a' /// Like "x", but prints the full address value prefixed with "@". /// 'c' /// Insert the u8 as a character (more specficially as a UTF-8 byte). /// /// Escapes: /// `{{` is replaced with `{` and `}}` is replaced by `}`. pub fn format(file: *File, comptime fmtstr: []const u8, args: anytype) FileError!void { const State = enum { NoFormat, // Outside Braces Format, // Inside Braces EscapeEnd, // Expecting } FormatSpec, // After {: }; const Spec = enum { Default, Hex, Address, Char, }; comptime var arg: usize = 0; comptime var state = State.NoFormat; comptime var spec = Spec.Default; comptime var no_format_start: usize = 0; inline for (fmtstr) |ch, index| { switch (state) { State.NoFormat => switch (ch) { '{' => { if (no_format_start < index) { try string(file, fmtstr[no_format_start..index]); } state = State.Format; spec = Spec.Default; }, '}' => { // Should be Escaped } if (no_format_start < index) { try string(file, fmtstr[no_format_start..index]); } state = State.EscapeEnd; }, else => {}, }, State.Format => switch (ch) { '{' => { // Escaped { state = State.NoFormat; no_format_start = index; }, '}' => { switch (spec) { Spec.Hex => try hex(file, args[arg]), Spec.Address => try address(file, args[arg]), Spec.Char => try char(file, args[arg]), Spec.Default => try any(file, args[arg]), } arg += 1; state = State.NoFormat; no_format_start = index + 1; }, ':' => { state = State.FormatSpec; }, else => @compileError( "Unexpected Format chacter: " ++ fmtstr[index..index+1]), }, State.FormatSpec => switch (ch) { 'x' => { spec = Spec.Hex; state = State.Format; }, 'a' => { spec = Spec.Address; state = State.Format; }, 'c' => { spec = Spec.Char; state = State.Format; }, else => @compileError( "Unexpected Format chacter after ':': " ++ fmtstr[index..index+1]), }, State.EscapeEnd => switch (ch) { '}' => { // Escaped } state = State.NoFormat; no_format_start = index; }, else => @compileError( "Expected } for end brace escape, but found: " ++ fmtstr[index..index+1]), }, } } if (args.len != arg) { @compileError("Unused arguments"); } if (state != State.NoFormat) { @compileError("Incomplete format string: " ++ fmtstr); } if (no_format_start < fmtstr.len) { try string(file, fmtstr[no_format_start..fmtstr.len]); } } pub fn dump_memory(file: *File, ptr: usize, size: usize) FileError!void { // Print hex data like this: // VV group_sep // 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F // ^^ Byte ^ byte_sep Group^^^^^^^^^^^^^^^^^^^^^^^ const group_byte_count = 8; const byte_sep = " "; const group_size = group_byte_count * 2 + // Bytes ((group_byte_count * byte_sep.len) - 1); // byte_sep Between Bytes const group_count = 2; const group_sep = " "; const buffer_size = group_size * group_count + // Groups (group_count - 1) * group_sep.len + // group_sep Between Groups 1; // Newline var buffer: [buffer_size]u8 = undefined; var i: usize = 0; var buffer_pos: usize = 0; var byte_i: usize = 0; var group_i: usize = 0; var has_next = i < size; var print_buffer = false; while (has_next) { const next_i = i + 1; has_next = next_i < size; print_buffer = !has_next; { const new_pos = buffer_pos + 2; utils.byte_buffer(buffer[buffer_pos..new_pos], @intToPtr(*allowzero u8, ptr + i).*); buffer_pos = new_pos; } byte_i += 1; if (byte_i == group_byte_count) { byte_i = 0; group_i += 1; if (group_i == group_count) { group_i = 0; print_buffer = true; } else { for (group_sep[0..group_sep.len]) |b| { buffer[buffer_pos] = b; buffer_pos += 1; } } } else if (has_next) { for (byte_sep[0..byte_sep.len]) |b| { buffer[buffer_pos] = b; buffer_pos += 1; } } if (print_buffer) { buffer[buffer_pos] = '\n'; buffer_pos += 1; try string(file, buffer[0..buffer_pos]); buffer_pos = 0; print_buffer = false; } i = next_i; } } pub fn dump_bytes(file: *File, byteslice: []const u8) FileError!void { try dump_memory(file, @ptrToInt(byteslice.ptr), byteslice.len); } pub fn dump_raw_object(file: *File, comptime Type: type, value: *const Type) FileError!void { const size: usize = @sizeOf(Type); const ptr: usize = @ptrToInt(value); try format(file, "type: {} at {:a} size: {} data:\n", @typeName(Type), ptr, size); try dump_memory(file, ptr, size); }
0
repos/georgios
repos/georgios/kernel/memory.zig
const std = @import("std"); const georgios = @import("georgios"); const utils = @import("utils"); const kernel = @import("kernel.zig"); const print = @import("print.zig"); const MinBuddyAllocator = @import("buddy_allocator.zig").MinBuddyAllocator; const console_writer = kernel.console_writer; const platform = @import("platform.zig"); pub const AllocError = georgios.memory.AllocError; pub const FreeError = georgios.memory.FreeError; pub const MemoryError = georgios.memory.MemoryError; pub const Range = struct { start: usize = 0, size: usize = 0, pub fn from_bytes(bytes: []const u8) Range { return .{.start = @ptrToInt(bytes.ptr), .size = bytes.len}; } pub fn end(self: *const Range) usize { return self.start + self.size; } pub fn to_ptr(self: *const Range, comptime PtrType: type) PtrType { return @intToPtr(PtrType, self.start); } pub fn to_slice(self: *const Range, comptime Type: type) []Type { return self.to_ptr([*]Type)[0..self.size / @sizeOf(Type)]; } }; /// Used by the platform to provide what real memory can be used for the real /// memory allocator. pub const RealMemoryMap = struct { const FrameGroup = struct { start: usize, frame_count: usize, }; frame_groups: [64]FrameGroup = undefined, frame_group_count: usize = 0, total_frame_count: usize = 0, fn invalid(self: *RealMemoryMap) bool { return self.frame_group_count == 0 or self.total_frame_count == 0; } /// Directly add a frame group. fn add_frame_group_impl(self: *RealMemoryMap, start: usize, frame_count: usize) void { if ((self.frame_group_count + 1) >= self.frame_groups.len) { @panic("Too many frame groups!"); } self.frame_groups[self.frame_group_count] = FrameGroup{ .start = start, .frame_count = frame_count, }; self.frame_group_count += 1; self.total_frame_count += frame_count; } /// Given a memory range, add a frame group if there are frames that can /// fit in it. pub fn add_frame_group(self: *RealMemoryMap, start: usize, end: usize) void { const aligned_start = utils.align_up(start, platform.frame_size); const aligned_end = utils.align_down(end, platform.frame_size); if (aligned_start < aligned_end) { self.add_frame_group_impl(aligned_start, (aligned_end - aligned_start) / platform.frame_size); } } }; var alloc_debug = false; pub const Allocator = struct { alloc_impl: fn(*Allocator, usize, usize) AllocError![]u8, free_impl: fn(*Allocator, []const u8, usize) FreeError!void, pub fn alloc(self: *Allocator, comptime Type: type) AllocError!*Type { if (alloc_debug) print.string( "Allocator.alloc: " ++ @typeName(Type) ++ "\n"); const rv = @ptrCast(*Type, @alignCast( @alignOf(Type), (try self.alloc_impl(self, @sizeOf(Type), @alignOf(Type))).ptr)); if (alloc_debug) print.format( "Allocator.alloc: " ++ @typeName(Type) ++ ": {:a}\n", .{@ptrToInt(rv)}); return rv; } pub fn free(self: *Allocator, value: anytype) FreeError!void { const traits = @typeInfo(@TypeOf(value)).Pointer; const bytes = utils.to_bytes(value); if (alloc_debug) print.format("Allocator.free: " ++ @typeName(@TypeOf(value)) ++ ": {:a}\n", .{@ptrToInt(bytes.ptr)}); try self.free_impl(self, bytes, traits.alignment); } pub fn alloc_array( self: *Allocator, comptime Type: type, count: usize) AllocError![]Type { if (alloc_debug) print.format( "Allocator.alloc_array: [{}]" ++ @typeName(Type) ++ "\n", .{count}); if (count == 0) { return AllocError.ZeroSizedAlloc; } const rv = @ptrCast([*]Type, @alignCast(@alignOf(Type), (try self.alloc_impl(self, @sizeOf(Type) * count, @alignOf(Type))).ptr))[0..count]; if (alloc_debug) print.format("Allocator.alloc_array: [{}]" ++ @typeName(Type) ++ ": {:a}\n", .{count, @ptrToInt(rv.ptr)}); return rv; } pub fn free_array(self: *Allocator, array: anytype) FreeError!void { const traits = @typeInfo(@TypeOf(array)).Pointer; if (alloc_debug) print.format( "Allocator.free_array: [{}]" ++ @typeName(traits.child) ++ ": {:a}\n", .{array.len, @ptrToInt(array.ptr)}); try self.free_impl(self, utils.to_const_bytes(array), traits.alignment); } pub fn alloc_range(self: *Allocator, size: usize) AllocError!Range { if (alloc_debug) print.format("Allocator.alloc_range: {}\n", .{size}); if (size == 0) { return AllocError.ZeroSizedAlloc; } const rv = Range{ .start = @ptrToInt((try self.alloc_impl(self, size, 1)).ptr), .size = size}; if (alloc_debug) print.format("Allocator.alloc_range: {}: {:a}\n", .{size, rv.start}); return rv; } pub fn free_range(self: *Allocator, range: Range) FreeError!void { if (alloc_debug) print.format( "Allocator.free_range: {}: {:a}\n", .{range.size, range.start}); try self.free_impl(self, range.to_slice(u8), 1); } fn std_alloc(self: *Allocator, n: usize, ptr_align: u29, len_align: u29, ra: usize) ![]u8 { _ = len_align; _ = ra; return self.alloc_impl(self, n, ptr_align) catch return std.mem.Allocator.Error.OutOfMemory; } fn std_resize(self: *Allocator, buf: []u8, buf_align: u29, new_len: usize, len_align: u29, ret_addr: usize) ?usize { _ = self; _ = buf_align; _ = len_align; _ = ret_addr; // TODO if (new_len <= buf.len) { return new_len; } else { return null; } } fn std_free(self: *Allocator, buf: []u8, buf_align: u29, ret_addr: usize) void { _ = ret_addr; self.free_impl(self, buf, buf_align) catch return; } pub fn std_allocator(self: *Allocator) std.mem.Allocator { return std.mem.Allocator.init(self, std_alloc, std_resize, std_free); } }; pub const UnitTestAllocator = struct { const Self = @This(); allocator: Allocator = undefined, impl: utils.TestAlloc = undefined, alloc: std.mem.Allocator = undefined, pub fn init(self: *Self) void { self.impl = .{}; self.alloc = self.impl.alloc(); self.allocator.alloc_impl = Self.alloc; self.allocator.free_impl = Self.free; } pub fn done_no_checks(self: *Self) void { self.impl.deinit(.NoPanic); } pub fn done(self: *Self) void { self.impl.deinit(.Panic); } pub fn done_check_if(self: *Self, condition: *bool) void { if (condition.*) { self.done(); } else { self.done_no_checks(); } } pub fn alloc(allocator: *Allocator, size: usize, align_to: usize) AllocError![]u8 { const self = @fieldParentPtr(Self, "allocator", allocator); const align_u29 = @truncate(u29, align_to); const rv = self.alloc.allocBytes(align_u29, size, align_u29, @returnAddress()) catch return AllocError.OutOfMemory; // std.debug.print("alloc {x}: {}\n", .{@ptrToInt(rv.ptr), rv.len}); return rv; } pub fn free(allocator: *Allocator, value: []const u8, aligned_to: usize) FreeError!void { // std.debug.print("free {x}: {}\n", .{@ptrToInt(value.ptr), value.len}); const self = @fieldParentPtr(Self, "allocator", allocator); _ = self.alloc.rawFree( @intToPtr([*]u8, @ptrToInt(value.ptr))[0..value.len], @truncate(u29, aligned_to), @returnAddress()); } }; /// Used by the kernel to manage system memory pub const Manager = struct { const alloc_size = utils.Mi(1); const AllocImplType = MinBuddyAllocator(alloc_size); impl: platform.MemoryMgrImpl = .{}, total_frame_count: usize = 0, free_frame_count: usize = 0, alloc_range: Range = undefined, alloc_impl_range: Range = undefined, alloc_impl: *AllocImplType = undefined, alloc: *Allocator = undefined, big_alloc: *Allocator = undefined, /// To be called by the platform after it can give "map". pub fn init(self: *Manager, map: *RealMemoryMap) !void { print.debug_format( \\ - Initializing Memory System \\ - Start of kernel: \\ - Real: {:a} \\ - Virtual: {:a} \\ - End of kernel: \\ - Real: {:a} \\ - Virtual: {:a} \\ - Size of kernel is {} B ({} KiB) \\ - Frame Size: {} B ({} KiB) \\ , .{ platform.kernel_real_start(), platform.kernel_virtual_start(), platform.kernel_real_end(), platform.kernel_virtual_end(), platform.kernel_size(), platform.kernel_size() >> 10, platform.frame_size, platform.frame_size >> 10}); // Process RealMemoryMap if (map.invalid()) { @panic("RealMemoryMap is invalid!"); } print.debug_string(" - Frame Groups:\n"); for (map.frame_groups[0..map.frame_group_count]) |*i| { print.debug_format(" - {} Frames starting at {:a}\n", .{i.frame_count, i.start}); } // Initialize Platform Implementation // After this we should be able to manage all the memory on the system. self.impl.init(self, map); // List Memory const total_memory: usize = map.total_frame_count * platform.frame_size; const indent = if (print.debug_print) " - " else ""; print.format( "{}Total Available Memory: {} B ({} KiB/{} MiB/{} GiB)\n", .{ indent, total_memory, total_memory >> 10, total_memory >> 20, total_memory >> 30}); self.alloc_impl = try self.big_alloc.alloc(AllocImplType); try self.alloc_impl.init(@alignCast(AllocImplType.area_align, try self.big_alloc.alloc([alloc_size]u8))); self.alloc = &self.alloc_impl.allocator; kernel.alloc = self.alloc; kernel.big_alloc = self.big_alloc; } pub fn print_status(self: *Manager) void { const free_size = std.fmt.fmtIntSizeBin(self.free_frame_count * platform.frame_size); const total_size = std.fmt.fmtIntSizeBin(self.total_frame_count * platform.frame_size); try console_writer.print("{}/{} free frames totaling {}/{}\n", .{self.free_frame_count, self.total_frame_count, free_size, total_size}); } };
0
repos/georgios
repos/georgios/kernel/sync.zig
// Synchronization Interfaces const std = @import("std"); const kernel = @import("kernel.zig"); const print = @import("print.zig"); const threading = @import("threading.zig"); const List = @import("list.zig").List; const memory = @import("memory.zig"); pub const Error = memory.MemoryError; pub const Lock = struct { locked: bool = false, /// Try to set locked to true if it's false. Return true if we couldn't do that. pub fn lock(self: *Lock) bool { return @cmpxchgStrong(bool, &self.locked, false, true, .Acquire, .Monotonic) != null; } /// Try to acquire lock forever pub fn spin_lock(self: *Lock) void { while (@cmpxchgWeak(bool, &self.locked, false, true, .Acquire, .Monotonic) != null) {} } pub fn unlock(self: *Lock) void { if (@cmpxchgStrong(bool, &self.locked, true, false, .Release, .Monotonic) != null) { @panic("Lock.unlock: Already unlocked"); } } }; test "Lock" { var lock = Lock{}; try std.testing.expect(!lock.lock()); try std.testing.expect(lock.lock()); lock.unlock(); try std.testing.expect(!lock.lock()); try std.testing.expect(lock.lock()); lock.unlock(); lock.spin_lock(); try std.testing.expect(lock.lock()); lock.unlock(); } pub fn Semaphore(comptime Type: type) type { return struct { const Self = @This(); lock: Lock = .{}, value: Type = 1, queue: List(threading.Thread.Id) = undefined, pub fn init(self: *Self) void { self.queue = .{.alloc = kernel.alloc}; } pub fn wait(self: *Self) Error!void { self.lock.spin_lock(); if (self.value == 0) { const thread = kernel.threading_mgr.current_thread.?; try self.queue.push_back(thread.id); thread.state = .Wait; self.lock.unlock(); kernel.threading_mgr.yield(); } else { self.value -= 1; self.lock.unlock(); } } pub fn signal(self: *Self) Error!void { self.lock.spin_lock(); self.value += 1; // TODO: Threads that exit with signalling should be done by kernel. while (try self.queue.pop_front()) |tid| { if (kernel.threading_mgr.thread_list.find(tid)) |thread| { thread.state = .Run; break; } } self.lock.unlock(); } }; } var system_test_lock_1 = Lock{.locked = true}; var system_test_lock_2 = Lock{}; var system_test_semaphore = Semaphore(u8){}; pub fn system_test_thread_a() void { print.string("system_test_thread_a started\n"); if (system_test_lock_2.lock()) @panic("system_test_lock_2 failed to lock lock 2"); system_test_lock_1.spin_lock(); print.string("system_test_thread_a got lock 1, getting semaphore, freeing lock 2...\n"); system_test_lock_2.unlock(); system_test_lock_1.unlock(); system_test_semaphore.wait() catch @panic("system_test_thread_a system_test_semaphore.wait()"); print.string("system_test_thread_a got semaphore\n"); print.string("system_test_thread_a finished\n"); } pub fn system_test_thread_b() void { print.string("system_test_thread_b started, unlocking lock 1 and waiting on lock 2\n"); system_test_semaphore.wait() catch @panic("system_test_thread_b system_test_semaphore.wait()"); system_test_lock_1.unlock(); system_test_lock_2.spin_lock(); print.string("system_test_thread_b got lock 2, releasing semaphore\n"); system_test_lock_2.unlock(); system_test_semaphore.signal() catch @panic("system_test_thread_b system_test_semaphore.signal()"); print.string("system_test_thread_b finished\n"); } pub fn system_tests() !void { system_test_semaphore.init(); var thread_a = threading.Thread{.kernel_mode = true}; try thread_a.init(false); thread_a.entry = @ptrToInt(system_test_thread_a); var thread_b = threading.Thread{.kernel_mode = true}; try thread_b.init(false); thread_b.entry = @ptrToInt(system_test_thread_b); try kernel.threading_mgr.insert_thread(&thread_a); try kernel.threading_mgr.insert_thread(&thread_b); kernel.threading_mgr.wait_for_thread(thread_a.id); kernel.threading_mgr.wait_for_thread(thread_b.id); }
0
repos/georgios
repos/georgios/kernel/dispatching.zig
// =========================================================================== // Dispatching Ports and Interfaces // =========================================================================== // // Dispatching is the planned future method for IPC and generally how programs // will talk to the OS. The lowest layer of this are ports for passing bytes in // messages called a Dispatch to and from abstract places. Interfaces in OMG // IDL are used to generate abstract structs in Zig with helper code to pass // parameters of the abstract methods using a port. This can then interact // directly with kernel code. This should be somewhat easier then implementing // system calls using the current method. // // Later this should also be able to be used to communicate with other // threads and processes using queued messages. Accessing interfaces will // be done through the file system where objects (could be files or // directories) will present multiple possible interfaces. Current // influences for all this are Mach ports and to a lesser extend Fuchsia // interfaces and Plan 9 Styx. const std = @import("std"); const Allocator = std.mem.Allocator; const utils = @import("utils"); const georgios = @import("georgios"); pub const Error = georgios.DispatchError; pub const PortId = georgios.PortId; pub const Dispatch = georgios.Dispatch; pub const SendOpts = georgios.SendOpts; pub const RecvOpts = georgios.RecvOpts; pub const CallOpts = georgios.CallOpts; const kernel = @import("kernel.zig"); const console_writer = kernel.console_writer; const MemoryError = kernel.memory.MemoryError; const threading = kernel.threading; const Process = threading.Process; pub const Port = struct { send_impl: ?fn(port: *Port, dispatch: Dispatch, opts: SendOpts) Error!void = null, recv_impl: ?fn(port: *Port, src: PortId, opts: RecvOpts) Error!?Dispatch = null, call_impl: ?fn(self: *Port, dispatch: Dispatch, opts: CallOpts) Error!Dispatch = null, close_impl: ?fn(self: *Port) void, pub fn send(self: *Port, dispatch: Dispatch, opts: SendOpts) Error!void { if (self.send_impl) |send_impl| { return send_impl(self, dispatch, opts); } return Error.DispatchOpUnsupported; } pub fn recv(self: *Port, src: PortId, opts: RecvOpts) Error!?Dispatch { if (self.recv_impl) |recv_impl| { return recv_impl(self, src, opts); } return Error.DispatchOpUnsupported; } pub fn call(self: *Port, dispatch: Dispatch, opts: CallOpts) Error!Dispatch { if (self.call_impl) |call_impl| { return call_impl(self, dispatch, opts); } return Error.DispatchOpUnsupported; } pub fn close(self: *Port) void { return self.close_impl(self); } }; pub const Dispatcher = struct { const Ports = std.AutoHashMap(PortId, *Port); alloc: Allocator, process: *Process, next_id: PortId = georgios.FirstDynamicPort, ports: Ports, meta_port: Port, directory: georgios.Directory, // TODO: Temporarily connected to meta port pub fn init(self: *Dispatcher, alloc: Allocator, process: *Process) MemoryError!void { self.* = .{ .alloc = alloc, .process = process, .ports = Ports.init(alloc), .meta_port = .{ .send_impl = meta_port_send_impl, .close_impl = meta_port_close_impl, }, .directory = .{ ._port_id = georgios.MetaPort, ._create_impl = create_impl, ._unlink_impl = unlink_impl, }, }; try self.map_port_to(&self.meta_port, georgios.MetaPort); } fn map_port_to(self: *Dispatcher, port: *Port, id: PortId) MemoryError!void { try self.ports.putNoClobber(id, port); } pub fn map_port(self: *Dispatcher, port: *Port) Error!PortId { const id = self.next_id; try self.map_port_to(port, id); self.next_id += 1; return id; } fn get_port(self: *Dispatcher, id: PortId) Error!*Port { return self.ports.get(id) orelse Error.DispatchInvalidPort; } // TODO: Remove pub fn create_impl(dir: *georgios.Directory, path: []const u8, kind: georgios.fs.NodeKind) georgios.DispatchError!void { const self = @fieldParentPtr(Dispatcher, "directory", dir); _ = self; try console_writer.print("create_impl({s}) called\n", .{path}); if (kernel.threading_mgr.current_process) |p| { p.fs_submgr.create(path, kind) catch |e| { try console_writer.print("create_impl error: {s}\n", .{@errorName(e)}); }; } } // TODO: Remove pub fn unlink_impl(dir: *georgios.Directory, path: []const u8) georgios.DispatchError!void { const self = @fieldParentPtr(Dispatcher, "directory", dir); _ = self; try console_writer.print("unlink_impl({s}) called\n", .{path}); if (kernel.threading_mgr.current_process) |p| { p.fs_submgr.unlink(path) catch |e| { try console_writer.print("unlink_impl error: {s}\n", .{@errorName(e)}); }; } } fn meta_port_send_impl(port: *Port, dispatch: Dispatch, opts: SendOpts) Error!void { const self = @fieldParentPtr(Dispatcher, "meta_port", port); _ = opts; try self.directory._recv_value(dispatch); } fn meta_port_close_impl(port: *Port) void { _ = port; // Closing the met-aport doesn't do anything... } pub fn send(self: *Dispatcher, dispatch: Dispatch, opts: SendOpts) Error!void { try (try self.get_port(dispatch.dst)).send(dispatch, opts); } pub fn recv(self: *Dispatcher, src: PortId, opts: RecvOpts) Error!?Dispatch { return (try self.get_port(src)).recv(src, opts); // src or dst, or both? } pub fn call(self: *Dispatcher, dispatch: Dispatch, opts: CallOpts) Error!Dispatch { return (try self.get_port(dispatch.dst)).call(dispatch, opts); } };
0
repos/georgios
repos/georgios/kernel/elf.zig
// Executable and Linkable Format (ELF) // // File Format for Code // // For Reference See: // ELF Spec: http://refspecs.linuxbase.org/elf/elf.pdf // ELF Wikipedia Page: https://en.wikipedia.org/wiki/Executable_and_Linkable_Format // ELF on OSDev Wiki: https://wiki.osdev.org/ELF // man elf const georgios = @import("georgios"); const utils = @import("utils"); const io = @import("io.zig"); const print = @import("print.zig"); const Allocator = @import("memory.zig").Allocator; const List = @import("list.zig").List; const debug = false; const dump_segments = false; pub const Error = georgios.elf.Error; // TODO: Create Seperate 32 and 64 bit Versions ([ui]size -> [ui]32, [ui]64) const SectionHeader = packed struct { name_index: u32, // sh_name kind: u32, // sh_type flags: u32, // sh_flags address: usize, // sh_addr offset: isize, // sh_offset size: u32, // sh_size link: u32, // sh_link info: u32, // sh_info addralign: u32, // sh_addralign entsize: u32, // sh_entsize }; // TODO: Create Seperate 32 and 64 bit Versions ([ui]size -> [ui]32, [ui]64) const ProgramHeader = packed struct { kind: u32, // p_type offset: isize, // p_offset virtual_address: usize, // p_vaddr physical_address: usize, // p_paddr size_in_file: u32, // p_filesz size_in_memory: u32, // p_memsz flags: u32, // p_flags address_align: u32, // p_align }; const Magic = [4]u8; pub const expected_magic: Magic = [_]u8 {0x7f, 'E', 'L', 'F'}; // TODO: Create Seperate 32 and 64 bit Versions ([ui]size -> [ui]32, [ui]64) const Header = packed struct { pub const Class = enum(u8) { Invalid = 0, // ELFCLASSNONE Is32 = 1, // ELFCLASS32 Is64 = 2, // ELFCLASS64 }; pub const Data = enum(u8) { Invalid = 0, // ELFDATANONE Little = 1, // ELFDATA2LSB Big = 2, // ELFDATA2MSB }; pub const HeaderVersion = enum(u8) { Invalid = 0, // EV_NONE Current = 1, // EV_CURRENT }; pub const ObjectType = enum(u16) { None = 0, // ET_NONE Relocatable = 1, // ET_REL Executable = 2, // ET_EXEC Shared = 3, // ET_DYN CoreDump = 4, // ET_CORE }; pub const Machine = enum(u16) { None = 0x00, // ET_NONE X86_32 = 0x03, // ET_386 X86_64 = 0x3e, Arm32 = 0x28, Arm64 = 0xb7, RiscV = 0xf3, // There are others, but I'm not going to put them in. }; pub const ObjectVersion = enum(u32) { Invalid = 0, // EV_NONE Current = 1, // EV_CURRENT }; // e_ident magic: Magic, // EI_MAG0 - EI_MAG3 class: Class, // EI_CLASS data: Data, // EI_DATA header_version: HeaderVersion, // EI_VERSION unused_abi_os: u8, // EI_OSABI unused_abi_version: u8, //EI_ABIVERSION // TODO: This adds 8 to the size of the struct, not 7. Retest with zig master. // reserved: [7]u8, // EI_PAD reserved0: u8, reserved1: u8, reserved2: u8, reserved3: u8, reserved4: u8, reserved5: u8, reserved6: u8, object_type: ObjectType, // e_type machine: Machine, // e_machine object_version: ObjectVersion, // e_version entry: usize, // e_entry program_header_offset: isize, // e_phoff section_header_offset: isize, // e_shoff flags: u32, // e_flags header_size: u16, // e_ehsize program_header_entry_size: u16, // e_phentsize program_header_entry_count: u16, // e_phnum section_header_entry_size: u16, // e_shentsize section_header_entry_count: u16, // e_shnum section_header_string_table_index: u16, // e_shstrndx pub fn verify_elf(self: *const Header) Error!void { const invalid = !utils.memory_compare(self.magic[0..], expected_magic[0..]) or !utils.valid_enum(Class, self.class) or self.class == .Invalid or !utils.valid_enum(Data, self.data) or self.data == .Invalid or !utils.valid_enum(HeaderVersion, self.header_version) or self.header_version == .Invalid or !utils.valid_enum(ObjectVersion, self.object_version) or self.object_version == .Invalid; if (invalid) { return Error.InvalidElfFile; } } pub fn verify_compatible(self: *const Header) Error!void { // TODO: Make machine depend on platform and other checks if (self.machine != .X86_32) { return Error.InvalidElfPlatform; } } pub fn verify_executable(self: *const Header) Error!void { try self.verify_elf(); if (self.object_type != .Executable) { return Error.InvalidElfObjectType; } try self.verify_compatible(); } }; pub const Object = struct { pub const Segment = struct { const WhatKind = enum { Data, UndefinedMemory, }; const What = union(WhatKind) { Data: []u8, UndefinedMemory: usize, }; what: What = undefined, address: usize, pub fn teardown(self: *Segment, alloc: *Allocator) !void { switch (self.what) { .Data => |data| try alloc.free_array(data), else => {}, } } pub fn size(self: *const Segment) usize { return switch (self.what) { .Data => |data| data.len, .UndefinedMemory => |size| size, }; } }; pub const Segments = List(Segment); alloc: *Allocator, data_alloc: *Allocator, header: Header = undefined, section_headers: []SectionHeader = undefined, program_headers: []ProgramHeader = undefined, segments: Segments = undefined, pub fn from_file(alloc: *Allocator, data_alloc: *Allocator, file: *io.File) !Object { var object = Object{.alloc = alloc, .data_alloc = data_alloc}; object.segments = Segments{.alloc = alloc}; errdefer object.teardown() catch unreachable; // Read Header _ = try file.read(utils.to_bytes(&object.header)); if (debug) print.format("Header Size: {}\n", .{@as(usize, @sizeOf(Header))}); try object.header.verify_executable(); if (debug) print.format("Entry: {:a}\n", .{@as(usize, @sizeOf(Header))}); // Read Section Headers if (debug) print.format("Section Header Count: {}\n", .{object.header.section_header_entry_count}); { _ = try file.seek( @intCast(isize, object.header.section_header_offset), .FromStart); const count = @intCast(usize, object.header.section_header_entry_count); const size = @intCast(usize, object.header.section_header_entry_size); const skip = @intCast(isize, size - @sizeOf(SectionHeader)); object.section_headers = try alloc.alloc_array(SectionHeader, count); for (object.section_headers) |*section_header| { _ = try file.read(utils.to_bytes(section_header)); _ = try file.seek(skip, .FromHere); } } for (object.section_headers) |*section_header| { if (debug) print.format("section: kind: {} offset: {:x} size: {:x}\n", .{ section_header.kind, @bitCast(usize, section_header.offset), section_header.size}); } // Read Program Headers if (debug) print.format("Program Header Count: {}\n", .{object.header.program_header_entry_count}); { _ = try file.seek(@intCast(isize, object.header.program_header_offset), .FromStart); const count = @intCast(usize, object.header.program_header_entry_count); const size = @intCast(usize, object.header.program_header_entry_size); const skip = @intCast(isize, size - @sizeOf(ProgramHeader)); object.program_headers = try alloc.alloc_array(ProgramHeader, count); for (object.program_headers) |*program_header| { _ = try file.read(utils.to_bytes(program_header)); _ = try file.seek(skip, .FromHere); } } for (object.program_headers) |*program_header| { if (debug) print.format("program: kind: {} offset: {:x} " ++ "size in file: {:x} size in memory: {:x}\n", .{ program_header.kind, @bitCast(usize, program_header.offset), program_header.size_in_file, program_header.size_in_memory}); // Read the Program // TODO: Remove/Make More Proper? if (program_header.kind == 0x1) { if (debug) print.format( "segment at {} kind {} file size {} memory size {}\n", .{ program_header.virtual_address, program_header.kind, program_header.size_in_file, program_header.size_in_memory, }); if (program_header.size_in_file > program_header.size_in_memory) { return Error.InvalidElfFile; } var address = program_header.virtual_address; var left = program_header.size_in_memory; if (program_header.size_in_file > 0) { const segment = Segment{ .address = address, .what = Segment.What{ .Data = try data_alloc.alloc_array(u8, program_header.size_in_file) }, }; _ = try file.seek(@intCast(isize, program_header.offset), .FromStart); _ = try file.read_or_error(segment.what.Data); if (dump_segments) print.dump_bytes(segment.what.Data); try object.segments.push_back(segment); left -= program_header.size_in_file; address += program_header.size_in_file; } if (left > 0) { try object.segments.push_back( .{.address = address, .what = Segment.What{.UndefinedMemory = left}}); } } } if (object.segments.len == 0) { print.string("No LOADs in ELF!\n"); return Error.InvalidElfFile; } return object; } pub fn teardown(self: *Object) !void { try self.alloc.free_array(self.section_headers); try self.alloc.free_array(self.program_headers); var iter = self.segments.iterator(); while (iter.next()) |*segment| { try segment.teardown(self.data_alloc); } try self.segments.clear(); } };
0
repos/georgios
repos/georgios/kernel/platform.zig
const builtin = @import("builtin"); pub const impl = switch(builtin.cpu.arch) { // x86_32 .i386 => @import("platform/platform.zig"), else => @compileError("Architecture Not Supported!"), }; pub const frame_size = impl.frame_size; pub const page_size = impl.page_size; pub const init = impl.init; pub const setup_devices = impl.setup_devices; pub const panic = impl.panic; pub const kernel_real_start = impl.kernel_real_start; pub const kernel_real_end = impl.kernel_real_end; pub const kernel_virtual_start = impl.kernel_virtual_start; pub const kernel_virtual_end = impl.kernel_virtual_end; pub const kernel_size = impl.kernel_size; pub const kernel_to_real = impl.kernel_to_real; pub const kernel_to_virtual = impl.kernel_to_virtual; pub const kernel_range_real_start_available = impl.kernel_range_real_start_available; pub const kernel_range_virtual_start_available = impl.kernel_range_virtual_start_available; pub const shutdown = impl.shutdown; pub const halt_forever = impl.halt_forever; pub const idle = impl.idle; pub const Memory = impl.Memory; pub const MemoryMgrImpl = impl.MemoryMgrImpl; pub const enable_interrupts = impl.enable_interrupts; pub const disable_interrupts = impl.disable_interrupts; pub const Time = impl.Time; pub const time = impl.time; pub const seconds_to_time = impl.seconds_to_time; pub const milliseconds_to_time = impl.milliseconds_to_time;
0
repos/georgios
repos/georgios/kernel/gpt.zig
const std = @import("std"); const bytesAsSlice = std.mem.bytesAsSlice; const utils = @import("utils"); const Guid = utils.Guid; const io = @import("io.zig"); const constant_guids = @import("constant_guids.zig"); pub const Error = error { InvalidMbr, InvalidGptHeader, } || Guid.Error || io.FileError; pub const Mbr = struct { const Part = packed struct { status: u8, chs_start: u24, partition_type: u8, chs_end: u24, lba_start: u32, sector_count: u32, }; const magic: u16 = 0xaa55; const gpt_protective_type: u8 = 0xEE; signature: u32 = undefined, partitions: [4]Part = undefined, gpt_protective: bool = undefined, pub fn new(block: []const u8) Error!Mbr { var mbr = Mbr{}; // Check MBR "Boot Signature" (magic) if (bytesAsSlice(u16, block)[255] != magic) { return Error.InvalidMbr; } mbr.signature = bytesAsSlice(u32, block)[110]; const partitions = @ptrCast([*]const Part, @alignCast(@alignOf(Part), &block[446]))[0..4]; for (partitions) |*partition, i| { mbr.partitions[i] = partition.*; } mbr.gpt_protective = partitions[0].partition_type == gpt_protective_type; return mbr; } }; pub const Partition = struct { type_guid: Guid, start: io.AddressType, end: io.AddressType, pub fn is_linux(self: *const Partition) bool { return self.type_guid.equals(&constant_guids.linux_partition_type); } }; pub const Disk = struct { const magic = "EFI PART"; block_store: *io.BlockStore = undefined, guid: Guid = undefined, partition_entries_lba: io.AddressType = undefined, partition_entry_size: usize = undefined, pub fn new(block_store: *io.BlockStore) Error!Disk { var disk = Disk{.block_store = block_store}; // Check to see if there's a MBR and it says this is a GPT disk. var mbr_block = io.Block{.address = 0}; try block_store.create_block(&mbr_block); try block_store.read_block(&mbr_block); defer block_store.destroy_block(&mbr_block); const mbr = try Mbr.new(mbr_block.data.?); if (!mbr.gpt_protective) { return Error.InvalidGptHeader; } // Get GPT Header Block var gpt_block = io.Block{.address = 1}; try block_store.create_block(&gpt_block); try block_store.read_block(&gpt_block); defer block_store.destroy_block(&gpt_block); const block = gpt_block.data.?; // Check Magic for (block[0..magic.len]) |*ptr, i| { if (ptr.* != magic[i]) { return Error.InvalidGptHeader; } } // Get Info try disk.guid.from_ms(block[0x38..0x48]); disk.partition_entries_lba = @as(io.AddressType, bytesAsSlice(u64, block[0x48..0x50])[0]); disk.partition_entry_size = bytesAsSlice(u32, block[0x54..0x58])[0]; return disk; } pub fn partitions(self: *const Disk) Error!PartitionIterator { var it = PartitionIterator{ .block_store = self.block_store, .block = io.Block{.address = self.partition_entries_lba}, .entry_size = self.partition_entry_size, }; try self.block_store.create_block(&it.block); try self.block_store.read_block(&it.block); return it; } pub const PartitionIterator = struct { offset: usize = 0, block_store: *io.BlockStore, block: io.Block, entry_size: usize, pub fn next(self: *PartitionIterator) Error!?Partition { var partition: Partition = undefined; if (self.offset >= self.block.data.?.len) { self.block.address += 1; try self.block_store.read_block(&self.block); self.offset = 0; } const id_offset = self.offset + 16; try partition.type_guid.from_ms(self.block.data.?[self.offset..id_offset]); if (partition.type_guid.is_null()) { return null; } const start_lba_offset = id_offset + 16; const end_lba_offset = start_lba_offset + 8; partition.start = @as(io.AddressType, bytesAsSlice(u64, self.block.data.?[start_lba_offset..end_lba_offset])[0]); const attributes_offset = end_lba_offset + 8; partition.end = @as(io.AddressType, bytesAsSlice(u64, self.block.data.?[end_lba_offset..attributes_offset])[0]); const name_offset = attributes_offset + 8; const supported_end = name_offset + 72; // Add any ammount we are over the entry size self.offset = supported_end + self.entry_size - (supported_end - self.offset); return partition; } pub fn done(self: *PartitionIterator) void { self.block_store.destroy_block(&self.block); } }; };
0
repos/georgios
repos/georgios/kernel/constant_guids.zig
// Generated by scripts/codegen/constant_guids.py const Guid = @import("utils").Guid; pub const nil = Guid{.data= // 00000000-0000-0000-0000-000000000000 [_]u8{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}; pub const linux_partition_type = Guid{.data= // 0fc63daf-8483-4772-8e79-3d69d8477de4 [_]u8{0x0f, 0xc6, 0x3d, 0xaf, 0x84, 0x83, 0x47, 0x72, 0x8e, 0x79, 0x3d, 0x69, 0xd8, 0x47, 0x7d, 0xe4}};
0
repos/georgios
repos/georgios/kernel/kernel.zig
const std = @import("std"); const builtin = @import("builtin"); const build_options = @import("build_options"); const no_max = std.math.maxInt(usize); const utils = @import("utils"); const georgios = @import("georgios"); pub const console_writer = georgios.get_console_writer(); pub const Console = georgios.Console; pub const platform = @import("platform.zig"); pub const fprint = @import("fprint.zig"); pub const print = @import("print.zig"); pub const memory = @import("memory.zig"); pub const io = @import("io.zig"); pub const elf = @import("elf.zig"); pub const devices = @import("devices.zig"); pub const threading = @import("threading.zig"); pub const fs = @import("fs.zig"); pub const sync = @import("sync.zig"); pub const keys = @import("keys.zig"); pub const builtin_font_data = @import("builtin_font_data.zig"); pub const BitmapFont = @import("BitmapFont.zig"); pub const List = @import("list.zig").List; pub const dispatching = @import("dispatching.zig"); pub var panic_message: []const u8 = ""; pub fn panic(msg: []const u8, trace: ?*std.builtin.StackTrace) noreturn { quick_debug_ready = false; // Probably won't be able to run this anymore print.format("panic: {}\n", .{msg}); platform.impl.ps2.anykey(); panic_message = msg; if (trace) |t| { print.format("index: {}\n", .{t.index}); for (t.instruction_addresses) |addr| { if (addr == 0) break; print.format(" - {:a}\n", .{addr}); } } else { print.string("No Stack Trace\n"); } platform.panic(msg, trace); } pub var memory_mgr = memory.Manager{}; pub var device_mgr = devices.Manager{}; pub var threading_mgr = threading.Manager{}; pub var filesystem_mgr: fs.Manager = undefined; pub var alloc: *memory.Allocator = undefined; pub var big_alloc: *memory.Allocator = undefined; pub var console: *Console = undefined; pub var console_file = io.File{}; // TODO: This should be builtin into the disk pub var disk_cache_block_store: io.MemoryBlockStore = .{}; pub var builtin_font: BitmapFont = undefined; pub var ram_disk: fs.RamDisk = undefined; fn platform_init() !void { print.init(&console_file, build_options.debug_log); try platform.init(); quick_debug_ready = true; } fn get_ext2_root() ?*fs.Vfilesystem { if (device_mgr.get(([_][]const u8{"ata0", "disk0"})[0..])) |disk_dev| { if (disk_dev.as_block_store()) |direct_block_store| { var use_block_store: *io.BlockStore = undefined; if (build_options.direct_disk) { use_block_store = direct_block_store; } else { disk_cache_block_store.init_as_cache(alloc.std_allocator(), direct_block_store, 128); use_block_store = &disk_cache_block_store.block_store_if; } if (fs.get_root(alloc, use_block_store)) |root_fs| { return root_fs; } } } print.string(" - No Disk Found\n"); return null; } fn init() !void { try platform_init(); // Filesystem ram_disk.init(alloc, big_alloc, platform.page_size); const ext2_root = get_ext2_root(); const ram_disk_root = &ram_disk.vfs; filesystem_mgr.init(alloc, ext2_root orelse ram_disk_root); if (ext2_root != null) { try filesystem_mgr.mount(ram_disk_root, "/ramdisk"); } } const ExecError = georgios.ExecError; pub fn exec_elf(info: *const georgios.ProcessInfo) ExecError!threading.Process.Id { const process = try threading_mgr.new_process(info); // print.format("exec: {} {} args:\n", .{info.path, info.args.len}); // for (info.args) |arg| { // print.format("- {}\n", .{arg}); // } var file_node = try filesystem_mgr.resolve_file(info.path, .{}); var file_ctx = try file_node.open_new_context(.{.ReadOnly = .{}}); defer file_ctx.close(); const file_io = try file_ctx.get_io_file(); var elf_object = try elf.Object.from_file(alloc, big_alloc, file_io); var segments = elf_object.segments.iterator(); var dynamic_memory_start: usize = 0; while (segments.next()) |segment| { switch (segment.what) { .Data => |data| try process.address_space_copy(segment.address, data), .UndefinedMemory => |size| try process.address_space_set(segment.address, 0, size), } dynamic_memory_start = @maximum(segment.address + segment.size(), dynamic_memory_start); } process.entry = elf_object.header.entry; process.dynamic_memory.start = utils.align_up(dynamic_memory_start, platform.page_size); // print.format("dynamic: {:a}", .{process.dynamic_memory.start}); try elf_object.teardown(); try threading_mgr.start_process(process); return process.id; } const shell = "/bin/shell.elf"; pub fn exec(info: *const georgios.ProcessInfo) ExecError!threading.Process.Id { const std_alloc = alloc.std_allocator(); var shebang_info: ?georgios.ProcessInfo = null; defer { if (shebang_info) |*si| { std_alloc.free(si.path); std_alloc.free(si.args); } } // Check for #! or ELF magic { var file_node = try filesystem_mgr.resolve_file(info.path, .{}); var file_ctx = try file_node.open_new_context(.{.ReadOnly = .{}}); defer file_ctx.close(); const file_io = try file_ctx.get_io_file(); const shebang = "#!"; var buffer: [@maximum(shebang.len, elf.expected_magic.len)]u8 = undefined; const bytes = buffer[0..try file_io.read(buffer[0..])]; if (utils.starts_with(bytes, shebang[0..])) { // Get program from shebang var al = std.ArrayList(u8).init(std_alloc); defer al.deinit(); _ = try file_io.seek(shebang.len, .FromStart); try file_io.reader().readUntilDelimiterArrayList(&al, '\n', no_max); // Make new args with original path at start const new_args = try std_alloc.alloc([]const u8, info.args.len + 1); new_args[0] = info.path; for (info.args) |arg, i| { new_args[i + 1] = arg; } shebang_info = .{ .path = al.toOwnedSlice(), .name = info.name, .args = new_args, .kernel_mode = info.kernel_mode, }; } else if (!utils.starts_with(bytes, elf.expected_magic[0..])) { return ExecError.InvalidElfFile; } } return exec_elf(if (shebang_info) |*si| si else info); } fn run() !void { try init(); if (!build_options.run_rc) { return; } print.string("\x1bc"); // Reset Console // try @import("sync.zig").system_tests(); try device_mgr.print_tree(console_writer); const init_info: georgios.ProcessInfo = .{.path = "/etc/init"}; const init_exit_info = try threading_mgr.wait_for_process(try exec(&init_info)); print.format("INIT: {}\n", .{init_exit_info}); } var quick_debug_ready = false; // Run at anytime after platform init with Ctrl-Alt-Shift-D pub fn quick_debug() void { if (!quick_debug_ready) return; print.string("\nSTART QUICK DEBUG =============================================================\n"); print.format("{} processes {} threads\n", .{threading_mgr.process_list.len(), threading_mgr.thread_list.len()}); memory_mgr.print_status(); print.string("END QUICK DEBUG ===============================================================\n"); } pub fn kernel_main() void { if (run()) |_| {} else |e| { panic(@errorName(e), @errorReturnTrace()); } print.string("Done\n"); if (build_options.halt_when_done) { print.string("Kernel configured to halt forever instead of shutdown...\n"); platform.halt_forever(); } else { print.string("Shutting down...\n"); platform.shutdown(); } }
0
repos/georgios
repos/georgios/kernel/buddy_allocator.zig
// Buddy System Allocation Implementation // // Based on http://bitsquid.blogspot.com/2015/08/allocation-adventures-3-buddy-allocator.html // // Also see prototype at scripts/prototypes/buddy.py // // For Reference See: // https://en.wikipedia.org/wiki/Buddy_memory_allocation // // TODO: Make Resizable const std = @import("std"); const memory = @import("memory.zig"); const Allocator = memory.Allocator; const MemoryError = memory.MemoryError; const AllocError = memory.AllocError; const FreeError = memory.FreeError; const utils = @import("utils"); const print = @import("print.zig"); const BlockStatus = enum(u2) { Invalid = 0, Split, Free, Used, }; const Error = error { WrongBlockStatus, CantReserveAlreadyUsed, } || utils.Error; const FreeBlock = struct { const ConstPtr = *allowzero const FreeBlock; const Ptr = *allowzero FreeBlock; prev: ?Ptr, next: ?Ptr, }; const free_block_size: usize = @sizeOf(FreeBlock); const FreeBlockKind = enum { InSelf, InManagedArea, }; pub fn MinBuddyAllocator(max_size_arg: usize) type { return BuddyAllocator(max_size_arg, free_block_size, .InManagedArea); } // max_size_arg is the size of the managed area and therefore the size of the // largest possible allocation. min_size is the size of the smallest posible. // allocation kind is where to store the free block list. pub fn BuddyAllocator(max_size_arg: usize, min_size: usize, kind: FreeBlockKind) type { if (kind == .InManagedArea and min_size < free_block_size) { @panic("With InManagedArea BuddyAllocator min_size must be >= free_block_size"); } return struct { const Self = @This(); pub const max_size: usize = max_size_arg; const max_level_block_count = max_size / min_size; const level_count: usize = utils.int_log2(usize, max_level_block_count) + 1; const unique_block_count: usize = level_block_count(level_count) - 1; const FreeBlocks = struct { lists: [level_count]?FreeBlock.Ptr = .{null} ** level_count, pub fn get(self: *FreeBlocks, level: usize) Error!?FreeBlock.Ptr { if (level >= level_count) { return Error.OutOfBounds; } return self.lists[level]; } pub fn push(self: *FreeBlocks, level: usize, block: FreeBlock.Ptr) Error!void { if (level >= level_count) { return Error.OutOfBounds; } const current_maybe = self.lists[level]; if (current_maybe) |current| { current.prev = block; } block.next = current_maybe; block.prev = null; self.lists[level] = block; } // TODO: Unused, is it even needed? pub fn pop(self: *FreeBlocks, level: usize) Error!?FreeBlock.Ptr { if (level >= level_count) { return Error.OutOfBounds; } const current_maybe = self.lists[level]; if (current_maybe) |current| { self.lists[level] = current.next; if (current.next) |next| { next.prev = null; } } return current_maybe; } pub fn remove_block(self: *FreeBlocks, level: usize, block: FreeBlock.ConstPtr) void { if (block.prev) |prev| { prev.next = block.next; } else { self.lists[level] = block.next; } if (block.next) |next| { next.prev = block.prev; } } fn dump_status(ba: *const Self, level: usize, index: usize) u8 { return switch (ba.block_statuses.get(unique_id(level, index)) catch unreachable) { .Invalid => 'I', .Split => 'S', .Free => 'F', .Used => 'U', }; } fn dump(self: *FreeBlocks, ba: *const Self) void { var level: usize = 0; while (level < level_count) { // Overview { std.debug.print("|", .{}); const space = (level_to_block_size(level) / min_size - 1) * 2; const count = level_block_count(level); var index: usize = 0; while (index < count) { std.debug.print("{c}", .{dump_status(ba, level, index)}); var i: usize = 0; while (i < space) { std.debug.print(" ", .{}); i += 1; } std.debug.print("|", .{}); index += 1; } } // List std.debug.print(" L{} ", .{level}); var block_maybe = self.lists[level]; while (block_maybe) |block| { const index = ba.block_to_index(level, block); std.debug.print("-> [{}({c})]", .{index, dump_status(ba, level, index)}); block_maybe = block.next; } std.debug.print("\n", .{}); level += 1; } } }; const FreeBlocksInSelf = if (kind == .InSelf) [max_level_block_count]FreeBlock else void; pub const area_align: u29 = if (kind == .InManagedArea) @sizeOf(FreeBlock) else 1; pub const Area = []align(area_align) u8; allocator: Allocator = undefined, start: usize = undefined, free_blocks: FreeBlocks = undefined, free_blocks_in_self: FreeBlocksInSelf = undefined, block_statuses: utils.PackedArray(BlockStatus, unique_block_count) = undefined, pub fn init(self: *Self, area: Area) Error!void { self.allocator = Allocator{ .alloc_impl = alloc, .free_impl = free, }; if (area.len < max_size) { return Error.NotEnoughDestination; } self.start = @ptrToInt(area.ptr); self.free_blocks = .{}; self.free_blocks.push(0, self.index_to_block(0, 0)) catch unreachable; self.block_statuses.reset(); self.block_statuses.set(0, .Free) catch unreachable; } fn level_block_count(level: usize) usize { return @as(usize, 1) << @truncate(utils.UsizeLog2Type, level); } fn level_to_block_size(level: usize) usize { return max_size >> @truncate(utils.UsizeLog2Type, level); } fn size_to_level(size: usize) usize { const target_size = @maximum(min_size, utils.pow2_round_up(usize, size)); return level_count - utils.int_log2(usize, target_size / min_size) - 1; } fn unique_id(level: usize, index: usize) usize { return level_block_count(level) + index - 1; } fn get_level_index(input_index: usize, level: usize, to_max: bool) usize { const shift = @intCast(utils.UsizeLog2Type, level_count - 1 - level); return if (to_max) input_index << shift else input_index >> shift; } fn in_self_offset(block: usize, start: usize) usize { return (block - start) / free_block_size; } fn block_to_index(self: *const Self, level: usize, block: FreeBlock.ConstPtr) usize { const b = @ptrToInt(block); const rv = switch (kind) { .InManagedArea => (b - self.start) / level_to_block_size(level), .InSelf => get_level_index( in_self_offset(b, @ptrToInt(&self.free_blocks_in_self[0])), level, false), }; return rv; } fn get_address(self: *Self, level: usize, index: usize) usize { return self.start + index * level_to_block_size(level); } fn get_block_raw(self: *Self, raw: usize) FreeBlock.Ptr { return switch (kind) { .InManagedArea => @intToPtr(FreeBlock.Ptr, raw), .InSelf => @ptrCast(FreeBlock.Ptr, &self.free_blocks_in_self[raw]), }; } fn index_to_block(self: *Self, level: usize, index: usize) FreeBlock.Ptr { return self.get_block_raw(switch (kind) { .InManagedArea => self.get_address(level, index), .InSelf => get_level_index(index, level, true), }); } fn address_to_block(self: *Self, address: usize) FreeBlock.Ptr { return self.get_block_raw(switch (kind) { .InManagedArea => blk: { if (address % free_block_size != 0) { @panic("address_to_block address isn't aligned to FreeBlock"); } break :blk address; }, .InSelf => in_self_offset(address, self.start), }); } fn get_buddy_index(index: usize) usize { return if ((index % 2) == 1) (index - 1) else (index + 1); } fn assert_unique_id(self: *Self, level: usize, index: usize, expected_status: BlockStatus) Error!usize { const id = unique_id(level, index); const status = try self.block_statuses.get(id); if (status != expected_status) { return Error.WrongBlockStatus; } return id; } fn split(self: *Self, level: usize, index: usize) Error!void { const this_unique_id = try self.assert_unique_id( level, index, .Free); const this_ptr = self.index_to_block(level, index); const new_level: usize = level + 1; const new_index = index << 1; const buddy_index = new_index + 1; const buddy_ptr = self.index_to_block(new_level, buddy_index); // Update Free Blocks self.free_blocks.remove_block(level, this_ptr); try self.free_blocks.push(new_level, buddy_ptr); try self.free_blocks.push(new_level, this_ptr); // Update Statuses try self.block_statuses.set(this_unique_id, BlockStatus.Split); try self.block_statuses.set( unique_id(new_level, new_index), BlockStatus.Free); try self.block_statuses.set( unique_id(new_level, buddy_index), BlockStatus.Free); } pub fn addr_in_range(self: *const Self, addr: usize) bool { return addr >= self.start and addr <= (self.start - 1 + max_size); } pub fn slice_in_range(self: *const Self, range: []u8) bool { const addr = @ptrToInt(range.ptr); return self.addr_in_range(addr) and !(range.len > 1 and !self.addr_in_range(addr + range.len - 1)); } fn reserve_block(self: *Self, level: usize, block: FreeBlock.Ptr) usize { self.free_blocks.remove_block(level, block); const index = self.block_to_index(level, block); const id = unique_id(level, index); self.block_statuses.set(id, .Used) catch unreachable; return index; } pub fn alloc(allocator: *Allocator, size: usize, align_to: usize) AllocError![]u8 { _ = align_to; const self = @fieldParentPtr(Self, "allocator", allocator); // TODO: Do we have to do something with align_to? if (size > max_size) { return AllocError.OutOfMemory; } const target_level = size_to_level(size); // Figure out how many (if any) levels we need to split a block in // to get a free block in our target level. var block: FreeBlock.Ptr = undefined; var level = target_level; while (true) { if (self.free_blocks.get(level) catch unreachable) |b| { block = b; break; } if (level == 0) { return AllocError.OutOfMemory; } level -= 1; } // If we need to split blocks, do that var split_level = level; while (split_level != target_level) { self.split(split_level, self.block_to_index(split_level, block)) catch unreachable; split_level += 1; block = (self.free_blocks.get(split_level) catch unreachable).?; } // Reserve it const index = self.reserve_block(target_level, block); const result = switch (kind) { .InManagedArea => @ptrCast([*]u8, block), .InSelf => @intToPtr([*]u8, self.get_address(target_level, index)), }[0..size]; if (!self.slice_in_range(result)) { @panic("invalid alloc address"); } return result; } fn merge(self: *Self, level: usize, index: usize) Error!void { if (level == 0) { return Error.OutOfBounds; } const buddy_index = get_buddy_index(index); const new_level = level - 1; const new_index = index >> 1; // Assert existing blocks are free and new/parent block is split const this_unique_id = try self.assert_unique_id(level, index, .Free); const buddy_unique_id = try self.assert_unique_id(level, buddy_index, .Free); const new_unique_id = try self.assert_unique_id(new_level, new_index, .Split); // Remove pointers to the old blocks const this_ptr = self.index_to_block(level, index); const buddy_ptr = self.index_to_block(level, buddy_index); self.free_blocks.remove_block(level, this_ptr); self.free_blocks.remove_block(level, buddy_ptr); // Push New Block into List try self.free_blocks.push(new_level, self.index_to_block(new_level, new_index)); // Set New Statuses try self.block_statuses.set(this_unique_id, .Invalid); try self.block_statuses.set(buddy_unique_id, .Invalid); try self.block_statuses.set(new_unique_id, .Free); } const BlockStatusIter = struct { ba: *Self, block: FreeBlock.Ptr, level: usize = level_count, index: usize = undefined, id: ?usize = null, fn next(self: *BlockStatusIter) ?BlockStatus { if (self.level == 0) return null; self.level -= 1; self.index = self.ba.block_to_index(self.level, self.block); self.block = self.ba.index_to_block(self.level, self.index); // Allow parent shift const id = unique_id(self.level, self.index); self.id = id; return self.ba.block_statuses.get(id) catch unreachable; } }; fn free(allocator: *Allocator, value: []const u8, aligned_to: usize) FreeError!void { _ = aligned_to; const self = @fieldParentPtr(Self, "allocator", allocator); // TODO: Check aligned_to makes sense? if (value.len > max_size) return FreeError.InvalidFree; const address = @ptrToInt(value.ptr); const block = self.address_to_block(address); // TODO: This will issue a false positive if the allocated size // does not equal the size passed to free somewhat intentionally. // For example using std.ArrayList can have some extra capacity in // the allocation and freeing the result of toOwnedSlice can have a // different size from the original allocation. if (value.len > 0 and false) { const level = size_to_level(value.len); const index = self.block_to_index(level, block); const id = unique_id(level, index); const status = self.block_statuses.get(id) catch unreachable; if (status != .Used) { print.format( "Error: BuddyAllocator.free will return InvalidFree for {:a} " ++ "size {} because its block at level {} index {} has status {}\n", .{address, value.len, level, index, status}); } } // else if it's zero-sized then it probably came from something like C // free where we don't get the size. // Find the level var iter = BlockStatusIter{.ba = self, .block = block}; while (iter.next()) |status| { if (status == .Used) { break; } } const id = iter.id orelse return FreeError.InvalidFree; var level = iter.level; var index = iter.index; // Insert Block into List and Mark as Free self.free_blocks.push(level, block) catch unreachable; self.block_statuses.set(id, .Free) catch unreachable; // Merge Until Buddy isn't Free or Level Is 0 while (level > 0) { const buddy_index = get_buddy_index(index); const buddy_unique_id = unique_id(level, buddy_index); const buddy_status = self.block_statuses.get(buddy_unique_id) catch unreachable; if (buddy_status == .Free) { self.merge(level, index) catch unreachable; index >>= 1; } else { break; } level -= 1; } } const AlignedRange = struct { ptr: usize, len: usize, fn end(self: *const AlignedRange) usize { return self.ptr + self.len; } }; fn aligned_range(range: []u8) AlignedRange { const as_int = @ptrToInt(range.ptr); return switch (kind) { .InManagedArea => blk: { const aligned = utils.align_down(as_int, free_block_size); break :blk .{.ptr = aligned, .len = range.len + (as_int - aligned)}; }, .InSelf => .{.ptr = as_int, .len = range.len}, }; } const BlockIsFreeRv = union(enum) { Next: usize, Last: void, }; fn block_is_free(self: *Self, address: usize, iter_ptr: ?*BlockStatusIter) ?BlockIsFreeRv { const block = self.address_to_block(address); var iter = BlockStatusIter{.ba = self, .block = block}; defer if (iter_ptr) |ptr| { ptr.* = iter; }; while (iter.next()) |status| { switch (status) { .Free => { const bs = level_to_block_size(iter.level); var next: usize = undefined; if (@addWithOverflow(usize, address, bs, &next)) { return BlockIsFreeRv.Last; } return BlockIsFreeRv{.Next = address +% bs}; }, .Invalid => {}, else => break, } } return null; } pub fn is_free(self: *Self, range: []u8) bool { if (!self.slice_in_range(range)) { @panic("is_free got a range that's outside managed area!"); } const aligned = aligned_range(range); var address = aligned.ptr; while (self.block_is_free(address, null)) |next| { switch (next) { .Next => |n| { if (n >= aligned.end()) return true; address = n; }, .Last => return true, } } return false; } pub fn reserve(self: *Self, to_reserve: []u8) Error!void { if (!self.is_free(to_reserve)) return Error.CantReserveAlreadyUsed; const aligned = aligned_range(to_reserve); var block_start = aligned.ptr; var iter: BlockStatusIter = undefined; while (self.block_is_free(block_start, &iter)) |next| { var level = iter.level; var index = iter.index; block_start = self.get_address(level, index); if (block_start >= aligned.end()) { break; } while (true) { const block_size = level_to_block_size(level); const range_end = aligned.ptr + aligned.len; const middle = block_start + block_size / 2; var split_right = false; var split_left = false; if (aligned.ptr >= middle) { split_right = true; } if (range_end < middle) { split_left = true; } if ((split_right or split_left) and level < (level_count - 1)) { self.split(level, index) catch unreachable; level += 1; index = index * 2; if (split_right) index += 1; block_start = self.get_address(level, index); } else { break; } } _ = self.reserve_block(level, self.index_to_block(level, index)); switch (next) { .Next => |n| { if (n >= self.start + max_size) { break; } block_start = n; }, .Last => break, } } } pub fn dump(self: *Self) void { std.debug.print("Blocks : Free Lists " ++ "============================================================\n", .{}); self.free_blocks.dump(self); std.debug.print( \\Memory ======================================================================== \\{} \\=============================================================================== \\ , .{utils.fmt_dump_hex(@intToPtr([*]const u8, self.start)[0..max_size])}); } }; } const any_byte: u8 = 0x00; fn expect_mem(expected: []const u8, actual: []const u8) !void { try std.testing.expectEqual(expected.len, actual.len); var fail = false; for (expected) |e, i| { if (e != any_byte and e != actual[i]) { fail = true; break; } } if (fail) { std.debug.print( \\Expected ====================================================================== \\NOTE: 0x{x} matches any byte \\{} \\Actual ======================================================================== \\{} \\=============================================================================== \\ , .{any_byte, utils.fmt_dump_hex(expected), utils.fmt_dump_hex(actual)}); try std.testing.expect(false); } } fn TestHelper(comptime kind: FreeBlockKind, total_size: usize) type { return struct { const Th = @This(); const Ba = BuddyAllocator(total_size, free_block_size, kind); const in_self = kind == .InSelf; ba: Ba = .{}, a: *Allocator = undefined, m: [total_size]u8 align(Ba.area_align) = undefined, fn init(self: *Th) !void { try self.ba.init(self.m[0..]); self.a = &self.ba.allocator; } fn assert_is_free(self: *Th, size: usize, at: usize, assert_free: bool) !void { // std.debug.print("assert_is_free {}@{} == {}\n", .{size, at, assert_free}); try std.testing.expectEqual(assert_free, self.ba.is_free( @intToPtr([*]align(Ba.area_align) u8, self.ba.start)[at..at + size])); } fn alloc(self: *Th, size: usize, at: usize, fill: u8) ![]u8 { // std.debug.print( // \\ALLOC ######################################################################### // \\Size: {} @ {} fill: {x} // \\ BEFORE: // \\ // , // .{size, at, fill}); // self.ba.dump(); try self.assert_is_free(size, at, true); const s = try self.ba.allocator.alloc_array(u8, size); for (s) |*e| e.* = fill; try self.assert_is_free(size, at, false); // std.debug.print( // \\ALLOC AFTER ################################################################### // \\ // , .{}); // self.ba.dump(); return s; } }; } fn buddy_allocator_test(comptime kind: FreeBlockKind) !void { const ptr_size = utils.int_bit_size(usize); const free_pointer_size: usize = switch (ptr_size) { 32 => @as(usize, 8), 64 => @as(usize, 16), else => unreachable, }; try std.testing.expectEqual(free_pointer_size, @sizeOf(?FreeBlock.Ptr)); try std.testing.expectEqual(free_pointer_size * 2, free_block_size); const Th = TestHelper(kind, 256); var th = Th{}; try th.init(); try std.testing.expectEqual(switch (ptr_size) { 32 => @as(usize, 5), 64 => @as(usize, 4), else => unreachable, }, Th.Ba.level_count); try th.assert_is_free(th.m.len, 0, true); try th.assert_is_free(1, 1, true); const single = 32; // Single Block const ones = try th.alloc(single, 0, 0x11); try th.assert_is_free(th.m.len, 0, false); try th.assert_is_free(th.m.len - single, single, true); try th.assert_is_free(1, 1, false); const fours = try th.alloc(single, single, 0x44); const bs_index = 100; const bs = th.m[bs_index..150]; try th.assert_is_free(bs.len, bs_index, true); try th.ba.reserve(bs); try th.assert_is_free(32, 64, true); // Before reserved try th.assert_is_free(bs.len, bs_index, false); try th.assert_is_free(96, 160, true); // After reserved for (bs) |*c| c.* = 0xbb; const ones_and_fours = "\x11" ** single ++ "\x44" ** single; const before_bs = [_]u8{any_byte} ** (bs_index - ones_and_fours.len); const after_bs_index = bs_index + bs.len; const after_bs = [_]u8{any_byte} ** (th.m.len - after_bs_index); const bs_and_before = ones_and_fours ++ before_bs ++ "\xbb" ** bs.len; try expect_mem(bs_and_before ++ after_bs, th.m[0..]); const fs_len = 64; const fs_index = 192; const fs = try th.alloc(fs_len, fs_index, 0xff); const before_fs = [_]u8{any_byte} ** (th.m.len - after_bs_index - fs_len); try expect_mem(bs_and_before ++ before_fs ++ "\xff" ** fs_len, th.m[0..]); const fives = try th.alloc(single, th.m.len - fs_len - single, 0x55); const sixes = try th.alloc(single, ones_and_fours.len, 0x66); try th.assert_is_free(fs_len, fs_index, false); try th.a.free_array(fs); try th.assert_is_free(fs_len, fs_index, true); { const byte: u8 = 0xaa; const as = try th.alloc(1, fs_index, byte); try std.testing.expectEqual(byte, th.m[fs_index]); try th.a.free_array(as); } const eights = try th.alloc(single, fs_index, 0x88); const sevens = try th.alloc(single, fs_index + single, 0x77); try expect_mem(bs_and_before ++ before_fs ++ "\x88" ** single ++ "\x77" ** single, th.m[0..]); try th.a.free_array(sevens); try th.a.free_array(ones); try th.a.free_array(eights); try th.a.free_array(sixes); try th.a.free_array(fours); try th.a.free_array(fives); } test "BuddyAllocator.InManagedArea" { try buddy_allocator_test(.InManagedArea); } test "BuddyAllocator.InSelf" { try buddy_allocator_test(.InSelf); }
0
repos/georgios
repos/georgios/kernel/keys.zig
// Generated by scripts/codegen/keys.py const Key = @import("georgios").keyboard.Key; pub fn key_to_char(key: Key) ?u8 { return chars_table[@enumToInt(key)]; } const chars_table = [_]?u8 { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '\n', '\n', '\t', '\x08', ' ', '/', '/', '\\', '.', '.', '?', '!', ',', ':', ';', '`', '\'', '"', '*', '*', '@', '&', '%', '^', '|', '~', '_', '#', '$', '+', '+', '-', '-', '=', '>', '<', '{', '}', '[', ']', '(', ')', null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, };
0
repos/georgios
repos/georgios/kernel/threading.zig
const std = @import("std"); const utils = @import("utils"); const georgios = @import("georgios"); const Info = georgios.ProcessInfo; const ExitInfo = georgios.ExitInfo; const platform = @import("platform.zig"); const pthreading = platform.impl.threading; const kernel = @import("kernel.zig"); const memory = @import("memory.zig"); const Range = memory.Range; const print = @import("print.zig"); const MappedList = @import("mapped_list.zig").MappedList; pub const debug = false; pub const Error = georgios.threading.Error; pub const Thread = struct { pub const Id = u32; pub const State = enum { Run, Wait, }; id: Id = undefined, state: State = .Run, // TODO: Support multiple waits? wake_on_exit: ?*Thread = null, kernel_mode: bool = false, impl: pthreading.ThreadImpl = undefined, process: ?*Process = null, prev_in_system: ?*Thread = null, next_in_system: ?*Thread = null, /// Address of First Instruction entry: usize = 0, pub fn init(self: *Thread, boot_thread: bool) Error!void { if (self.process) |process| { if (process.info) |*info| { self.kernel_mode = info.kernel_mode; } } try self.impl.init(self, boot_thread); } pub fn start(self: *Thread) Error!void { try self.impl.start(); } pub fn finish(self: *Thread) void { if (self.wake_on_exit) |other| { other.state = .Run; } } }; pub const Process = struct { pub const Id = u32; info: ?Info = null, id: Id = undefined, impl: pthreading.ProcessImpl = .{}, main_thread: Thread = .{}, /// Address of First Instruction for Main Thread entry: usize = 0, // TODO: Replace with something like mmap provides dynamic_memory: Range = .{}, /// Current Working Directory cwd: ?[]const u8 = null, fs_submgr: kernel.fs.Submanager = undefined, dispatcher: kernel.dispatching.Dispatcher = undefined, pub fn init(self: *Process, current: ?*Process) Error!void { // TODO: Cleanup on failure if (self.info) |*info| { // Duplicate info data because we can't trust it will stay. const path_temp = try kernel.memory_mgr.alloc.alloc_array(u8, info.path.len); _ = utils.memory_copy_truncate(path_temp, info.path); info.path = path_temp; if (info.name.len > 0) { const name_temp = try kernel.memory_mgr.alloc.alloc_array(u8, info.name.len); _ = utils.memory_copy_truncate(name_temp, info.name); info.name = name_temp; } if (info.args.len > 0) { const args_temp = try kernel.memory_mgr.alloc.alloc_array([]u8, info.args.len); for (info.args) |arg, i| { if (arg.len > 0) { args_temp[i] = try kernel.memory_mgr.alloc.alloc_array(u8, arg.len); _ = utils.memory_copy_truncate(args_temp[i], arg); } else { args_temp[i] = @intToPtr([*]u8, 1024)[0..0]; } } info.args = args_temp; } } try self.set_cwd(if (current) |c| c.cwd.? else "/"); self.fs_submgr.init(&kernel.filesystem_mgr, &self.cwd.?); try self.dispatcher.init(kernel.memory_mgr.alloc.std_allocator(), self); try self.impl.init(self); self.main_thread.process = self; try self.main_thread.init(false); } pub fn start(self: *Process) Error!void { self.main_thread.entry = self.entry; try self.impl.start(); } pub fn address_space_copy(self: *Process, address: usize, data: []const u8) memory.AllocError!void { try self.impl.address_space_copy(address, data); } pub fn address_space_set(self: *Process, address: usize, byte: u8, len: usize) memory.AllocError!void { try self.impl.address_space_set(address, byte, len); } // TODO: Replace with something like mmap provides pub fn add_dynamic_memory(self: *Process, inc: usize) memory.AllocError![]u8 { if (inc > 0) { var new_end: usize = undefined; if (@addWithOverflow(usize, self.dynamic_memory.end(), inc, &new_end)) { return memory.AllocError.OutOfMemory; } if (new_end >= (platform.kernel_to_virtual(0) - pthreading.ProcessImpl.usermode_stack_size)) { return memory.AllocError.OutOfMemory; } try self.impl.address_space_set(self.dynamic_memory.end(), 0xee, inc); self.dynamic_memory.size += inc; } return self.dynamic_memory.to_slice(u8); } pub fn set_cwd(self: *Process, dir: []const u8) Error!void { // Reuse existing memory? const new_cwd = try kernel.memory_mgr.alloc.alloc_array(u8, dir.len); _ = utils.memory_copy_truncate(new_cwd, dir); if (self.cwd) |cwd| { try kernel.memory_mgr.alloc.free_array(cwd); } self.cwd = new_cwd; } }; const TimeQueue = struct { const Element = struct { valid: bool, tid: Thread.Id, when: platform.Time, prev: ?*Element, next: ?*Element, }; elements: []Element = undefined, head: ?*Element = null, tail: ?*Element = null, pub fn init(self: *TimeQueue) Error!void { self.elements = try kernel.alloc.alloc_array(Element, 8); for (self.elements) |*e| { e.valid = false; } } pub fn insert(self: *TimeQueue, tid: Thread.Id, when: platform.Time) void { // print.format("insert {} {}\n", .{tid, when}); var index: usize = 0; while (self.elements[index].valid) { index += 1; if (index >= self.elements.len) @panic("TimeQueue Full"); // TODO } const element = &self.elements[index]; element.valid = true; element.tid = tid; element.when = when; if (self.head) |head| { _ = head; var compare = self.head; while (compare) |cmp| { if (when < cmp.when) { break; } compare = cmp.next; } if (compare) |cmp| { // Comes before something else if (cmp.prev) |prev| { prev.next = element; } else { self.head = element; } element.prev = cmp.prev; cmp.prev = element; element.next = cmp; } else { // Tack on end element.prev = self.tail; element.next = null; self.tail = element; } } else { // Nothing in Queue self.head = element; self.tail = element; element.prev = null; element.next = null; } } pub fn check(self: *TimeQueue) ?Thread.Id { if (self.head) |head| { if (platform.time() >= head.when) { head.valid = false; if (head.next) |next| { next.prev = null; } self.head = head.next; if (self.head == null) { self.tail = null; } return head.tid; } } return null; } }; pub const Manager = struct { fn tid_eql(a: Thread.Id, b: Thread.Id) bool { return a == b; } fn tid_cmp(a: Thread.Id, b: Thread.Id) bool { return a > b; } const ThreadList = MappedList(Thread.Id, *Thread, tid_eql, tid_cmp); fn pid_eql(a: Process.Id, b: Process.Id) bool { return a == b; } fn pid_cmp(a: Process.Id, b: Process.Id) bool { return a > b; } const ProcessList = MappedList(Process.Id, *Process, pid_eql, pid_cmp); const ExitInfoMap = std.AutoHashMap(Process.Id, ExitInfo); thread_list: ThreadList = undefined, idle_thread: Thread = .{.kernel_mode = true, .state = .Wait}, boot_thread: Thread = .{.kernel_mode = true}, next_thread_id: Thread.Id = 0, current_thread: ?*Thread = null, head_thread: ?*Thread = null, tail_thread: ?*Thread = null, process_list: ProcessList = undefined, exit_info_map: ExitInfoMap = undefined, next_process_id: Process.Id = 0, current_process: ?*Process = null, waiting_for_keyboard: ?*Thread = null, waiting_for_mouse: ?*Thread = null, time_queue: TimeQueue = .{}, pub fn init(self: *Manager) Error!void { self.thread_list = .{.alloc = kernel.alloc}; self.process_list = .{.alloc = kernel.alloc}; self.exit_info_map = ExitInfoMap.init(kernel.alloc.std_allocator()); try self.idle_thread.init(false); self.idle_thread.entry = @ptrToInt(platform.idle); try self.boot_thread.init(true); self.current_thread = &self.boot_thread; platform.disable_interrupts(); try self.insert_thread(&self.idle_thread); try self.insert_thread(&self.boot_thread); try self.time_queue.init(); platform.enable_interrupts(); } pub fn new_process_i(self: *Manager) Error!*Process { _ = self; const p = try kernel.alloc.alloc(Process); p.* = .{.info = undefined}; return p; } pub fn new_process(self: *Manager, info: *const Info) Error!*Process { const p = try self.new_process_i(); p.info = info.*; try p.init(self.current_process); return p; } pub fn start_process(self: *Manager, process: *Process) Error!void { platform.disable_interrupts(); // Assign ID process.id = self.next_process_id; self.next_process_id += 1; // Start try self.process_list.push_back(process.id, process); try self.insert_thread(&process.main_thread); try process.start(); } pub fn insert_thread(self: *Manager, thread: *Thread) Error!void { // Assign ID thread.id = self.next_thread_id; self.next_thread_id += 1; // Insert into Thread List if (self.head_thread == null) { self.head_thread = thread; } if (self.tail_thread) |tail| { tail.next_in_system = thread; } thread.prev_in_system = self.tail_thread; thread.next_in_system = null; self.tail_thread = thread; try self.thread_list.push_back(thread.id, thread); } pub fn remove_process(self: *Manager, process: *Process) void { _ = self.process_list.find_remove(process.id) catch @panic("remove_process: process_list.find_remove"); kernel.alloc.free(process) catch @panic("remove_process: free(process)"); } pub fn remove_thread(self: *Manager, thread: *Thread) void { if (thread.next_in_system) |nt| { nt.prev_in_system = thread.prev_in_system; } if (thread.prev_in_system) |pt| { pt.next_in_system = thread.next_in_system; } if (self.head_thread == thread) { self.head_thread = thread.next_in_system; } if (self.tail_thread == thread) { self.tail_thread = thread.prev_in_system; } thread.finish(); if (thread.process) |process| { if (thread == &process.main_thread) { self.remove_process(process); } } _ = self.thread_list.find_remove(thread.id) catch @panic("remove_thread: thread_list.find_remove"); } pub fn remove_current_thread(self: *Manager) void { platform.disable_interrupts(); if (self.current_thread) |thread| { if (debug) print.format("Thread {} has Finished\n", .{thread.id}); self.remove_thread(thread); // TODO: Cleanup Process, Memory while (true) { self.yield(); } } else { @panic("remove_current_thread: no current thread"); } @panic("remove_current_thread: reached end"); } pub fn exit_current_process(self: *Manager, info: ExitInfo) void { if (self.current_thread.?.process) |process| { self.exit_info_map.put(process.id, info) catch @panic("exit_current_process put failed"); } else { @panic("exit_current_process no current process"); } self.remove_current_thread(); } fn next_from(self: *const Manager, thread_maybe: ?*Thread) ?*Thread { if (thread_maybe) |thread| { const nt = thread.next_in_system orelse self.head_thread; if (debug) print.format("+{}->{}+", .{thread.id, nt.?.id}); return nt; } return null; } fn next(self: *Manager) ?*Thread { if (self.time_queue.check()) |tid| { // print.uint(tid); if (self.thread_list.find(tid)) |thread| { // print.uint(thread.id); thread.state = .Run; return thread; } } var next_thread: ?*Thread = null; var thread = self.current_thread; while (next_thread == null) { thread = self.next_from(thread); if (thread) |t| { if (t == self.current_thread.?) { if (self.current_thread.?.state != .Run) { if (debug) print.string("&I&"); self.idle_thread.state = .Run; next_thread = &self.idle_thread; } else { if (debug) print.string("&C&"); } break; } if (t.state == .Run) { next_thread = t; } } else break; } if (next_thread) |nt| { if (nt != &self.idle_thread and self.idle_thread.state == .Run) { if (debug) print.string("&i&"); self.idle_thread.state = .Wait; } } if (debug) { if (next_thread) |nt| { print.format("({})", .{nt.id}); } else { print.string("(null)"); } } return next_thread; } pub fn yield(self: *Manager) void { platform.disable_interrupts(); if (self.next()) |next_thread| { next_thread.impl.switch_to(); } } pub fn thread_is_running(self: *Manager, id: Thread.Id) bool { return self.thread_list.find(id) != null; } pub fn wait_for_thread(self: *Manager, id: Thread.Id) void { if (debug) print.format("<Wait for tid {}>\n", .{id}); platform.disable_interrupts(); if (self.thread_list.find(id)) |thread| { if (debug) print.string("<tid found>"); if (thread.wake_on_exit != null) @panic("wait_for_thread: wake_on_exit not null"); self.current_thread.?.state = .Wait; thread.wake_on_exit = self.current_thread; self.yield(); } if (debug) print.format("<Wait for tid {} is done>\n", .{id}); } pub fn process_is_running(self: *Manager, id: Process.Id) bool { return self.process_list.find(id) != null; } pub fn wait_for_process(self: *Manager, id: Process.Id) Error!ExitInfo { if (debug) print.format("<Wait for pid {}>\n", .{id}); platform.disable_interrupts(); if (self.process_list.find(id)) |proc| { if (debug) print.string("<pid found>"); if (proc.main_thread.wake_on_exit != null) @panic("wait_for_process: wake_on_exit not null"); self.current_thread.?.state = .Wait; proc.main_thread.wake_on_exit = self.current_thread; self.yield(); } if (debug) print.format("<Wait for pid {} is done>\n", .{id}); if (self.exit_info_map.get(id)) |exit_info| { return exit_info; } else { return Error.NoSuchProcess; } } // TODO Make this and keyboard_event_occurred generic pub fn wait_for_keyboard(self: *Manager) void { platform.disable_interrupts(); self.current_thread.?.state = .Wait; self.waiting_for_keyboard = self.current_thread; self.yield(); } pub fn keyboard_event_occurred(self: *Manager) void { platform.disable_interrupts(); if (self.waiting_for_keyboard) |t| { t.state = .Run; self.waiting_for_keyboard = null; // TODO: yield to waiting process? } } // Same problems as the keyboard functions pub fn wait_for_mouse(self: *Manager) void { platform.disable_interrupts(); self.current_thread.?.state = .Wait; self.waiting_for_mouse = self.current_thread; self.yield(); } pub fn mouse_event_occurred(self: *Manager) void { platform.disable_interrupts(); if (self.waiting_for_mouse) |t| { t.state = .Run; self.waiting_for_mouse = null; } } pub fn get_cwd(self: *Manager, buffer: []u8) Error![]const u8 { if (self.current_process) |proc| { return buffer[0..try utils.memory_copy_error(buffer, proc.cwd.?)]; } else { return "/"; } } pub fn get_cwd_heap(self: *Manager) Error![]const u8 { const cwd = if (self.current_process) |proc| proc.cwd.? else "/"; const rv = try kernel.memory_mgr.alloc.alloc_array(u8, cwd.len); _ = utils.memory_copy_truncate(rv, cwd); return rv; } pub fn set_cwd(self: *Manager, dir: []const u8) georgios.ThreadingOrFsError!void { if (self.current_process) |proc| { const resolved = try kernel.filesystem_mgr.resolve_directory_path(dir, proc.cwd.?); try proc.set_cwd(resolved); try kernel.memory_mgr.alloc.free_array(resolved); } else { return Error.NoCurrentProcess; } } // TODO: If this is called by shell sleep for too short a time (like less // than 5ms), it causes a really weird looking page fault. Might have // something to do with the keyboard interrupt for the enter release. pub fn sleep_milliseconds(self: *Manager, ms: u64) void { if (ms == 0) return; platform.disable_interrupts(); self.current_thread.?.state = .Wait; self.time_queue.insert(self.current_thread.?.id, platform.time() + platform.milliseconds_to_time(ms)); self.yield(); } pub fn sleep_seconds(self: *Manager, s: u64) void { if (s == 0) return; platform.disable_interrupts(); self.current_thread.?.state = .Wait; self.time_queue.insert(self.current_thread.?.id, platform.time() + platform.seconds_to_time(s)); self.yield(); } };
0
repos/georgios
repos/georgios/kernel/fs.zig
// =========================================================================== // Virtual Filesystem Interface // =========================================================================== // // TODO: hard and symbolic links // TODO: different open modes // TODO: permissions // // References: // - The main source of inspiration and requirements is // "UNIX Internals: The New Frontiers" by Uresh Vahalia // Chapter 8 "File System Interface and Framework" const std = @import("std"); const georgios = @import("georgios"); const utils = @import("utils"); const streq = utils.memory_compare; const Guid = utils.Guid; const gpt = @import("gpt.zig"); const io = @import("io.zig"); const memory = @import("memory.zig"); const print = @import("print.zig"); const MappedList = @import("mapped_list.zig").MappedList; const List = @import("list.zig").List; pub const Error = georgios.fs.Error; pub const OpenOpts = georgios.fs.OpenOpts; pub const NodeKind = georgios.fs.NodeKind; pub const RamDisk = @import("fs/RamDisk.zig"); pub const Ext2 = @import("fs/Ext2.zig"); pub const FileId = io.File.Id; // TODO: Something better var root_ext2: Ext2 = .{}; fn found_partition(block_store: *io.BlockStore) !bool { if (gpt.Disk.new(block_store)) |disk| { var disk_guid: [Guid.string_size]u8 = undefined; try disk.guid.to_string(disk_guid[0..]); print.format( \\ - Disk GUID is {} \\ - Disk partitions entries at LBA {} \\ - Disk partitions entries are {}B each \\ - Partitions: \\ , .{ disk_guid, disk.partition_entries_lba, disk.partition_entry_size, }); var part_it = try disk.partitions(); defer part_it.done(); while (try part_it.next()) |part| { var type_guid: [Guid.string_size]u8 = undefined; try part.type_guid.to_string(type_guid[0..]); print.format( \\ - Part \\ - {} \\ - {} - {} \\ , .{ type_guid, part.start, part.end, }); if (part.is_linux()) { // TODO: Acutally see if this is the right partition print.string(" - Is Linux!\n"); root_ext2.offset = part.start * block_store.block_size; return true; } } } else |e| { if (e != gpt.Error.InvalidMbr) { return e; } else { print.string(" - Disk doesn't have a MBR, going to try to use whole " ++ "disk as a ext2 filesystem.\n"); // Else try to use whole disk return true; } } return false; } pub fn get_root(alloc: *memory.Allocator, block_store: *io.BlockStore) ?*Vfilesystem { if (found_partition(block_store) catch false) { print.string(" - Filesystem\n"); root_ext2.init(alloc.std_allocator(), block_store) catch return null; return &root_ext2.vfs; } else { print.string(" - No Filesystem\n"); return null; } } pub const PathIterator = struct { path: []const u8, pos: usize = 0, absolute: bool, trailing_slash: bool, pub fn new(path: []const u8) PathIterator { var trimmed_path = path; var absolute = false; var trailing_slash = false; if (trimmed_path.len > 0 and trimmed_path[0] == '/') { absolute = true; trimmed_path = trimmed_path[1..]; } if (trimmed_path.len > 0 and trimmed_path[trimmed_path.len - 1] == '/') { trailing_slash = true; trimmed_path = trimmed_path[0..trimmed_path.len - 1]; } return PathIterator{ .path = trimmed_path, .absolute = absolute, .trailing_slash = trailing_slash, }; } fn next_slash(self: *PathIterator) ?usize { var i: usize = self.pos; while (self.path[i] != '/') { i += 1; if (i >= self.path.len) return null; } return i; } pub fn done(self: *PathIterator) bool { return self.pos >= self.path.len; } pub fn next(self: *PathIterator) ?[]const u8 { var component: ?[]const u8 = null; while (component == null) { if (self.done()) { return null; } if (self.next_slash()) |slash| { component = self.path[self.pos..slash]; self.pos = slash + 1; } else { component = self.path[self.pos..]; self.pos = self.path.len; } if (component.?.len == 0 or streq(component.?, ".")) { component = null; } } return component; } }; fn assert_path_iterator( path: []const u8, expected: []const []const u8, absolute: bool, trailing_slash: bool) !void { var i: usize = 0; var it = PathIterator.new(path); try std.testing.expectEqual(absolute, it.absolute); try std.testing.expectEqual(trailing_slash, it.trailing_slash); while (it.next()) |component| { try std.testing.expect(i < expected.len); try std.testing.expectEqualStrings(expected[i], component); i += 1; } try std.testing.expect(it.done()); try std.testing.expectEqual(expected.len, i); } test "PathIterator" { try assert_path_iterator( "", &[_][]const u8{}, false, false); try assert_path_iterator( ".", &[_][]const u8{}, false, false); try assert_path_iterator( "./", &[_][]const u8{}, false, true); try assert_path_iterator( ".///////", &[_][]const u8{}, false, true); try assert_path_iterator( ".//.///.", &[_][]const u8{}, false, false); try assert_path_iterator( "/", &[_][]const u8{}, true, false); try assert_path_iterator( "/.", &[_][]const u8{}, true, false); try assert_path_iterator( "/./", &[_][]const u8{}, true, true); try assert_path_iterator( "/.///////", &[_][]const u8{}, true, true); try assert_path_iterator( "/.//.///.", &[_][]const u8{}, true, false); try assert_path_iterator( "alice", &[_][]const u8{"alice"}, false, false); try assert_path_iterator( "alice/bob", &[_][]const u8{"alice", "bob"}, false, false); try assert_path_iterator( "alice/bob/carol", &[_][]const u8{"alice", "bob", "carol"}, false, false); try assert_path_iterator( "alice/", &[_][]const u8{"alice"}, false, true); try assert_path_iterator( "alice/bob/", &[_][]const u8{"alice", "bob"}, false, true); try assert_path_iterator( "alice/bob/carol/", &[_][]const u8{"alice", "bob", "carol"}, false, true); try assert_path_iterator( "alice/bob/./carol/", &[_][]const u8{"alice", "bob", "carol"}, false, true); try assert_path_iterator( "alice/bob/../carol/.//./", &[_][]const u8{"alice", "bob", "..", "carol"}, false, true); try assert_path_iterator( "/alice", &[_][]const u8{"alice"}, true, false); try assert_path_iterator( "/alice/bob", &[_][]const u8{"alice", "bob"}, true, false); try assert_path_iterator( "/alice/bob/carol", &[_][]const u8{"alice", "bob", "carol"}, true, false); try assert_path_iterator( "/alice/", &[_][]const u8{"alice"}, true, true); try assert_path_iterator( "/alice/bob/", &[_][]const u8{"alice", "bob"}, true, true); try assert_path_iterator( "/alice/bob/carol/", &[_][]const u8{"alice", "bob", "carol"}, true, true); try assert_path_iterator( "/alice/bob/./carol/", &[_][]const u8{"alice", "bob", "carol"}, true, true); try assert_path_iterator( "/alice/bob/../carol/.//./", &[_][]const u8{"alice", "bob", "..", "carol"}, true, true); } pub const Path = struct { const StrList = List([]const u8); alloc: *memory.Allocator, absolute: bool = false, list: StrList = undefined, fn copy_string(self: *const Path, str: []const u8) Error![]u8 { const copy = try self.alloc.alloc_array(u8, str.len); _ = utils.memory_copy_truncate(copy, str); return copy; } fn push_to_list(self: *Path, list: *StrList, str: []const u8) Error!void { try list.push_back(try self.copy_string(str)); } pub fn push_component(self: *Path, str: []const u8) Error!void { try self.push_to_list(&self.list, str); } pub fn pop_component(self: *Path) Error!void { if (try self.list.pop_back()) |component| { try self.alloc.free_array(component); } } fn path_to_list(self: *Path, list: *StrList, path: []const u8) Error!bool { var it = PathIterator.new(path); while (it.next()) |component| { // Parent of root is root if (streq(component, "..") and it.absolute and list.len == 0) { continue; } try self.push_to_list(list, component); } return it.absolute; } pub fn set(self: *Path, path: []const u8) Error!void { self.absolute = try self.path_to_list(&self.list, path); } pub fn prepend(self: *Path, path: []const u8) Error!void { if (self.absolute) { @panic("Can not prepend to an absolute path"); } var new_list = StrList{.alloc = self.alloc}; self.absolute = try self.path_to_list(&new_list, path); new_list.push_back_list(&self.list); self.list = new_list; } pub fn init(self: *Path, path: ?[]const u8) Error!void { self.list = .{.alloc = self.alloc}; if (path) |p| { try self.set(p); } } pub fn done(self: *Path) Error!void { while (self.list.len > 0) { try self.pop_component(); } } fn value_if_empty(self: *const Path) []const u8 { return if (self.absolute) "/" else "."; } pub fn get(self: *const Path) Error![]u8 { // Calculate size of path string var size: usize = 0; var iter = self.list.const_iterator(); while (iter.next()) |component| { if (size > 0 or self.absolute) { size += 1; // For '/' } size += component.len; } if (size == 0) { size = 1; // For '.' or '/' } // Build path string iter = self.list.const_iterator(); var buffer: []u8 = try self.alloc.alloc_array(u8, size); var build = utils.ToString{.buffer = buffer}; while (iter.next()) |component| { if (build.got > 0 or self.absolute) { try build.string("/"); } try build.string(component); } if (build.got == 0) { try build.string(self.value_if_empty()); } return build.get(); } pub fn filename(self: *const Path) Error![]u8 { return try self.copy_string(if (self.list.tail) |tail_node| tail_node.value else self.value_if_empty()); } }; fn assert_path(alloc: *memory.Allocator, prepend: ?[]const u8, path_str: []const u8, expected: []const u8, expected_filename: []const u8) !void { var path = Path{.alloc = alloc}; try path.init(path_str); defer (path.done() catch unreachable); if (prepend) |pre| { try path.prepend(pre); } const result_path_str = try path.get(); try std.testing.expectEqualStrings(expected, result_path_str); try alloc.free_array(result_path_str); const filename = try path.filename(); try std.testing.expectEqualStrings(expected_filename, filename); try alloc.free_array(filename); } test "Path" { var alloc = memory.UnitTestAllocator{}; alloc.init(); defer alloc.done(); const galloc = &alloc.allocator; try assert_path(galloc, null, "", ".", "."); try assert_path(galloc, null, "./", ".", "."); try assert_path(galloc, null, "./.", ".", "."); try assert_path(galloc, null, "./a/b/c", "a/b/c", "c"); try assert_path(galloc, null, "./a/b/../c", "a/b/../c", "c"); try assert_path(galloc, null, "/", "/", "/"); try assert_path(galloc, null, "/a/b/c", "/a/b/c", "c"); try assert_path(galloc, null, "/a/b/../c", "/a/b/../c", "c"); try assert_path(galloc, null, "/a/../a/b/..//c///./.", "/a/../a/b/../c", "c"); try assert_path(galloc, null, "..", "..", ".."); try assert_path(galloc, null, "a/../../b", "a/../../b", "b"); try assert_path(galloc, null, "/..", "/", "/"); try assert_path(galloc, null, "/../file", "/file", "file"); try assert_path(galloc, ".", ".", ".", "."); try assert_path(galloc, "", "goodbye", "goodbye", "goodbye"); try assert_path(galloc, "hello", "goodbye", "hello/goodbye", "goodbye"); try assert_path(galloc, "/", "a", "/a", "a"); } pub const DirIterator = struct { pub const Result = struct { name: []const u8, node: *Vnode, }; dir: *Vnode, current: ?Result = null, finished: bool = false, next_impl: fn(self: *DirIterator) Error!?Result, done_impl: fn(self: *DirIterator) void, pub fn next(self: *DirIterator) Error!?Result { if (self.finished) { return null; } return self.next_impl(self); } pub fn done(self: *DirIterator) void { return self.done_impl(self); } }; pub const Context = struct { vnode: *Vnode, open_opts: OpenOpts, dir_io_it: ?*DirIterator = null, get_io_file_impl: fn(*Context) Error!*io.File, close_impl: fn(*Context) void, dir_io: io.File = .{ .read_impl = dir_io_read_impl, }, fn dir_io_read_impl(io_file: *io.File, to: []u8) io.FileError!usize { const self = @fieldParentPtr(Context, "dir_io", io_file); if (self.dir_io_it == null) { self.dir_io_it = self.vnode.dir_iter() catch return io.FileError.Internal; } if (self.dir_io_it.?.next() catch return io.FileError.Internal) |item| { return utils.memory_copy_truncate(to, item.name); } return 0; } pub fn get_io_file(self: *Context) Error!*io.File { if (self.vnode.kind.directory) { return &self.dir_io; } return self.get_io_file_impl(self); } pub fn close(self:* Context) void { self.vnode.context_closed(); if (self.dir_io_it) |dir_it| { dir_it.done(); } self.close_impl(self); } }; pub const Vnode = struct { pub const Kind = NodeKind; fs: *Vfilesystem, kind: NodeKind, mounted_here: ?*Vfilesystem = null, context_rc: usize = 0, get_dir_iter_impl: fn(*Vnode) Error!*DirIterator, create_node_impl: ?fn(*Vnode, []const u8, Kind) Error!*Vnode = null, unlink_impl: ?fn(*Vnode, []const u8) Error!void = null, open_new_context_impl: fn(*Vnode, OpenOpts) Error!*Context, pub fn assert_directory(self: *const Vnode) Error!void { if (!self.kind.directory) { return Error.NotADirectory; } } pub fn assert_file(self: *const Vnode) Error!void { if (!self.kind.file) { return Error.NotAFile; } } fn node_with_content(self: *Vnode) callconv(.Inline) Error!*Vnode { if (self.mounted_here) |other_fs| { return other_fs.get_root_vnode(); } return self; } fn dir_iter_i(self: *Vnode) callconv(.Inline) Error!*DirIterator { try self.assert_directory(); return self.get_dir_iter_impl(self); } pub fn dir_iter(self: *Vnode) Error!*DirIterator { return (try self.node_with_content()).dir_iter_i(); } fn find_in_directory_i(self: *Vnode, name: []const u8) callconv(.Inline) Error!?*Vnode { var it = try self.dir_iter_i(); defer it.done(); while (try it.next()) |result| { if (streq(name, result.name)) { return result.node; } } return null; } fn assert_in_directory_i(self: *Vnode, name: []const u8) callconv(.Inline) Error!*Vnode { return (try self.find_in_directory_i(name)) orelse Error.FileNotFound; } pub fn assert_in_directory(self: *Vnode, name: []const u8) Error!*Vnode { return (try self.node_with_content()).assert_in_directory_i(name); } fn directory_empty_i(self: *Vnode) callconv(.Inline) Error!bool { var it = try self.dir_iter_i(); defer it.done(); while (try it.next()) |result| { if (!(streq(result.name, ".") or streq(result.name, ".."))) { return false; } } return true; } pub fn directory_empty(self: *Vnode) Error!bool { return (try self.node_with_content()).directory_empty_i(); } fn create_node_i(self: *Vnode, name: []const u8, kind: Kind) callconv(.Inline) Error!*Vnode { if ((try self.find_in_directory_i(name)) != null) { return Error.AlreadyExists; } if (self.create_node_impl) |create_node_impl| { return create_node_impl(self, name, kind); } return Error.Unsupported; } pub fn create_node(self: *Vnode, name: []const u8, kind: Kind) Error!*Vnode { return (try self.node_with_content()).create_node_i(name, kind); } fn unlink_i(self: *Vnode, name: []const u8) callconv(.Inline) Error!void { const vnode_to_unlink = try self.assert_in_directory_i(name); if (vnode_to_unlink.kind.directory and !try vnode_to_unlink.directory_empty()) { return Error.DirectoryNotEmpty; } if (self.unlink_impl) |unlink_impl| { return unlink_impl(self, name); } return Error.Unsupported; } pub fn unlink(self: *Vnode, name: []const u8) Error!void { return (try self.node_with_content()).unlink_i(name); } pub fn open_new_context(self: *Vnode, opts: OpenOpts) Error!*Context { self.context_rc += 1; return self.open_new_context_impl(self, opts); } pub fn context_closed(self: *Vnode) void { if (self.context_rc > 0) { self.context_rc -%= 1; } // TODO: assert it can't be 0? // TODO: Do something when it reaches 0? } }; pub const Vfilesystem = struct { get_root_vnode_impl: fn(self: *Vfilesystem) Error!*Vnode, pub fn get_root_vnode(self: *Vfilesystem) Error!*Vnode { return self.get_root_vnode_impl(self); } }; pub const ResolvePathOpts = struct { // Optionally set to get canonical path if set. path: ?*[]u8 = null, // Optionally set the current working directory. cwd: ?[]const u8 = null, // Optionally set the starting node for resolution. cwd should be null. starting_node: ?*Vnode = null, // The resulting node. Will also be the last valid part of the path if there's an error. node: ?**Vnode = null, pub fn get_cwd(self: *const ResolvePathOpts) []const u8 { return self.cwd orelse "/"; } pub fn get_working_copy(self: *const ResolvePathOpts, default_node_ptr_ptr: **Vnode) ResolvePathOpts { var ro = self.*; if (ro.cwd == null) { ro.cwd = "/"; } if (ro.node == null) { ro.node = default_node_ptr_ptr; } return ro; } pub fn set_node(self: *const ResolvePathOpts, node: *Vnode) void { if (self.node) |node_ptr| { node_ptr.* = node; } } pub fn get_node(self: *const ResolvePathOpts) *Vnode { return self.node.?.*; } }; pub const Manager = struct { alloc: *memory.Allocator, root_fs: *Vfilesystem, pub fn init(self: *Manager, alloc: *memory.Allocator, root_fs: *Vfilesystem) void { self.* = .{ .alloc = alloc, .root_fs = root_fs, }; } pub fn get_root_vnode(self: *Manager) Error!*Vnode { return self.root_fs.get_root_vnode(); } fn get_absolute_path(self: *Manager, path_str: []const u8, opts: ResolvePathOpts) Error!Path { var path = Path{.alloc = self.alloc}; try path.init(path_str); if (!path.absolute) { try path.prepend(opts.get_cwd()); } return path; } fn resolve_path_i(self: *Manager, raw_path: *Path, opts: ResolvePathOpts) Error!*Vnode { var vnode = opts.starting_node orelse try self.get_root_vnode(); var resolved_path = Path{.alloc = self.alloc, .absolute = true}; try resolved_path.init(null); defer (resolved_path.done() catch @panic("resolve_path_i: resolved_path.done()")); var it = raw_path.list.const_iterator(); while (it.next()) |component| { vnode = try vnode.assert_in_directory(component); opts.set_node(vnode); if (streq(component, "..")) { try resolved_path.pop_component(); } else { try resolved_path.push_component(component); } } if (opts.path) |rp| { rp.* = try resolved_path.get(); } opts.set_node(vnode); return vnode; } fn resolve_path(self: *Manager, path_str: []const u8, opts: ResolvePathOpts) Error!*Vnode { // See man page path_resolution(7) for reference // Get unresolved absolute path var path = try self.get_absolute_path(path_str, opts); defer (path.done() catch @panic("resolve_path: path.done()")); // Find node and build resolved path const vnode = try self.resolve_path_i(&path, opts); if (path_str.len > 0 and path_str[path_str.len - 1] == '/') { try vnode.assert_directory(); } return vnode; } pub fn resolve_directory(self: *Manager, path_str: []const u8, opts: ResolvePathOpts) Error!*Vnode { var dnp: *Vnode = undefined; var opts_copy = opts.get_working_copy(&dnp); const vnode = try self.resolve_path(path_str, opts_copy); try vnode.assert_directory(); return vnode; } pub fn resolve_directory_path(self: *Manager, path: []const u8, cwd: []const u8) Error![]const u8 { var resolved: []u8 = undefined; _ = try self.resolve_directory(path, .{.path = &resolved, .cwd = cwd}); return resolved; } pub fn resolve_parent_directory(self: *Manager, path_str: []const u8, opts: ResolvePathOpts) Error![]const u8 { var dnp: *Vnode = undefined; var opts_copy = opts.get_working_copy(&dnp); var path = try self.get_absolute_path(path_str, opts_copy); defer (path.done() catch @panic("resolve_parent_directory: path.done()")); const child_name = try path.filename(); try path.pop_component(); _ = try self.resolve_path_i(&path, opts_copy); return child_name; } pub fn resolve_file(self: *Manager, path_str: []const u8, opts: ResolvePathOpts) Error!*Vnode{ var dnp: *Vnode = undefined; var opts_copy = opts.get_working_copy(&dnp); const vnode = try self.resolve_path(path_str, opts_copy); try vnode.assert_file(); return vnode; } pub fn create_node(self: *Manager, path_str: []const u8, kind: Vnode.Kind, opts: ResolvePathOpts) Error!*Vnode { var dnp: *Vnode = undefined; var opts_copy = opts.get_working_copy(&dnp); const child_name = try self.resolve_parent_directory(path_str, opts_copy); errdefer self.alloc.free_array(child_name) catch unreachable; return opts_copy.get_node().create_node(child_name, kind); } pub fn resolve_or_create_file(self: *Manager, path: []const u8, opts: ResolvePathOpts) Error!*Vnode { return self.resolve_file(path, opts) catch |e| { if (e == Error.FileNotFound) { return self.create_node(path, .{.file = true}, opts); } return e; }; } pub fn unlink(self: *Manager, path_str: []const u8, opts: ResolvePathOpts) Error!void { var dnp: *Vnode = undefined; var opts_copy = opts.get_working_copy(&dnp); const child_name = try self.resolve_parent_directory(path_str, opts_copy); defer self.alloc.free_array(child_name) catch unreachable; try opts_copy.get_node().unlink(child_name); } pub fn mount(self: *Manager, fs: *Vfilesystem, path: []const u8) Error!void { // TODO: Support mounting at any node, for example if the filesystem // consists of just a file. // TODO: Support unmounting var opts = ResolvePathOpts{}; const node = try self.resolve_directory(path, opts); if (node.mounted_here != null) { return Error.FilesystemAlreadyMountedHere; } node.mounted_here = fs; } pub fn assert_directory_has(self: *Manager, path: []const u8, expected: []const []const u8) !void { var count: usize = 0; const dir = try self.resolve_directory(path, .{}); var it = try dir.dir_iter(); defer it.done(); while (try it.next()) |item| { try std.testing.expect(count < expected.len); try std.testing.expectEqualStrings(expected[count], item.name); count += 1; } try std.testing.expectEqual(expected.len, count); } }; pub const Submanager = struct { const OpenFiles = std.AutoHashMap(FileId, *Context); manager: *Manager, open_files: OpenFiles, cwd_ptr: *[]const u8, next_file_id: FileId = 0, pub fn init(self: *Submanager, manager: *Manager, cwd_ptr: *[]const u8) void { self.* = .{ .manager = manager, .open_files = OpenFiles.init(manager.alloc.std_allocator()), .cwd_ptr = cwd_ptr, }; } pub fn done(self: *Submanager) void { var it = self.open_files.iterator(); while (it.next()) |kv| { kv.value_ptr.*.close() catch unreachable; // TODO? } self.open_files.deinit(); } pub fn create(self: *Submanager, name: []const u8, kind: NodeKind) Error!void { const path_opts = ResolvePathOpts{.cwd = self.cwd_ptr.*}; _ = try self.manager.create_node(name, kind, path_opts); } pub fn unlink(self: *Submanager, name: []const u8) Error!void { const path_opts = ResolvePathOpts{.cwd = self.cwd_ptr.*}; try self.manager.unlink(name, path_opts); } pub fn open(self: *Submanager, path: []const u8, opts: OpenOpts) Error!FileId { try opts.check(); var vnode: *Vnode = undefined; const path_opts = ResolvePathOpts{.cwd = self.cwd_ptr.*}; if (opts.dir()) { vnode = try self.manager.resolve_directory(path, path_opts); } else if (opts.must_exist()) { vnode = try self.manager.resolve_file(path, path_opts); } else { vnode = try self.manager.resolve_or_create_file(path, path_opts); } const id = self.next_file_id; self.next_file_id += 1; try self.open_files.put(id, try vnode.open_new_context(opts)); return id; } pub fn close(self: *Submanager, id: FileId) Error!void { const kv = self.open_files.fetchRemove(id) orelse return Error.InvalidFileId; kv.value.close(); } pub fn read(self: *Submanager, id: FileId, to: []u8) io.FileError!usize { const cxt = self.open_files.get(id) orelse return io.FileError.InvalidFileId; const io_file = cxt.get_io_file() catch return io.FileError.Unsupported; return try io_file.read(to); } pub fn write(self: *Submanager, id: FileId, from: []const u8) io.FileError!usize { const cxt = self.open_files.get(id) orelse return io.FileError.InvalidFileId; const io_file = cxt.get_io_file() catch return io.FileError.Unsupported; return io_file.write(from); } pub fn seek(self: *Submanager, id: FileId, offset: isize, seek_type: io.File.SeekType) io.FileError!usize { const cxt = self.open_files.get(id) orelse return io.FileError.InvalidFileId; const io_file = cxt.get_io_file() catch return io.FileError.Unsupported; return io_file.seek(offset, seek_type); } };
0
repos/georgios
repos/georgios/kernel/log.zig
const std = @import("std"); const io = @import("io.zig"); const fprint = @import("fprint.zig"); pub const Log = struct { const Self = @This(); const tab = " "; const marker = " - "; file: ?*io.File, indent: usize = 0, parent: ?*const Self = null, enabled: bool = true, pub fn child(self: *const Self) Self { return Self{.indent = self.indent + 1, .file = self.file, .parent = self}; } fn is_enabled(self: *const Self) bool { var logger: ?*const Self = self; while (logger) |l| { if (!l.enabled) { return false; } logger = l.parent; } return true; } fn print_indent(file: *io.File, indent: usize) void { var i: usize = 0; while (i < indent) { _ = fprint.string(file, tab) catch {}; i += 1; } _ = fprint.string(file, marker) catch {}; } pub fn log(self: *const Self, comptime fmtstr: []const u8, args: anytype) void { if (self.file) |file| { if (self.is_enabled()) { print_indent(file, self.indent); _ = fprint.format(file, fmtstr ++ "\n", args) catch {}; } } } }; test "Log" { var buffer: [1024]u8 = undefined; var buffer_file = io.BufferFile{}; buffer_file.init(buffer[0..]); const file = &buffer_file.file; { buffer_file.reset(); var log = Log{.file = file}; log.log("{}, World!", .{"Hello"}); try buffer_file.expect(" - Hello, World!\n"); } { buffer_file.reset(); var log1 = Log{.file = file}; log1.log("1", .{}); log1.enabled = false; log1.log("SHOULD NOT BE LOGGED", .{}); log1.enabled = true; log1.log("2", .{}); { var log2 = log1.child(); log2.log("3", .{}); { var log3 = log2.child(); log3.log("4", .{}); log1.enabled = false; log3.log("SHOULD NOT BE LOGGED", .{}); log1.enabled = true; log3.log("5", .{}); } log2.log("6", .{}); log2.log("7", .{}); } log1.log("8", .{}); try buffer_file.expect( \\ - 1 \\ - 2 \\ - 3 \\ - 4 \\ - 5 \\ - 6 \\ - 7 \\ - 8 \\ ); } }
0
repos/georgios
repos/georgios/kernel/list.zig
const memory = @import("memory.zig"); pub fn List(comptime Type: type) type { return struct { const Self = @This(); pub const Node = struct { next: ?*Node, prev: ?*Node, value: Type, }; alloc: *memory.Allocator, head: ?*Node = null, tail: ?*Node = null, len: usize = 0, pub fn remove_node(self: *Self, node_maybe: ?*Node) void { if (node_maybe) |node| { if (node.next) |next| { next.prev = node.prev; } if (node.prev) |prev| { prev.next = node.next; } if (node == self.head) { self.head = node.next; } if (node == self.tail) { self.tail = node.prev; } self.len -= 1; } } pub fn push_front_node(self: *Self, node: *Node) void { node.next = self.head; node.prev = null; if (self.head) |head| { head.prev = node; } self.head = node; if (self.len == 0) { self.tail = node; } self.len += 1; } pub fn push_front(self: *Self, value: Type) memory.MemoryError!void { const node = try self.alloc.alloc(Node); node.value = value; self.push_front_node(node); } pub fn pop_front_node(self: *Self) ?*Node { const node = self.head; self.remove_node(node); return node; } pub fn pop_front(self: *Self) memory.MemoryError!?Type { if (self.pop_front_node()) |node| { const value = node.value; try self.alloc.free(node); return value; } return null; } pub fn bump_node_to_front(self: *Self, node: *Node) void { if (self.head == node) { return; } self.remove_node(node); self.push_front_node(node); } pub fn push_back_node(self: *Self, node: *Node) void { node.next = null; node.prev = self.tail; if (self.tail) |tail| { tail.next = node; } self.tail = node; if (self.len == 0) { self.head = node; } self.len += 1; } pub fn push_back(self: *Self, value: Type) memory.MemoryError!void { const node = try self.alloc.alloc(Node); node.value = value; self.push_back_node(node); } pub fn pop_back_node(self: *Self) ?*Node { const node = self.tail; self.remove_node(node); return node; } pub fn pop_back(self: *Self) memory.MemoryError!?Type { if (self.pop_back_node()) |node| { const value = node.value; try self.alloc.free(node); return value; } return null; } pub fn bump_node_to_back(self: *Self, node: *Node) void { if (self.tail == node) { return; } self.remove_node(node); self.push_back_node(node); } pub fn push_back_list(self: *Self, other: *Self) void { if (other.head) |other_head| { other_head.prev = self.tail; if (self.tail) |tail| { tail.next = other_head; } self.tail = other.tail; if (self.len == 0) { self.head = other_head; } self.len += other.len; other.head = null; other.tail = null; other.len = 0; } } pub fn clear(self: *Self) memory.MemoryError!void { while (self.pop_back_node()) |node| { try self.alloc.free(node); } } pub const Iterator = struct { node: ?*Node, pub fn next(self: *Iterator) ?Type { if (self.node) |n| { self.node = n.next; return n.value; } return null; } pub fn done(self: *const Iterator) bool { return self.node == null; } }; pub fn iterator(self: *Self) Iterator { return Iterator{.node = self.head}; } // TODO: Make generic with Iterator? pub const ConstIterator = struct { node: ?*const Node, pub fn next(self: *ConstIterator) ?Type { if (self.node) |n| { self.node = n.next; return n.value; } return null; } pub fn done(self: *const ConstIterator) bool { return self.node == null; } }; pub fn const_iterator(self: *const Self) ConstIterator { return ConstIterator{.node = self.head}; } }; } test "List" { const std = @import("std"); const equal = std.testing.expectEqual; var alloc = memory.UnitTestAllocator{}; alloc.init(); defer alloc.done(); const UsizeList = List(usize); var list = UsizeList{.alloc = &alloc.allocator}; const nilv: ?usize = null; const niln: ?*UsizeList.Node = null; // Empty try equal(@as(usize, 0), list.len); try equal(nilv, try list.pop_back()); try equal(nilv, try list.pop_front()); try equal(niln, list.head); try equal(niln, list.tail); // Push Some Values try list.push_back(1); try equal(@as(usize, 1), list.len); try list.push_back(2); try equal(@as(usize, 2), list.len); try list.push_back(3); try equal(@as(usize, 3), list.len); // Test Iterator var i: usize = 0; const expected = [_]usize{1, 2, 3}; var it = list.iterator(); while (it.next()) |actual| { try equal(expected[i], actual); i += 1; } // pop_back The Values try equal(@as(usize, 3), (try list.pop_back()).?); try equal(@as(usize, 2), list.len); try equal(@as(usize, 2), (try list.pop_back()).?); try equal(@as(usize, 1), list.len); try equal(@as(usize, 1), (try list.pop_back()).?); // It's empty again try equal(@as(usize, 0), list.len); try equal(nilv, try list.pop_back()); try equal(nilv, try list.pop_front()); try equal(niln, list.head); try equal(niln, list.tail); // Push Some Values try list.push_front(1); try equal(@as(usize, 1), list.len); try list.push_back(2); try list.push_front(3); try list.push_front(10); try equal(@as(usize, 4), list.len); // pop_back The Values try equal(@as(usize, 10), (try list.pop_front()).?); try equal(@as(usize, 3), (try list.pop_front()).?); try equal(@as(usize, 1), (try list.pop_front()).?); try equal(@as(usize, 2), (try list.pop_front()).?); // It's empty yet again try equal(@as(usize, 0), list.len); try equal(nilv, try list.pop_back()); try equal(nilv, try list.pop_front()); try equal(niln, list.head); try equal(niln, list.tail); // Clear try list.push_back(12); try list.push_front(6); try list.clear(); // It's empty ... again try equal(@as(usize, 0), list.len); try equal(nilv, try list.pop_back()); try equal(nilv, try list.pop_front()); try equal(niln, list.head); try equal(niln, list.tail); // Test push_back_list by adding empty list to empty list var other_list = UsizeList{.alloc = &alloc.allocator}; list.push_back_list(&other_list); try equal(@as(usize, 0), list.len); try equal(nilv, try list.pop_back()); try equal(nilv, try list.pop_front()); try equal(niln, list.head); try equal(niln, list.tail); // Test push_back_list by adding non empty list to empty list try other_list.push_back(1); try other_list.push_back(3); list.push_back_list(&other_list); try equal(@as(usize, 0), other_list.len); try equal(nilv, try other_list.pop_back()); try equal(nilv, try other_list.pop_front()); try equal(niln, other_list.head); try equal(niln, other_list.tail); try equal(@as(usize, 2), list.len); // Test push_back_list by adding non empty list to non empty list try other_list.push_back(5); try other_list.push_back(7); list.push_back_list(&other_list); try equal(@as(usize, 0), other_list.len); try equal(nilv, try other_list.pop_back()); try equal(nilv, try other_list.pop_front()); try equal(niln, other_list.head); try equal(niln, other_list.tail); try equal(@as(usize, 4), list.len); try equal(@as(usize, 1), (try list.pop_front()).?); try equal(@as(usize, 3), (try list.pop_front()).?); try equal(@as(usize, 5), (try list.pop_front()).?); try equal(@as(usize, 7), (try list.pop_front()).?); try equal(@as(usize, 0), list.len); try equal(nilv, try list.pop_back()); try equal(nilv, try list.pop_front()); try equal(niln, list.head); try equal(niln, list.tail); }
0
repos/georgios/kernel
repos/georgios/kernel/fs/RamDisk.zig
// In memory filesystem. // // In addition to using this for a RamDisk, this allows for unit testing the // virtual filesystem code. const std = @import("std"); const utils = @import("utils"); const kernel = @import("../kernel.zig"); const List = kernel.List; const memory = kernel.memory; const Allocator = memory.Allocator; const MemoryError = memory.MemoryError; const io = kernel.io; const fs = kernel.fs; const DirIterator = fs.DirIterator; const Context = fs.Context; const ResolvePathOpts = fs.ResolvePathOpts; const Vnode = fs.Vnode; const Vfilesystem = fs.Vfilesystem; const Error = fs.Error; const OpenOpts = fs.OpenOpts; const RamDisk = @This(); const PageFile = struct { const Page = struct { buffer: []u8, written: usize = 0, }; const PageView = struct { page: *Page, offset: usize, pub fn get_buffer(self: *const PageView, writing: bool) []u8 { const end = if (writing) self.page.buffer.len else self.page.written; return self.page.buffer[self.offset..end]; } pub fn copy_from(self: *PageView, src: []const u8) usize { const copied = utils.memory_copy_truncate(self.get_buffer(true), src); self.offset += copied; self.page.written = @maximum(self.page.written, self.offset); return copied; } pub fn copy_to(self: *PageView, dest: []u8) usize { return utils.memory_copy_truncate(dest, self.get_buffer(false)); } pub fn full(self: *const PageView) bool { return self.page.written == self.page.buffer.len; } pub fn at_end(self: *const PageView) bool { return self.offset >= self.page.written; } }; const Pages = List(*Page); pages: Pages, alloc: *Allocator, page_alloc: *Allocator, page_size: usize, total_written: usize = 0, pub fn new(alloc: *Allocator, page_alloc: *Allocator, page_size: usize) PageFile { return .{ .pages = .{.alloc = alloc}, .alloc = alloc, .page_alloc = page_alloc, .page_size = page_size, }; } pub fn done(self: *PageFile) MemoryError!void { while (try self.pages.pop_front()) |page| { try self.alloc.free_array(page.buffer); try self.alloc.free(page); } } fn get_page(self: *PageFile, pos: usize) ?PageView { var it = self.pages.iterator(); var return_page: ?*Page = null; var seen: usize = 0; var seen_before: usize = 0; while (it.next()) |page| { seen += page.written; if (seen >= pos and pos < (seen_before + self.page_size)) { return_page = page; break; } seen_before = seen; } if (return_page) |p| { return PageView{.page = p, .offset = pos - seen_before}; } return null; } fn append_page(self: *PageFile) MemoryError!PageView { const page = try self.alloc.alloc(Page); page.* = .{.buffer = try self.page_alloc.alloc_array(u8, self.page_size)}; try self.pages.push_back(page); return PageView{.page = page, .offset = 0}; } fn get_or_create_page(self: *PageFile, pos: usize) MemoryError!PageView { // TODO: This doesn't seem like it would handle the case of wanting to // write in the middle of a file with multiple full pages. It looks // like it would append instead. var page = self.get_page(pos); if (page == null or page.?.full()) { return try self.append_page(); } return page.?; } fn write_impl(self: *PageFile, pos: *usize, from: []const u8) io.FileError!usize { if (from.len == 0) return 0; var left: usize = from.len; var written: usize = 0; while (left > 0) { var page = self.get_or_create_page(pos.*) catch return io.FileError.OutOfSpace; const prev_page_written = page.page.written; const copied = page.copy_from(from[written..]); self.total_written = self.total_written - prev_page_written + page.page.written; written += copied; left -= copied; pos.* += copied; } return written; } fn read_impl(self: *PageFile, pos: *usize, to: []u8) io.FileError!usize { var left: usize = to.len; var read: usize = 0; while (left > 0) { var page = self.get_page(pos.*) orelse break; if (page.at_end()) { break; } const copied = page.copy_to(to[read..]); read += copied; left -= copied; pos.* += copied; } return read; } fn seek_impl(self: *PageFile, pos: *usize, offset: isize, seek_type: io.File.SeekType) io.FileError!usize { // TODO: limit is null here, is that right? const new_pos = try io.File.generic_seek( pos.*, self.total_written, null, offset, seek_type); pos.* = new_pos; return new_pos; } }; const ContextImpl = struct { alloc: *Allocator, context: Context, page_file: *?PageFile, pos: usize, io_file: io.File, fn new(alloc: *Allocator, node: *Node, opts: OpenOpts) ContextImpl { return .{ .alloc = alloc, .context = .{ .vnode = &node.vnode, .open_opts = opts, .get_io_file_impl = get_io_file_impl, .close_impl = close_impl, }, .page_file = &node.page_file, .pos = 0, .io_file = .{ .write_impl = write_impl, .read_impl = read_impl, .seek_impl = seek_impl, .close_impl = io.File.nop.close_impl, }, }; } fn get_io_file_impl(ctx: *Context) Error!*io.File { const self = @fieldParentPtr(ContextImpl, "context", ctx); if (self.page_file.* != null) { return &self.io_file; } return Error.NotAFile; } fn write_impl(io_file: *io.File, from: []const u8) io.FileError!usize { const self = @fieldParentPtr(ContextImpl, "io_file", io_file); return self.page_file.*.?.write_impl(&self.pos, from); } fn read_impl(io_file: *io.File, to: []u8) io.FileError!usize { const self = @fieldParentPtr(ContextImpl, "io_file", io_file); return self.page_file.*.?.read_impl(&self.pos, to); } fn seek_impl(io_file: *io.File, offset: isize, seek_type: io.File.SeekType) io.FileError!usize { const self = @fieldParentPtr(ContextImpl, "io_file", io_file); return self.page_file.*.?.seek_impl(&self.pos, offset, seek_type); } fn close_impl(ctx: *Context) void { const self = @fieldParentPtr(ContextImpl, "context", ctx); self.alloc.free(self) catch unreachable; } }; pub const Node = struct { const Nodes = std.StringArrayHashMap(*Node); const DirIteratorImpl = struct { alloc: *Allocator, dir_iter: DirIterator, returned_self: bool = false, returned_parent: bool = false, node_iter: Nodes.Iterator, fn next_impl(dir_it: *DirIterator) Error!?DirIterator.Result { const self = @fieldParentPtr(DirIteratorImpl, "dir_iter", dir_it); const node = @fieldParentPtr(Node, "vnode", dir_it.dir); if (!self.returned_self) { self.returned_self = true; return DirIterator.Result{.name = ".", .node = dir_it.dir}; } if (!self.returned_parent) { self.returned_parent = true; return DirIterator.Result{.name = "..", .node = node.parent}; } if (self.node_iter.next()) |kv| { return DirIterator.Result{.name = kv.key_ptr.*, .node = &kv.value_ptr.*.vnode}; } return null; } fn done_impl(dir_it: *DirIterator) void { const self = @fieldParentPtr(DirIteratorImpl, "dir_iter", dir_it); self.alloc.free(self) catch @panic("RamDisk DirIterator done"); } }; ram_disk: *RamDisk, vnode: Vnode, parent: *Vnode, nodes: ?Nodes = null, page_file: ?PageFile = null, pub fn init(self: *Node, ram_disk: *RamDisk, kind: Vnode.Kind, parent: *Vnode) void { self.* = .{ .ram_disk = ram_disk, .vnode = .{ .fs = &ram_disk.vfs, .kind = kind, .get_dir_iter_impl = get_dir_iter_impl, .create_node_impl = create_node_impl, .unlink_impl = unlink_impl, .open_new_context_impl = open_new_context_impl, }, .parent = parent, }; if (kind.directory) { self.nodes = Nodes.init(ram_disk.alloc.std_allocator()); } if (kind.file) { self.page_file = PageFile.new(ram_disk.alloc, ram_disk.page_alloc, ram_disk.page_size); } } fn get_dir_iter_impl(vnode: *Vnode) Error!*DirIterator { const self = @fieldParentPtr(Node, "vnode", vnode); if (self.nodes) |*nodes| { const alloc = self.ram_disk.alloc; var impl = try alloc.alloc(DirIteratorImpl); impl.* = .{ .alloc = alloc, .dir_iter = .{ .dir = vnode, .next_impl = DirIteratorImpl.next_impl, .done_impl = DirIteratorImpl.done_impl, }, .node_iter = nodes.iterator(), }; return &impl.dir_iter; } return Error.NotADirectory; } fn create_node_impl(vnode: *Vnode, name: []const u8, kind: Vnode.Kind) Error!*Vnode { const self = @fieldParentPtr(Node, "vnode", vnode); if (self.nodes) |*nodes| { var node = try self.ram_disk.alloc.alloc(Node); node.init(self.ram_disk, kind, vnode); try nodes.put(name, node); return &node.vnode; } return Error.NotADirectory; } fn unlink_impl(vnode: *Vnode, name: []const u8) Error!void { const self = @fieldParentPtr(Node, "vnode", vnode); if (self.nodes) |*nodes| { const kv = nodes.fetchOrderedRemove(name).?; try kv.value.done(); try self.ram_disk.alloc.free_array(kv.key); try self.ram_disk.alloc.free(kv.value); } else { return Error.NotADirectory; } } fn open_new_context_impl(vnode: *Vnode, opts: OpenOpts) Error!*Context { const self = @fieldParentPtr(Node, "vnode", vnode); const alloc = self.ram_disk.alloc; var impl = try alloc.alloc(ContextImpl); impl.* = ContextImpl.new(alloc, self, opts); return &impl.context; } pub fn done(self: *Node) Error!void { if (self.nodes) |*nodes| { var it = nodes.iterator(); while (it.next()) |kv| { try kv.value_ptr.*.done(); try self.ram_disk.alloc.free_array(kv.key_ptr.*); try self.ram_disk.alloc.free(kv.value_ptr.*); } nodes.deinit(); } if (self.page_file) |*page_file| { try page_file.done(); } } }; vfs: Vfilesystem, alloc: *Allocator, page_alloc: *Allocator, page_size: usize, root_node: Node = undefined, pub fn init(self: *RamDisk, alloc: *Allocator, page_alloc: *Allocator, page_size: usize) void { self.* = .{ .vfs = .{ .get_root_vnode_impl = get_root_vnode_impl, }, .alloc = alloc, .page_alloc = page_alloc, .page_size = page_size, }; self.root_node.init(self, .{.directory = true}, &self.root_node.vnode); } fn get_root_vnode_impl(vfs: *Vfilesystem) Error!*Vnode { const self = @fieldParentPtr(RamDisk, "vfs", vfs); return &self.root_node.vnode; } pub fn done(self: *RamDisk) Error!void { try self.root_node.done(); } const RamDiskTest = struct { const test_page_size = 4; alloc: memory.UnitTestAllocator = .{}, check_allocs: bool = false, rd: RamDisk = undefined, rd2: RamDisk = undefined, m: fs.Manager = undefined, pub fn init(self: *RamDiskTest) void { self.alloc.init(); const galloc = &self.alloc.allocator; self.rd.init(galloc, galloc, test_page_size); self.rd2.init(galloc, galloc, test_page_size); self.m.init(galloc, &self.rd.vfs); } pub fn reached_end(self: *RamDiskTest) void { self.check_allocs = true; } pub fn done(self: *RamDiskTest) void { self.rd.done() catch unreachable; self.rd2.done() catch unreachable; self.alloc.done_check_if(&self.check_allocs); } }; test "RamDisk: Files and Directories" { var t = RamDiskTest{}; t.init(); defer t.done(); // Assert root is empty try t.m.assert_directory_has("/", &[_][]const u8{".", ".."}); // Make a file _ = try t.m.create_node("/file1", .{.file = true}, .{}); // And it should now be available try t.m.assert_directory_has("/", &[_][]const u8{".", "..", "file1"}); // Try to make the same file again try std.testing.expectError(Error.AlreadyExists, t.m.create_node("/file1", .{.file = true}, .{})); // Make a directory const dir = try t.m.create_node("/dir", .{.directory = true}, .{}); // And it should now be available try t.m.assert_directory_has("/", &[_][]const u8{".", "..", "file1", "dir"}); _ = try t.m.resolve_directory("/dir", .{}); // Make some files in the directory _ = try t.m.create_node("/dir/file2", .{.file = true}, .{}); _ = try t.m.create_node("/dir/file3", .{.file = true}, .{}); const file_list = [_][]const u8{".", "..", "file2", "file3"}; // And they should now be there try t.m.assert_directory_has("/dir", &file_list); // Test directory io read { const ctx = try dir.open_new_context(.{.ReadOnly = .{.dir = true}}); defer ctx.close(); const dir_io = try ctx.get_io_file(); var buffer: [16]u8 = undefined; var count: usize = 0; while (true) { const read = try dir_io.read(buffer[0..]); if (read == 0) break; try std.testing.expect(count < file_list.len); try std.testing.expectEqualStrings(file_list[count], buffer[0..read]); count += 1; } } // Remove file1 try t.m.unlink("/file1", .{}); try t.m.assert_directory_has("/", &[_][]const u8{".", "..", "dir"}); // Try to remove dir try std.testing.expectError(Error.DirectoryNotEmpty, t.m.unlink("/dir", .{})); // Remove files first try t.m.unlink("/dir/file2", .{}); try t.m.assert_directory_has("/dir", &[_][]const u8{".", "..", "file3"}); try t.m.unlink("/dir/file3", .{}); try t.m.assert_directory_has("/dir", &[_][]const u8{".", ".."}); // Try again try t.m.unlink("/dir", .{}); t.reached_end(); } test "RamDisk: Write and Read Files" { var t = RamDiskTest{}; t.init(); defer t.done(); const a = try t.m.create_node("/a", .{.file = true}, .{}); const ctx = try a.open_new_context(.{.Write = .{.read = true}}); defer ctx.close(); const file = try ctx.get_io_file(); const str1 = "abc123"; const len1 = str1.len; try std.testing.expectEqual(len1, try file.write(str1)); var offset: usize = 0; var read_buffer: [len1]u8 = undefined; while (offset < len1) { try std.testing.expectEqual(offset, try file.seek(@intCast(isize, offset), .FromStart)); try std.testing.expectEqual(len1 - offset, try file.read(read_buffer[offset..])); try std.testing.expectEqualStrings(str1[offset..], read_buffer[offset..]); offset += 1; } } test "RamDisk: Mount Another Ram Disk" { var t = RamDiskTest{}; t.init(); defer t.done(); // Create some files in root _ = try t.m.create_node("/file1", .{.file = true}, .{}); _ = try t.m.create_node("/file2", .{.file = true}, .{}); // Mount another ram disk _ = try t.m.create_node("/mount", .{.directory = true}, .{}); try t.m.mount(&t.rd2.vfs, "/mount"); // Create some files there _ = try t.m.create_node("/mount/file3", .{.file = true}, .{}); _ = try t.m.create_node("/mount/file4", .{.file = true}, .{}); // Should contain: try t.m.assert_directory_has("/", &[_][]const u8{".", "..", "file1", "file2", "mount"}); try t.m.assert_directory_has("/mount", &[_][]const u8{".", "..", "file3", "file4"}); // Confirm these are in the seperate filesystems try std.testing.expectEqual(@as(usize, 3), t.rd.root_node.nodes.?.count()); try std.testing.expectEqual(@as(usize, 2), t.rd2.root_node.nodes.?.count()); // TODO: More tests, like unmount and what happens if we delete a mount point? }
0
repos/georgios/kernel
repos/georgios/kernel/fs/Ext2.zig
// Second Extended File System (Ext2) // // For Reference See: // https://en.wikipedia.org/wiki/Ext2 // https://wiki.osdev.org/Ext2 // https://www.nongnu.org/ext2-doc/ext2.html const std = @import("std"); const Allocator = std.mem.Allocator; const utils = @import("utils"); const georgios = @import("georgios"); const kernel = @import("../kernel.zig"); const print = kernel.print; const io = kernel.io; const fs = kernel.fs; const Vnode = fs.Vnode; const Vfilesystem = fs.Vfilesystem; const DirIterator = fs.DirIterator; const Error = fs.Error; const Context = fs.Context; const OpenOpts = fs.OpenOpts; const Ext2 = @This(); const Superblock = packed struct { const expected_magic: u16 = 0xef53; // Rev0 Superblock inode_count: u32 = 0, block_count: u32 = 0, superuser_block_count: u32 = 0, free_block_count: u32 = 0, free_inode_count: u32 = 0, first_data_block: u32 = 0, log_block_size: u32 = 0, log_frag_size: u32 = 0, blocks_per_group: u32 = 0, frags_per_group: u32 = 0, inodes_per_group: u32 = 0, last_mount_time: u32 = 0, last_write_time: u32 = 0, unchecked_mount_count: u16 = 0, max_unchecked_mount_count: u16 = 0, magic: u16 = 0, state: u16 = 0, error_repsponse: u16 = 0, minor_revision: u16 = 0, last_check_time: u32 = 0, check_interval: u32 = 0, creator_os: u32 = 0, major_revision: u32 = 0, superuser_uid: u16 = 0, superuser_gid: u16 = 0, // Start of Rev1 Superblock Extention first_nonreserved_inode: u32 = 0, inode_size: u32 = 0, // Rest has been left out for now fn verify(self: *const Superblock) Error!void { if (self.magic != expected_magic) { print.string("Invalid Ext2 Magic\n"); return Error.InvalidFilesystem; } if (self.major_revision != 1) { print.string("Invalid Ext2 Revision"); return Error.InvalidFilesystem; } if ((utils.align_up(self.inode_count, self.inodes_per_group) / self.inodes_per_group) != self.block_group_count()) { print.string("Inconsistent Ext2 Block Group Count"); return Error.InvalidFilesystem; } // TODO: Verify things related to inode_size } fn block_size(self: *const Superblock) usize { // TODO: Zig Bug? Can't inline utils.Ki(1) return @as(usize, 1024) << @truncate(utils.UsizeLog2Type, self.log_block_size); } fn block_group_count(self: *const Superblock) usize { return utils.align_up(self.block_count, self.blocks_per_group) / self.blocks_per_group; } }; const BlockGroupDescriptor = packed struct { block_bitmap: u32, inode_bitmap: u32, inode_table: u32, free_block_count: u16, free_inode_count: u16, used_dir_count: u16, pad: u16, reserved: [12]u8, }; const Inode = packed struct { mode: u16, uid: u16, size: u32, last_access_time: u32, creation_time: u32, last_modification_time: u32, deletion_time: u32, gid: u16, link_count: u16, block_count: u32, flags: u32, os_dependant_field_1: u32, // TODO: Revert when https://github.com/ziglang/zig/issues/2627 is fixed // blocks: [15]u32, // generation: u32, blocks: [16]u32, file_acl: u32, dir_acl: u32, fragment_address: u32, os_dependant_field_2: [12]u8, fn is_file(self: *const Inode) bool { return self.mode & 0x8000 > 0; } fn is_directory(self: *const Inode) bool { return self.mode & 0x4000 > 0; } }; const DataBlockIterator = struct { const max_first_level_index: u8 = 11; const second_level_index = max_first_level_index + 1; const third_level_index = second_level_index + 1; const fourth_level_index = third_level_index + 1; const DataBlockInfoState = enum { Index, FillInZeros, EndOfFile, }; const DataBlockInfo = union(DataBlockInfoState) { Index: u32, FillInZeros: void, EndOfFile: void, }; ext2: *Ext2, inode: *Inode, got: usize = 0, first_level_pos: usize = 0, second_level: ?[]u32 = null, second_level_pos: usize = 0, third_level: ?[]u32 = null, third_level_pos: usize = 0, fourth_level: ?[]u32 = null, fourth_level_pos: usize = 0, new_pos: bool = false, fn set_position(self: *DataBlockIterator, block: usize) Error!void { if (block <= max_first_level_index) { self.first_level_pos = block; self.second_level_pos = 0; self.third_level_pos = 0; self.fourth_level_pos = 0; } else if (block >= Ext2.second_level_start and block < self.ext2.third_level_start) { self.first_level_pos = second_level_index; self.second_level_pos = block - Ext2.second_level_start; self.third_level_pos = 0; self.fourth_level_pos = 0; } else if (block >= self.ext2.third_level_start and block < self.ext2.fourth_level_start) { self.first_level_pos = third_level_index; const level_offset = block - self.ext2.third_level_start; self.second_level_pos = level_offset / self.ext2.max_entries_per_block; self.third_level_pos = level_offset % self.ext2.max_entries_per_block; self.fourth_level_pos = 0; } else if (block >= self.ext2.fourth_level_start and block < self.ext2.max_fourth_level_entries) { self.first_level_pos = fourth_level_index; const level_offset = block - self.ext2.fourth_level_start; self.second_level_pos = level_offset / self.ext2.max_third_level_entries; const sub_level_offset = level_offset % self.ext2.max_third_level_entries; self.third_level_pos = sub_level_offset / self.ext2.max_entries_per_block; self.fourth_level_pos = sub_level_offset % self.ext2.max_entries_per_block; } else return Error.OutOfBounds; self.got = block * self.ext2.block_size; self.new_pos = true; } fn get_level(self: *DataBlockIterator, level: *?[]u32, index: u32) Error!void { if (level.* == null) { level.* = try self.ext2.alloc.alloc( u32, self.ext2.block_size / @sizeOf(u32)); } try self.ext2.get_entry_block(level.*.?, index); } fn prepare_level(self: *DataBlockIterator, index: usize, level_pos: *usize, level: *?[]u32, parent_level_pos: *usize) bool { if (self.first_level_pos < index) return false; if (level_pos.* >= self.ext2.max_entries_per_block) { parent_level_pos.* += 1; level_pos.* = 0; return true; } return level.* == null or self.new_pos; } fn get_next_block_info(self: *DataBlockIterator) Error!DataBlockInfo { // print.format("get_next_block_index_i: {}\n", self.first_level_pos); // First Level if (self.first_level_pos <= max_first_level_index) { const index = self.inode.blocks[self.first_level_pos]; self.first_level_pos += 1; if (index == 0) { return DataBlockInfo.FillInZeros; } return DataBlockInfo{.Index = index}; } // Figure Out Our Position var get_fourth_level = self.prepare_level( fourth_level_index, &self.fourth_level_pos, &self.fourth_level, &self.third_level_pos); var get_third_level = self.prepare_level( third_level_index, &self.third_level_pos, &self.third_level, &self.second_level_pos); var get_second_level = self.prepare_level( second_level_index, &self.second_level_pos, &self.second_level, &self.first_level_pos); if (self.new_pos) self.new_pos = false; // Check for end of blocks if (self.first_level_pos > fourth_level_index) return DataBlockInfo.EndOfFile; // Get New Levels if Needed if (get_second_level) { const index = self.inode.blocks[self.first_level_pos]; if (index == 0) { self.second_level_pos += 1; return DataBlockInfo.FillInZeros; } try self.get_level(&self.second_level, index); } if (get_third_level) { const index = self.second_level.?[self.second_level_pos]; if (index == 0) { self.third_level_pos += 1; return DataBlockInfo.FillInZeros; } try self.get_level(&self.third_level, index); } if (get_fourth_level) { const index = self.third_level.?[self.third_level_pos]; if (index == 0) { self.fourth_level_pos += 1; return DataBlockInfo.FillInZeros; } try self.get_level(&self.fourth_level, index); } // Return The Result switch (self.first_level_pos) { second_level_index => { const index = self.second_level.?[self.second_level_pos]; if (index == 0) { self.second_level_pos += 1; return DataBlockInfo.FillInZeros; } return DataBlockInfo{.Index = index}; }, third_level_index => { const index = self.third_level.?[self.third_level_pos]; if (index == 0) { self.third_level_pos += 1; return DataBlockInfo.FillInZeros; } return DataBlockInfo{.Index = index}; }, fourth_level_index => { const index = self.fourth_level.?[self.fourth_level_pos]; if (index == 0) { self.fourth_level_pos += 1; return DataBlockInfo.FillInZeros; } return DataBlockInfo{.Index = index}; }, else => unreachable, } } fn next(self: *DataBlockIterator, dest: []u8) Error!?[]u8 { if (dest.len < self.ext2.block_size) { return Error.NotEnoughDestination; } const dest_use = dest[0..self.ext2.block_size]; switch (try self.get_next_block_info()) { .Index => |index| { try self.ext2.get_data_block(dest_use, index); }, .FillInZeros => utils.memory_set(dest_use, 0), .EndOfFile => return null, } const got = @minimum(@as(usize, self.inode.size) - self.got, self.ext2.block_size); // std.debug.print("DataBlockIterator.next: got: {} {} {}\n", .{self.inode.size, self.got, self.ext2.block_size}); self.got += got; return dest_use[0..got]; } fn done(self: *DataBlockIterator) void { if (self.second_level != null) self.ext2.alloc.free(self.second_level.?); if (self.third_level != null) self.ext2.alloc.free(self.third_level.?); if (self.fourth_level != null) self.ext2.alloc.free(self.fourth_level.?); } }; const DirectoryEntry = packed struct { inode: u32, next_entry_offset: u16, name_size: u8, file_type: u8, // NOTE: This field seems to always be 0 for the disk I am creating at the // time of writing, so this field can't be relied on. }; const DirIteratorImpl = struct { ext2: *Ext2, node: *Node, alloc: Allocator, dir_iter: DirIterator, data_block_iter: DataBlockIterator, buffer: []u8, block_count: usize, buffer_pos: usize = 0, initial: bool = true, fn new(vnode: *Vnode) Error!*DirIterator { const node = @fieldParentPtr(Node, "vnode", vnode); const ext2 = node.ext2; const inode = &node.inode; var impl = try ext2.alloc.create(DirIteratorImpl); impl.* = .{ .alloc = ext2.alloc, .ext2 = ext2, .node = node, .data_block_iter = DataBlockIterator{.ext2 = ext2, .inode = inode}, .buffer = try ext2.alloc.alloc(u8, ext2.block_size), .block_count = inode.size / ext2.block_size, .dir_iter = .{.dir = &node.vnode, .next_impl = next_impl, .done_impl = done_impl}, }; return &impl.dir_iter; } fn next_impl(dir_it: *DirIterator) Error!?DirIterator.Result { const self = @fieldParentPtr(DirIteratorImpl, "dir_iter", dir_it); const get_next_block = self.buffer_pos >= self.ext2.block_size; if (get_next_block) { self.buffer_pos = 0; self.block_count -= 1; if (self.block_count == 0) { return null; } } if (get_next_block or self.initial) { self.initial = false; const result = self.data_block_iter.next(self.buffer) catch return Error.Internal; if (result == null) { return null; } } const entry = @ptrCast(*DirectoryEntry, &self.buffer[self.buffer_pos]); const name_pos = self.buffer_pos + @sizeOf(DirectoryEntry); self.buffer_pos += entry.next_entry_offset; return DirIterator.Result{ .name = self.buffer[name_pos..name_pos + entry.name_size], .node = &(try self.ext2.get_node(entry.inode)).vnode, }; } fn done_impl(dir_it: *DirIterator) void { const self = @fieldParentPtr(DirIteratorImpl, "dir_iter", dir_it); self.alloc.free(self.buffer); self.alloc.destroy(self); } }; const Node = struct { ext2: *Ext2, vnode: Vnode, inode: Inode = undefined, fn init(self: *Node, ext2: *Ext2, kind: Vnode.Kind) void { self.* = .{ .ext2 = ext2, .vnode = .{ .fs = &ext2.vfs, .kind = kind, .get_dir_iter_impl = DirIteratorImpl.new, .create_node_impl = create_node_impl, .unlink_impl = unlink_impl, .open_new_context_impl = open_new_context_impl, }, }; } fn init_after_inode(self: *Node) void { self.vnode.kind = .{ .file = self.inode.is_file(), .directory = self.inode.is_directory(), }; } fn create_node_impl(vnode: *Vnode, name: []const u8, kind: Vnode.Kind) Error!*Vnode { const self = @fieldParentPtr(Node, "vnode", vnode); _ = self; _ = name; _ = kind; return Error.Unsupported; } fn unlink_impl(vnode: *Vnode, name: []const u8) Error!void { const self = @fieldParentPtr(Node, "vnode", vnode); _ = self; _ = name; return Error.Unsupported; } fn open_new_context_impl(vnode: *Vnode, opts: OpenOpts) Error!*Context { const self = @fieldParentPtr(Node, "vnode", vnode); const alloc = self.ext2.alloc; var impl = try alloc.create(ContextImpl); impl.* = .{ .context = .{ .vnode = vnode, .open_opts = opts, .get_io_file_impl = ContextImpl.get_io_file_impl, .close_impl = ContextImpl.close_impl, }, .node = self, .io_file = .{ .read_impl = ContextImpl.read, .write_impl = io.File.unsupported.write_impl, .seek_impl = ContextImpl.seek, .close_impl = io.File.nop.close_impl, }, .data_block_iter = DataBlockIterator{.ext2 = self.ext2, .inode = &self.inode}, }; return &impl.context; } }; const ContextImpl = struct { context: Context, node: *Node, io_file: io.File = undefined, data_block_iter: DataBlockIterator = undefined, buffer: ?[]u8 = null, position: usize = 0, fn get_io_file_impl(ctx: *Context) Error!*io.File { const self = @fieldParentPtr(ContextImpl, "context", ctx); return &self.io_file; } fn read(file: *io.File, to: []u8) io.FileError!usize { const self = @fieldParentPtr(ContextImpl, "io_file", file); if (self.buffer == null) { self.buffer = try self.node.ext2.alloc.alloc(u8, self.node.ext2.block_size); } var got: usize = 0; while (got < to.len) { // TODO: See if buffer already has the data we need!!! self.data_block_iter.set_position(self.position / self.node.ext2.block_size) catch |e| { print.format("ERROR: ext2.File.read: set_position: {}\n", .{@errorName(e)}); return io.FileError.Internal; }; const block = self.data_block_iter.next(self.buffer.?) catch |e| { print.format("ERROR: ext2.File.read: next: {}\n", .{@errorName(e)}); return io.FileError.Internal; }; if (block == null) break; const read_size = utils.memory_copy_truncate( to[got..], block.?[self.position % self.node.ext2.block_size..]); if (read_size == 0) break; self.position += read_size; got += read_size; } return got; } fn seek(file: *io.File, offset: isize, seek_type: io.File.SeekType) io.FileError!usize { const self = @fieldParentPtr(ContextImpl, "io_file", file); self.position = try io.File.generic_seek( self.position, self.node.inode.size, null, offset, seek_type); return self.position; } fn close_impl(ctx: *Context) void { const self = @fieldParentPtr(ContextImpl, "context", ctx); self.position = 0; const alloc = self.node.ext2.alloc; if (self.buffer) |buffer| { alloc.free(buffer); } alloc.destroy(self); } }; const NodeCache = std.AutoHashMap(u32, *Node); const root_inode_number = @as(usize, 2); const second_level_start = 12; vfs: fs.Vfilesystem = undefined, node_cache: NodeCache = undefined, initialized: bool = false, alloc: Allocator = undefined, block_store: *io.BlockStore = undefined, offset: io.AddressType = 0, superblock: Superblock = Superblock{}, block_size: usize = 0, block_group_descriptor_table: io.AddressType = 0, max_entries_per_block: usize = 0, max_third_level_entries: usize = 0, max_fourth_level_entries: usize = 0, third_level_start: usize = 0, fourth_level_start: usize = 0, fn get_block_address(self: *const Ext2, index: usize) io.AddressType { return self.offset + @as(u64, index) * @as(u64, self.block_size); } fn get_block_group_descriptor(self: *Ext2, index: usize, dest: *BlockGroupDescriptor) Error!void { try self.block_store.read( self.block_group_descriptor_table + @sizeOf(BlockGroupDescriptor) * index, utils.to_bytes(dest)); } fn get_node(self: *Ext2, n: u32) Error!*Node { if (self.node_cache.get(n)) |node| { return node; } var node: *Node = try self.alloc.create(Node); node.init(self, undefined); // On purpose, wait until we got the inode errdefer self.alloc.destroy(node); // Get Inode var block_group: BlockGroupDescriptor = undefined; const nm1 = n - 1; try self.get_block_group_descriptor( nm1 / self.superblock.inodes_per_group, &block_group); const address = @as(u64, block_group.inode_table) * self.block_size + (nm1 % self.superblock.inodes_per_group) * self.superblock.inode_size; try self.block_store.read(self.offset + address, utils.to_bytes(&node.inode)); node.init_after_inode(); try self.node_cache.put(n, node); return node; } fn get_data_block(self: *Ext2, block: []u8, index: usize) Error!void { try self.block_store.read(self.get_block_address(index), block); } fn get_entry_block(self: *Ext2, block: []u32, index: usize) Error!void { try self.get_data_block( @ptrCast([*]u8, block.ptr)[0..block.len * @sizeOf(u32)], index); } pub fn init(self: *Ext2, alloc: Allocator, block_store: *io.BlockStore) Error!void { self.alloc = alloc; self.vfs = .{ .get_root_vnode_impl = get_root_vnode_impl, }; self.node_cache = NodeCache.init(alloc); self.block_store = block_store; try block_store.read(self.offset + utils.Ki(1), utils.to_bytes(&self.superblock)); // std.debug.print("{}\n", .{self.superblock}); try self.superblock.verify(); self.block_size = self.superblock.block_size(); self.max_entries_per_block = self.block_size / @sizeOf(u32); self.block_group_descriptor_table = self.get_block_address( if (self.block_size >= utils.Ki(2)) 1 else 2); self.third_level_start = second_level_start + self.max_entries_per_block; self.max_third_level_entries = self.max_entries_per_block * self.max_entries_per_block; self.fourth_level_start = self.third_level_start + self.max_third_level_entries; self.max_fourth_level_entries = self.max_third_level_entries * self.max_entries_per_block; self.initialized = true; } fn done(self: *Ext2) void { var it = self.node_cache.iterator(); while (it.next()) |kv| { self.alloc.destroy(kv.value_ptr.*); } self.node_cache.deinit(); } fn get_root_vnode_impl(vfs: *Vfilesystem) Error!*Vnode { const self = @fieldParentPtr(Ext2, "vfs", vfs); return &(try self.get_node(2)).vnode; } const Ext2Test = struct { ta: utils.TestAlloc = .{}, alloc: kernel.memory.UnitTestAllocator = .{}, check_allocs: bool = false, file: std.fs.File = undefined, fbs: io.StdFileBlockStore = .{}, cache: io.MemoryBlockStore = .{}, ext2: Ext2 = .{}, m: fs.Manager = undefined, fn init(self: *Ext2Test, use_cache: bool) !void { self.alloc.init(); self.file = try std.fs.cwd().openFile( "misc/ext2-test-disk/ext2-test-disk.img", .{.read = true}); const std_alloc = self.ta.alloc(); self.fbs.init(std_alloc, &self.file, 1024); self.cache.init_as_cache(self.alloc.allocator.std_allocator(), &self.fbs.block_store_if, 4); try self.ext2.init(std_alloc, if (use_cache) &self.cache.block_store_if else &self.fbs.block_store_if); self.m.init(&self.alloc.allocator, &self.ext2.vfs); } fn reached_end(self: *Ext2Test) void { self.check_allocs = true; } fn done(self: *Ext2Test) void { self.ext2.done(); self.cache.done(); self.alloc.done_check_if(&self.check_allocs); self.file.close(); } }; fn test_reading(file: *io.File, comptime expected: []const u8) !void { var offset: usize = 0; var read_buffer: [expected.len]u8 = undefined; while (offset < expected.len) { try std.testing.expectEqual(offset, try file.seek(@intCast(isize, offset), .FromStart)); try std.testing.expectEqual(expected.len - offset, try file.read(read_buffer[offset..])); try std.testing.expectEqualStrings(expected[offset..], read_buffer[offset..]); offset += 1; } } fn ext2_test(use_cache: bool) !void { var t = Ext2Test{}; defer t.ta.deinit(.Panic); errdefer t.ta.deinit(.NoPanic); try t.init(use_cache); defer t.done(); try t.m.assert_directory_has("/", &[_][]const u8{".", "..", "lost+found", "dir", "file1"}); try t.m.assert_directory_has("/dir", &[_][]const u8{".", "..", "file2"}); { const file = try t.m.resolve_file("/file1", .{}); const file_ctx = try file.open_new_context(.{.ReadOnly = .{}}); defer file_ctx.close(); const io_file = try file_ctx.get_io_file(); try test_reading(io_file, \\Hello this is a file \\ ); } { const file = try t.m.resolve_file("/dir/file2", .{}); const file_ctx = try file.open_new_context(.{.ReadOnly = .{}}); defer file_ctx.close(); const io_file = try file_ctx.get_io_file(); try test_reading(io_file, \\This is another file \\ ); } t.reached_end(); } test "Ext2" { try ext2_test(false); } test "Ext2 with cache" { try ext2_test(true); }
0
repos/georgios/kernel
repos/georgios/kernel/platform/cga_console.zig
// Interface to use the IBM PC Color Graphics Adapter (CGA)'s 80x25 text mode. // // For Reference See: // "IBM Color/Graphics Monitor Adaptor" // https://en.wikipedia.org/wiki/VGA_text_mode // https://en.wikipedia.org/wiki/Code_page_437 // https://wiki.osdev.org/Printing_to_Screen const kernel = @import("root").kernel; const Console = kernel.Console; const HexColor = Console.HexColor; const util = @import("util.zig"); const out8 = util.out8; const in8 = util.in8; const platform = @import("platform.zig"); const code_point_437 = @import("code_point_437.zig"); const Color = enum(u4) { Black = 0, Blue = 1, Green = 2, Cyan = 3, Red = 4, Magenta = 5, Brown = 6, LightGray = 7, DarkGray = 8, LightBlue = 9, LightGreen = 10, LightCyan = 11, LightRed = 12, LightMagenta = 13, Yellow = 14, White = 15, var color_value: u16 = undefined; fn get_cga_color(ansi_color: HexColor) Color { return switch (ansi_color) { HexColor.White => .White, HexColor.LightGray => .LightGray, HexColor.DarkGray => .DarkGray, HexColor.Black => .Black, HexColor.Red => .Red, HexColor.Green => .Green, HexColor.Yellow => .Brown, HexColor.Blue => .Blue, HexColor.Magenta => .Magenta, HexColor.Cyan => .Cyan, HexColor.LightRed => .LightRed, HexColor.LightGreen => .LightGreen, HexColor.LightYellow => .Yellow, HexColor.LightBlue => .LightBlue, HexColor.LightMagenta => .LightMagenta, HexColor.LightCyan => .LightCyan, }; } pub fn set(fg: HexColor, bg: HexColor) void { color_value = (@enumToInt(get_cga_color(fg)) | (@intCast(u16, @enumToInt(get_cga_color(bg))) << 4)) << 8; } pub fn char_value(c: u8) callconv(.Inline) u16 { return @intCast(u16, c) | color_value; } }; const command_port: u16 = 0x03D4; const data_port: u16 = 0x03D5; const high_byte_command: u8 = 14; const low_byte_command: u8 = 15; const set_cursor_shape_command: u8 = 0x0a; const default_fg_color = HexColor.White; const default_bg_color = HexColor.Black; var fg_color = default_fg_color; var bg_color = default_bg_color; var buffer: [*]u16 = undefined; pub var console = Console{ .place_impl = place_impl, .scroll_impl = scroll_impl, .set_hex_color_impl = set_hex_color_impl, .get_hex_color_impl = get_hex_color_impl, .use_default_color_impl = use_default_color_impl, .reset_attributes_impl = reset_attributes_impl, .move_cursor_impl = move_cursor_impl, .show_cursor_impl = show_cursor_impl, .clear_screen_impl = clear_screen_impl, }; pub fn init() void { buffer = @intToPtr([*]u16, platform.kernel_to_virtual(0xB8000)); console.init(80, 25); } fn place_impl(c: *Console, utf32_value: u32, row: u32, col: u32) void { const cp437_value = if (from_unicode(utf32_value)) |cp437| cp437 else '?'; const index: u32 = (row *% c.width) +% col; buffer[index] = Color.char_value(cp437_value); } pub fn set_hex_color_impl(c: *Console, color: HexColor, layer: Console.Layer) void { _ = c; if (layer == .Foreground) { fg_color = color; } else { bg_color = color; } Color.set(fg_color, bg_color); } pub fn get_hex_color_impl(c: *Console, layer: Console.Layer) HexColor { _ = c; return if (layer == .Foreground) fg_color else bg_color; } fn use_default_color_impl(c: *Console, layer: Console.Layer) void { c.set_hex_color(if (layer == .Foreground) default_fg_color else default_bg_color, layer); } pub fn reset_attributes_impl(c: *Console) void { _ = c; } pub fn clear_screen_impl(c: *Console) void { var row: u32 = 0; while (row < c.height) : (row +%= 1) { var col: u32 = 0; while (col < c.width) : (col +%= 1) { c.place(' ', row, col); } } } pub fn move_cursor_impl(c: *Console, row: u32, col: u32) void { const index: u32 = (row *% c.width) +% col; out8(command_port, high_byte_command); out8(data_port, @intCast(u8, (index >> 8) & 0xFF)); out8(command_port, low_byte_command); out8(data_port, @intCast(u8, index & 0xFF)); } pub fn show_cursor_impl(c: *Console, show: bool) void { _ = c; out8(command_port, set_cursor_shape_command); out8(data_port, if (show) 0 else 0x20); // Bit 5 Disables Cursor } pub fn scroll_impl(c: *Console) void { var y: u32 = 1; while (y < c.height) : (y +%= 1) { var x: u32 = 0; while (x < c.width) : (x +%= 1) { const src: u32 = (y *% c.width) +% x; const dest: u32 = ((y - 1) *% c.width) +% x; buffer[dest] = buffer[src]; } } var x: u32 = 0; while (x < c.width) : (x +%= 1) { c.place(' ', c.height - 1, x); } } pub fn print_all_characters() void { console.reset_terminal(); var i: u16 = 0; while (i < 256) { console.print_char(@truncate(u8, i)); if (i % 32 == 31) { console.newline(); } i += 1; } } /// Convert UTF-32 to Code Page 437 pub fn from_unicode(c: u32) ?u8 { // Code Page 437 Doesn't Have Any Points Past 2^16 if (c > 0xFFFF) return null; const c16 = @intCast(u16, c); // Check a few contiguous ranges. The main one is Printable ASCII. if (code_point_437.contiguous_ranges(c16)) |c8| return c8; // Else check the hash table const hash = c16 % code_point_437.bucket_count; if (hash > code_point_437.max_hash_used) return null; const offset = hash * code_point_437.max_bucket_length; const bucket = code_point_437.hash_table[offset..offset + code_point_437.max_bucket_length]; for (bucket[0..]) |entry| { const valid = @intCast(u8, entry >> 24); if (valid == 0) return null; const key = @truncate(u16, entry); const value = @truncate(u8, entry >> 16); if (key == c16) return value; } return null; }
0
repos/georgios/kernel
repos/georgios/kernel/platform/interrupts.zig
// Management and Base Handler Code for Interrupts // // TODO: More Info const builtin = @import("builtin"); const kernel = @import("root").kernel; const kutil = kernel.util; const print = kernel.print; const kthreading = kernel.threading; const putil = @import("util.zig"); // TODO: Zig Bug? unable to evaluate constant expression // const segments = @import("segments.zig"); // const kernel_code_selector = segments.kernel_code_selector; // const user_code_selector = segments.user_code_selector; const segments = @import("segments.zig"); const ps2 = @import("ps2.zig"); const system_calls = @import("system_calls.zig"); // Stack When the Interrupt is Handled ======================================== pub fn StackTemplate(comptime include_error_code: bool) type { return packed struct { const has_error_code = include_error_code; // Pushed by us using pusha edi: u32, esi: u32, ebp: u32, esp: u32, ebx: u32, edx: u32, ecx: u32, eax: u32, // Pushed by CPU // Pushed by some exceptions, but not others. error_code: if (include_error_code) u32 else void, eip: u32, cs: u32, eflags: u32, }; } pub const Stack = StackTemplate(false); pub const StackEc = StackTemplate(true); // Interrupt Descriptor Table ================================================ const Entry = packed struct { offset_0_15: u16 = 0, selector: u16 = 0, zero: u8 = 0, flags: u8 = 0, offset_16_31: u16 = 0, }; var table = table_init: { var entries: [256]Entry = undefined; for (entries) |*e| { e.* = Entry{}; } break :table_init entries; }; // TODO: Bochs error for interrupt 39 is missing default error message, figure // out why. const invalid_index = "Interrupt number is invalid"; var names = names_init: { var the_names: [table.len][]const u8 = undefined; for (the_names) |*i| { i.* = invalid_index; } break :names_init the_names; }; const TablePointer = packed struct { limit: u16, base: u32, }; var table_pointer: TablePointer = undefined; pub fn load() void { asm volatile ("lidtl (%[p])" : : [p] "{ax}" (&table_pointer)); } fn set_entry( name: []const u8, index: u8, handler: fn() void, selector: u16, flags: u8) void { const offset: u32 = @ptrToInt(handler); names[index] = name; print.debug_format( " - [{}]: \"{}\"\n" ++ " - selector: {:x} address: {:a} flags: {:x}\n", .{ index, name, selector, offset, flags}); // TODO: Print flag and selector meanings table[index].offset_0_15 = @intCast(u16, offset & 0xffff); table[index].offset_16_31= @intCast(u16, (offset & 0xffff0000) >> 16); table[index].selector = selector; table[index].flags = flags; } // TODO: Figure out what these are... pub const kernel_flags: u8 = 0x8e; pub const user_flags: u8 = kernel_flags | (3 << 5); // Interrupt Handler Generation ============================================== pub fn PanicMessage(comptime StackType: type) type { return struct { pub fn show(interrupt_number: u32, interrupt_stack: *const StackType) void { const has_ec = StackType.has_error_code; const ec = interrupt_stack.error_code; const gpf = has_ec and interrupt_number == 13; const page_fault = has_ec and interrupt_number == 14; // TODO: Need a better way to determine this because if the kernel // jumps to userspace for whatever reason then the whole message // makes no sense and exit_current_process is called, which could // kill an innocent process. const caused_by_user = interrupt_stack.eip < 0xc000000 or (page_fault and (ec & 4) > 0); if (caused_by_user) { print.string( \\==============================<!>Program Crash<!>============================= \\A program has encountered an unrecoverable error: \\ ); } else { kernel.console.reset_terminal(); kernel.console.show_cursor(false); kernel.console.set_hex_colors(.Black, .Red); kernel.console.clear_screen(); print.string( \\==============================<!>Kernel Panic<!>============================== \\The system has encountered an unrecoverable error: \\ ); } print.format( \\ Interrupt Number: {} \\ , .{interrupt_number}); if (has_ec) { print.format(" Error Code: {}\n", .{ec}); } print.string(" Message: "); if (!is_exception(interrupt_number)) { print.string(kernel.panic_message); } else { print.string(get_name(interrupt_number)); if (gpf) { // Explain General Protection Fault Cause const which_table = @intCast(u2, (ec >> 1) & 3); const table_index = (ec >> 3) & 8191; print.format("{} Caused By {}[{}]", .{ if ((ec & 1) == 1) @as([]const u8, " Externally") else @as([]const u8, ""), @as([]const u8, switch (which_table) { 0 => "GDT", 1 => "IDT", 2 => "LDT", 3 => "IDT", }), table_index}); if (which_table == 0) { // Print Selector if GDT print.format(" ({})", .{segments.get_name(table_index)}); } else if ((which_table & 1) == 1) { // Print Interrupt if IDT print.format(" ({})", .{get_name(table_index)}); } } else if (page_fault) { // Explain Page Fault Cause const what = if ((ec & 1) > 0) @as([]const u8, "Page Protection Violation") else @as([]const u8, "Missing Page"); const reserved = if ((ec & 8) > 0) @as([]const u8, " (Reserved bits set in directory entry)") else @as([]const u8, ""); const when = if ((ec & 16) > 0) @as([]const u8, "Fetching an Instruction From") else (if ((ec & 2) > 0) @as([]const u8, "Writing to") else @as([]const u8, "Reading From")); const user = if (caused_by_user) @as([]const u8, "User") else @as([]const u8, "Non-User"); print.format("\n {}{} While {} {:a} while in {} Ring", .{ what, reserved, when, putil.cr2(), user}); // TODO: Zig Compiler Assertion // print.format("\n {}{} While {} {:a} while in {} Ring", .{ // if ((ec & 1) > 0) // @as([]const u8, "Page Protection Violation") else // @as([]const u8, "Missing Page"), // if ((ec & 8) > 0) // @as([]const u8, " (Reserved bits set in directory entry)") else // @as([]const u8, ""), // if ((ec & 16) > 0) // @as([]const u8, "Fetching an Instruction From") // else // (if ((ec & 2) > 0) @as([]const u8, "Writing to") else // @as([]const u8, "Reading From")), // putil.cr2(), // if ((ec & 4) > 0) @as([]const u8, "User") else // @as([]const u8, "Non-User")}); } } print.format( \\ \\ \\--Registers------------------------------------------------------------------- \\ EIP: {:a} \\ EFLAGS: {:x} \\ EAX: {:x} \\ ECX: {:x} \\ EDX: {:x} \\ EBX: {:x} \\ ESP: {:a} \\ EBP: {:a} \\ ESI: {:x} \\ EDI: {:x} \\ CS: {:x} ({}) , .{ interrupt_stack.eip, interrupt_stack.eflags, interrupt_stack.eax, interrupt_stack.ecx, interrupt_stack.edx, interrupt_stack.ebx, interrupt_stack.esp, interrupt_stack.ebp, interrupt_stack.esi, interrupt_stack.edi, interrupt_stack.cs, segments.get_name(interrupt_stack.cs / 8), }); if (caused_by_user) { print.char('\n'); kernel.threading_mgr.exit_current_process(.{.crashed = true}); } else { putil.halt_forever(); } } }; } fn BaseInterruptHandler( comptime i: u32, comptime StackType: type, comptime irq: bool, impl: fn(u32, *const StackType) void) type { return struct { const index: u8 = i; const irq_number: u32 = if (irq) i - pic.irq_0_7_interrupt_offset else 0; fn inner_handler(interrupt_stack: *const StackType) void { const spurious = if (irq_number == 7 or irq_number == 15) pic.is_spurious_irq(irq_number) else false; if (irq) { if (!spurious) { impl(irq_number, interrupt_stack); } pic.end_of_interrupt(irq_number, spurious); } else if (!spurious) { impl(@as(u32, i), interrupt_stack); } } pub fn handler() callconv(.Naked) noreturn { asm volatile ("cli"); // Push EAX, ECX, EDX, EBX, original ESP, EBP, ESI, and EDI asm volatile ("pushal"); inner_handler(asm volatile ("mov %%esp, %[interrupt_stack]" : [interrupt_stack] "={eax}" (-> *const StackType))); asm volatile ("popal"); // Restore Registers if (StackType.has_error_code) { asm volatile ("addl $4, %%esp"); // Pop Error Code } asm volatile ("iret"); unreachable; } pub fn get() fn() void { return @ptrCast(fn() void, handler); } pub fn set(name: []const u8, selector: u16, flags: u8) void { set_entry(name, index, @ptrCast(fn() void, handler), selector, flags); } }; } fn HardwareErrorInterruptHandler( comptime i: u32, comptime error_code: bool) type { const StackType = StackTemplate(error_code); return BaseInterruptHandler( i, StackType, false, PanicMessage(StackType).show); } pub fn IrqInterruptHandler( comptime irq_number: u32, impl: fn(u32, *const Stack) void) type { return BaseInterruptHandler(irq_number + pic.irq_0_7_interrupt_offset, Stack, true, impl); } fn InterruptHandler(comptime i: u32, impl: fn(u32, *const Stack) void) type { return BaseInterruptHandler(i, Stack, false, impl); } // CPU Exception Interrupts ================================================== const Exception = struct { name: []const u8, index: u32, error_code: bool, }; const exceptions = [_]Exception { Exception{.name = "Divide by Zero Fault", .index = 0, .error_code = false}, Exception{.name = "Debug Trap", .index = 1, .error_code = false}, Exception{.name = "Nonmaskable Interrupt", .index = 2, .error_code = false}, Exception{.name = "Breakpoint Trap", .index = 3, .error_code = false}, Exception{.name = "Overflow Trap", .index = 4, .error_code = false}, Exception{.name = "Bounds Fault", .index = 5, .error_code = false}, Exception{.name = "Invalid Opcode", .index = 6, .error_code = false}, Exception{.name = "Device Not Available", .index = 7, .error_code = false}, Exception{.name = "Double Fault", .index = 8, .error_code = true}, Exception{.name = "Coprocessor Segment Overrun", .index = 9, .error_code = false}, Exception{.name = "Invalid TSS", .index = 10, .error_code = true}, Exception{.name = "Segment Not Present", .index = 11, .error_code = true}, Exception{.name = "Stack-Segment Fault", .index = 12, .error_code = true}, Exception{.name = "General Protection Fault", .index = 13, .error_code = true}, Exception{.name = "Page Fault", .index = 14, .error_code = true}, Exception{.name = "x87 Floating-Point Exception", .index = 16, .error_code = false}, Exception{.name = "Alignment Check", .index = 17, .error_code = true}, Exception{.name = "Machine Check", .index = 18, .error_code = false}, Exception{.name = "SIMD Floating-Point Exception", .index = 19, .error_code = false}, Exception{.name = "Virtualization Exception", .index = 20, .error_code = false}, Exception{.name = "Security Exception", .index = 30, .error_code = true}, }; // 8259 Programmable Interrupt Controller (PIC) ============================== pub const pic = struct { const irq_0_7_interrupt_offset: u8 = 32; const irq_8_15_interrupt_offset: u8 = irq_0_7_interrupt_offset + 8; const irq_0_7_command_port: u16 = 0x20; const irq_0_7_data_port: u16 = 0x21; const irq_8_15_command_port: u16 = 0xA0; const irq_8_15_data_port: u16 = 0xA1; const read_irr_command: u8 = 0x0a; const read_isr_command: u8 = 0x0b; const init_command: u8 = 0x11; const reset_command: u8 = 0x20; fn busywork() callconv(.Inline) void { asm volatile ( \\add %%ch, %%bl \\add %%ch, %%bl ); } fn irq_mask(irq: u8) callconv(.Inline) u8 { var offset = irq; if (irq >= 8) { offset -= 8; } return @as(u8, 1) << @intCast(u3, offset); } pub fn is_spurious_irq(irq: u8) bool { var port = irq_0_7_command_port; if (irq >= 8) { port = irq_8_15_command_port; } putil.out8(port, read_isr_command); const rv = putil.in8(port) & irq_mask(irq) == 0; return rv; } pub fn end_of_interrupt(irq: u8, spurious: bool) void { const chained = irq >= 8; if (chained and !spurious) { putil.out8(irq_8_15_command_port, reset_command); } if (!spurious or (chained and spurious)) { putil.out8(irq_0_7_command_port, reset_command); } busywork(); } pub fn allow_irq(irq: u8, enabled: bool) void { // TODO if (!enabled) { @panic("Trying to use allow_irq(*, false)"); } var port = irq_0_7_data_port; if (irq >= 8) { port = irq_8_15_data_port; } putil.out8(port, putil.in8(port) & ~irq_mask(irq)); busywork(); } pub fn init() void { // Start Initialization of PICs putil.out8(irq_0_7_command_port, init_command); busywork(); putil.out8(irq_8_15_command_port, init_command); busywork(); // Set Interrupt Number Offsets for IRQs putil.out8(irq_0_7_data_port, irq_0_7_interrupt_offset); busywork(); putil.out8(irq_8_15_data_port, irq_8_15_interrupt_offset); busywork(); // Tell PICs About Each Other putil.out8(irq_0_7_data_port, 4); busywork(); putil.out8(irq_8_15_data_port, 2); busywork(); // Set Mode of PICs putil.out8(irq_0_7_data_port, 1); busywork(); putil.out8(irq_8_15_data_port, 1); busywork(); // Disable All IRQs for Now... putil.out8(irq_0_7_data_port, 0xff); busywork(); putil.out8(irq_8_15_data_port, 0xff); busywork(); // Expect for 2 which chains the secondary PIC. allow_irq(2, true); // Enable Interrupts putil.enable_interrupts(); } }; pub var in_tick = false; fn tick(irq_number: u32, interrupt_stack: *const Stack) void { _ = irq_number; _ = interrupt_stack; in_tick = true; if (kthreading.debug) print.char('!'); kernel.threading_mgr.yield(); in_tick = false; } pub fn init() void { table_pointer.limit = @sizeOf(Entry) * table.len; table_pointer.base = @ptrToInt(&table); // TODO: See top of file const kernel_code_selector = @import("segments.zig").kernel_code_selector; print.debug_string(" - Filling the Interrupt Descriptor Table (IDT)\n"); const debug_print_value = print.debug_print; print.debug_print = false; // Too many lines comptime var interrupt_number = 0; comptime var exceptions_index = 0; @setEvalBranchQuota(2000); inline while (interrupt_number < 150) { if (exceptions_index < exceptions.len and exceptions[exceptions_index].index == interrupt_number) { exceptions_index += 1; } else { HardwareErrorInterruptHandler(interrupt_number, false).set( "Unknown Interrupt", kernel_code_selector, kernel_flags); } interrupt_number += 1; } print.debug_print = debug_print_value; inline for (exceptions) |ex| { HardwareErrorInterruptHandler(ex.index, ex.error_code).set( ex.name, kernel_code_selector, kernel_flags); } InterruptHandler(50, PanicMessage(Stack).show).set( "Software Panic", kernel_code_selector, kernel_flags); InterruptHandler(system_calls.interrupt_number, system_calls.handle).set( "System Call", kernel_code_selector, user_flags); IrqInterruptHandler(0, tick).set( "IRQ0: Timer", kernel_code_selector, kernel_flags); load(); pic.init(); } pub fn get_name(index: u32) []const u8 { return if (index < names.len) names[index] else invalid_index ++ " and out of range"; } pub fn is_exception(index: u32) bool { return index <= exceptions.len; }
0
repos/georgios/kernel
repos/georgios/kernel/platform/code_point_437.zig
// Generated by scripts/codegen/code_page_437.py // This is data just used by cga_console.zig pub const bucket_count: u16 = 154; pub const max_bucket_length: u16 = 4; pub const max_hash_used: u16 = 152; pub const hash_table = [_]u32 { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x01fc207f, 0x00000000, 0x00000000, 0x00000000, 0x01cd2550, 0x00000000, 0x00000000, 0x00000000, 0x01ba2551, 0x00000000, 0x00000000, 0x00000000, 0x01d52552, 0x01ff00a0, 0x00000000, 0x00000000, 0x01d62553, 0x01ad00a1, 0x01e403a3, 0x00000000, 0x01c92554, 0x019b00a2, 0x00000000, 0x00000000, 0x01b82555, 0x019c00a3, 0x00000000, 0x00000000, 0x01b72556, 0x01e803a6, 0x00000000, 0x00000000, 0x01bb2557, 0x019d00a5, 0x00000000, 0x00000000, 0x01d42558, 0x00000000, 0x00000000, 0x00000000, 0x01d32559, 0x011500a7, 0x01ea03a9, 0x00000000, 0x01c8255a, 0x00000000, 0x00000000, 0x00000000, 0x01be255b, 0x00000000, 0x00000000, 0x00000000, 0x01bd255c, 0x01a600aa, 0x00000000, 0x00000000, 0x01bc255d, 0x01ae00ab, 0x00000000, 0x00000000, 0x01c6255e, 0x01aa00ac, 0x00000000, 0x00000000, 0x01c7255f, 0x00000000, 0x00000000, 0x00000000, 0x01cc2560, 0x00000000, 0x00000000, 0x00000000, 0x01b52561, 0x01e003b1, 0x00000000, 0x00000000, 0x01b62562, 0x01f800b0, 0x00000000, 0x00000000, 0x01b92563, 0x01f100b1, 0x01f02261, 0x00000000, 0x01d12564, 0x01fd00b2, 0x01eb03b4, 0x00000000, 0x01d22565, 0x01ee03b5, 0x00000000, 0x00000000, 0x01cb2566, 0x01f32264, 0x00000000, 0x00000000, 0x01cf2567, 0x01e600b5, 0x01f22265, 0x00000000, 0x01d02568, 0x011400b6, 0x00000000, 0x00000000, 0x01ca2569, 0x01fa00b7, 0x00000000, 0x00000000, 0x01d8256a, 0x017f2302, 0x00000000, 0x00000000, 0x01d7256b, 0x00000000, 0x00000000, 0x00000000, 0x01ce256c, 0x01a700ba, 0x00000000, 0x00000000, 0x01af00bb, 0x00000000, 0x00000000, 0x00000000, 0x01ac00bc, 0x00000000, 0x00000000, 0x00000000, 0x01ab00bd, 0x00000000, 0x00000000, 0x00000000, 0x01e303c0, 0x00000000, 0x00000000, 0x00000000, 0x01a800bf, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x01e503c3, 0x00000000, 0x00000000, 0x00000000, 0x01e703c4, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x018e00c4, 0x01ed03c6, 0x00000000, 0x00000000, 0x018f00c5, 0x019e20a7, 0x00000000, 0x00000000, 0x019200c6, 0x01a92310, 0x00000000, 0x00000000, 0x018000c7, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x019000c9, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x01df2580, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x01a500d1, 0x00000000, 0x00000000, 0x00000000, 0x01dc2584, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x019900d6, 0x01db2588, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x01072022, 0x01dd258c, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x019a00dc, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x01de2590, 0x00000000, 0x00000000, 0x00000000, 0x01e100df, 0x01b02591, 0x00000000, 0x00000000, 0x018500e0, 0x01b12592, 0x00000000, 0x00000000, 0x01a000e1, 0x01b22593, 0x00000000, 0x00000000, 0x018300e2, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x018400e4, 0x00000000, 0x00000000, 0x00000000, 0x018600e5, 0x00000000, 0x00000000, 0x00000000, 0x019100e6, 0x00000000, 0x00000000, 0x00000000, 0x018700e7, 0x00000000, 0x00000000, 0x00000000, 0x018a00e8, 0x01c42500, 0x00000000, 0x00000000, 0x018200e9, 0x00000000, 0x00000000, 0x00000000, 0x018800ea, 0x01b32502, 0x00000000, 0x00000000, 0x018900eb, 0x00000000, 0x00000000, 0x00000000, 0x018d00ec, 0x00000000, 0x00000000, 0x00000000, 0x01a100ed, 0x00000000, 0x00000000, 0x00000000, 0x018c00ee, 0x0101263a, 0x01fe25a0, 0x00000000, 0x018b00ef, 0x0102263b, 0x00000000, 0x00000000, 0x010f263c, 0x00000000, 0x00000000, 0x00000000, 0x01a400f1, 0x00000000, 0x00000000, 0x00000000, 0x019500f2, 0x00000000, 0x00000000, 0x00000000, 0x01a200f3, 0x00000000, 0x00000000, 0x00000000, 0x019300f4, 0x0113203c, 0x01da250c, 0x010c2640, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x019400f6, 0x010b2642, 0x00000000, 0x00000000, 0x01f600f7, 0x00000000, 0x00000000, 0x00000000, 0x019f0192, 0x01bf2510, 0x00000000, 0x00000000, 0x019700f9, 0x00000000, 0x00000000, 0x00000000, 0x01a300fa, 0x011625ac, 0x00000000, 0x00000000, 0x019600fb, 0x00000000, 0x00000000, 0x00000000, 0x018100fc, 0x01c02514, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x019800ff, 0x00000000, 0x00000000, 0x00000000, 0x01d92518, 0x011e25b2, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x01f92219, 0x00000000, 0x00000000, 0x00000000, 0x01fb221a, 0x01c3251c, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x01ec221e, 0x011025ba, 0x00000000, 0x00000000, 0x011c221f, 0x00000000, 0x00000000, 0x00000000, 0x011f25bc, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x01b42524, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x011125c4, 0x00000000, 0x00000000, 0x00000000, 0x01ef2229, 0x00000000, 0x00000000, 0x00000000, 0x011b2190, 0x01c2252c, 0x01062660, 0x00000000, 0x01182191, 0x00000000, 0x00000000, 0x00000000, 0x011a2192, 0x00000000, 0x00000000, 0x00000000, 0x01192193, 0x01052663, 0x00000000, 0x00000000, 0x011d2194, 0x00000000, 0x00000000, 0x00000000, 0x01122195, 0x010925cb, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x01c12534, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x01c5253c, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x010825d8, 0x00000000, 0x00000000, 0x00000000, 0x010a25d9, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x01e20393, 0x00000000, 0x00000000, 0x00000000, 0x011721a8, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x01e90398, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x01f72248, 0x00000000, 0x00000000, 0x00000000, }; pub fn contiguous_ranges(c: u16) ?u8 { if (c >= 0x0020 and c <= 0x007e) return @intCast(u8, c); if (c >= 0x2320 and c <= 0x2321) return @intCast(u8, c - 0x222c); if (c >= 0x2665 and c <= 0x2666) return @intCast(u8, c - 0x2662); if (c >= 0x266a and c <= 0x266b) return @intCast(u8, c - 0x265d); return null; }
0
repos/georgios/kernel
repos/georgios/kernel/platform/usb.zig
// ============================================================================ // Universal Serial Bus (USB) Enhanced Host Controller Interface (EHCI) // // References: // "USB: The Universal Serial Bus" by Benjamin David Lunt 3rd Edition // // ============================================================================ const kernel = @import("root").kernel; const print = kernel.print; const memory = kernel.memory; const platform = @import("platform.zig"); const pci = @import("pci.zig"); const interrupts = @import("interrupts.zig"); const segments = @import("segments.zig"); const timing = @import("timing.zig"); const ps2 = @import("ps2.zig"); const Error = memory.MemoryError; const StructParams = packed struct { port_count: u4, // N_PORTS port_power_control: bool, // PPC reserved0: u2, port_routing_rules: bool, ports_per_companion: u4, // N_PCC companion_count: u4, // N_CC port_indicator: bool, // P_INDICATOR reserved1: u3, debug_port_number: u4, reserved2: u8, }; const CapParams = packed struct { has_64b_addr: bool, programmable_frame_list: bool, async_schedule_park: bool, reserved0: bool, isochronous_scheduling_threshold: u4, extended_caps_offset: u8, reserved1: u16, // 4 bits at the start of this are used by v1.1 }; const CapRegs = packed struct { length: u8, // CAPLENGTH reserved: u8, version: u16, // HCIVERSION _struct_params: StructParams, // HCSPARAMS _cap_params: CapParams, // HCCPARAMS pub fn get_struct_params(self: *const CapRegs) StructParams { return self._struct_params; } pub fn get_cap_params(self: *const CapRegs) CapParams { return self._cap_params; } pub fn get(virtual_range: memory.Range) *const CapRegs { return @intToPtr(*const CapRegs, virtual_range.start); } // HCSP-PORTROUTE is after HCCPARAMS, but its size depends on CAPLENGTH and // its validity depends on struct_params. pub fn get_companion_port_route(self: *const CapRegs, index: usize) ?u4 { if (!self.get_struct_params().port_routing_rules) return null; const count = (@as(usize, self.length) - @sizeOf(CapRegs)) / 2; if (index >= count) return null; const byte = @intToPtr(*const u8, @ptrToInt(self) + @sizeOf(CapRegs) + index / 2).*; return @truncate(u4, byte >> (@truncate(u3, index & 1) << 2)); } pub fn get_op_regs(self: *const CapRegs) *OpRegs { return @intToPtr(*OpRegs, @ptrToInt(self) + self.length); } pub fn get_port_regs(self: *const CapRegs) []PortReg { return @intToPtr([*]PortReg, @ptrToInt(self.get_op_regs()) + @sizeOf(OpRegs)) [0..self.get_struct_params().port_count]; } pub fn get_extended_caps_id_offset(self: *const CapRegs, dev: *pci.Dev, id: u8) ?u8 { // Lunt Pages 7-8 and M-7 var offset = self.get_cap_params().extended_caps_offset; while (true) { const value = dev.read(u32, offset); const this_id = @truncate(u8, value); if (this_id == id) { return offset; } const next = @truncate(u8, value >> 8); if (next == 0) { break; } offset += next; } return null; } }; const Command = packed struct { // Lunt Table 7-10 // TODO: Zig Compiler crashes: "TODO buf_read_value_bytes enum packed" // const FrameListSize = enum(u2) { // e1024 = 0b00, // e512 = 0b01, // e256 = 0b10, // e32 = 0b11, // }; run: bool, // RS reset: bool, // HCRESET // frame_list_size: FrameListSize, frame_list_size: u2, period_schedule_enabled: bool, async_schedule_enabled: bool, async_doorbell_interrupt: bool, light_host_reset: bool, async_park_mode_count: u2, reserved0: bool, async_park_mode_enabled: bool, reserved1: u4, interrupt_threshold: u8, reserved2: u8, pub fn init(self: *Command) void { var new = @bitCast(Command, @as(u32, 0)); new.interrupt_threshold = 8; // new.async_schedule_enabled = true; // new.period_schedule_enabled = true; // new.frame_list_size = FrameListSize.e1024; new.run = true; self.* = new; } }; /// Lunt Table 7-12 const Status = packed struct { transfer_interrupt: bool, error_interrupt: bool, port_change_detect: bool, frame_list_rollover: bool, host_system_error: bool, doorbell_interrupt: bool, reserved0: u6, halted: bool, reclamation: bool, periodic_schedule_status: bool, async_schedule_status: bool, reserved1: u16, pub fn clear(self: *Status) void { self.* = @bitCast(Status, @as(u32, 0x3f)); } }; /// Lunt Table 7-13 const Interrupts = packed struct { enabled: bool, error_enabled: bool, port_change_enabled: bool, frame_list_rollover_enabled: bool, host_system_error_enabled: bool, async_advance_enabled: bool, reserved0: u26, }; /// Lunt Table 7-22 const PortReg = packed struct { connected: bool, // Read-only status_changed: bool, // enabled: bool, // Read/Write only false enabled_changed: bool, // over_current: bool, // Read-only over_current_changed: bool, // force_port_resume: bool, // Read/Write suspended: bool, // Read/Write reset: bool, // Read/Write reserved0: bool, status: u2, // Read-only power: bool, // Read-only or Read/Write if port_power_control is true release_ownership: bool, // Read/Write indicator_control: u2, // test_control: u4, // Read/Write wake_on_connect: bool, // Read/Write wake_on_disconnect: bool, // Read/Write wake_on_over_current: bool, // Read/Write reserved1: u9, }; /// Lunt Table 7-8 const OpRegs = packed struct { command: Command, // USBCMD status: Status, // USBSTS interrupts: Interrupts, // USBINTR frame_index: u32, // FRINDEX segment_selector: u32, // CTRLDSSEGMENT frame_list_address: u32, // PERIODICLISTBASE next_async_list: u32, // ASYNCLISTADDR reserved: u288, config_flag: u32, // CONFIGFLAG // PORTSC is after this, see CapRegs.get_port_regs() }; pub fn interrupt(interrupt_number: u32, interrupt_stack: *const interrupts.Stack) void { _ = interrupt_number; _ = interrupt_stack; print.string("USB INT\n"); } var frame_list: ?[]u32 = null; pub fn init(dev: *pci.Dev) void { const indent = " - "; // Zero out PCI Capabilities Pointer and Reserved? // From Lunt in Step 2 on Chapter 2 Page 10 dev.write(u32, 0x34, 0); dev.write(u32, 0x38, 0); // Setup Interrupt Handler const irq: u8 = 51; interrupts.IrqInterruptHandler(irq, interrupt).set( "USB", segments.kernel_code_selector, interrupts.kernel_flags); interrupts.load(); dev.write(u8, 0x3c, irq); // Use Memory-Mapped I/O // This can be set to 5 to use Port I/O, but memory is easier to use. dev.write(u16, 0x04, 0x0006); // Map Controller's Address Space const physical_range = dev.base_addresses[0].?.memory.range; const pmem = &kernel.memory_mgr.impl; const range = pmem.get_unused_kernel_space(physical_range.size) catch @panic("usb.init: get_unused_kernel_space failed"); pmem.map(range, physical_range.start, false) catch @panic("usb.init: map failed"); ps2.anykey(); // Get Controller Registers const cap_regs = CapRegs.get(range); const op_regs = cap_regs.get_op_regs(); // Turn Off BIOS USB to PS/2 Emulation if (cap_regs.get_cap_params().extended_caps_offset >= 0x40) { // Find the USB Legacy Support if (cap_regs.get_extended_caps_id_offset(dev, 1)) |offset| { // Set the "System Software Owned Semaphore" Bit // Lunt Pages M-9 dev.write(u32, offset, dev.read(u32, offset) | (1 << 24)); } } // Reset the Controller var reset_timeout: u8 = 30; // Lunt says 20ms, but do 30ms to be safe. { var copy = op_regs.command; copy.run = false; copy.reset = true; op_regs.command = copy; } while (reset_timeout > 0) { var copy = op_regs.command; if (!copy.reset) break; timing.wait_milliseconds(1); reset_timeout -= 1; } { var copy = op_regs.command; if (copy.reset) { print.string(indent ++ "EHCI Controller failed to respond to reset\n"); return; } } print.string(indent ++ "EHCI Controller Reset\n"); frame_list = kernel.memory_mgr.big_alloc.alloc_array(u32, 1024) catch @panic("usb.init: alloc frame_list failed"); // Initialize the Controller var int_copy = op_regs.interrupts; int_copy.enabled = true; int_copy.error_enabled = true; int_copy.port_change_enabled = true; op_regs.interrupts = int_copy; op_regs.frame_index = 0; op_regs.segment_selector = 0; op_regs.frame_list_address = @ptrToInt(frame_list.?.ptr); // op_regs.next_async_list = 0; // TODO op_regs.status.clear(); op_regs.command.init(); op_regs.config_flag = 1; print.string(indent ++ "EHCI Controller Initialized\n"); const power_control = cap_regs.get_struct_params().port_power_control; for (cap_regs.get_port_regs()) |*port_reg, i| { // For some reason the accessing the ports registers in QEMU must be // done as a whole. var copy = port_reg.*; // Check to see if we need to power the port if (power_control and !copy.power) { copy.power = true; port_reg.* = copy; timing.wait_milliseconds(30); copy = port_reg.*; } if (!copy.connected) continue; // No device // Reset the Port Lunt 7-25 copy.reset = true; copy.enabled = false; port_reg.* = copy; copy = port_reg.*; while (!copy.reset) { copy = port_reg.*; } timing.wait_milliseconds(50); copy.reset = false; port_reg.* = copy; copy = port_reg.*; while (copy.reset) { copy = port_reg.*; } if (!copy.enabled) { // Not a high-speed device, release ownership to another controller copy.release_ownership = true; port_reg.* = copy; continue; } print.format("Port {}: {}\n", .{i, copy}); } }
0
repos/georgios/kernel
repos/georgios/kernel/platform/pci.zig
// PCI Interface // Based on https://wiki.osdev.org/PCI const builtin = @import("builtin"); const utils = @import("utils"); const kernel = @import("root").kernel; const print = kernel.print; const fprint = kernel.fprint; const io = kernel.io; const memory = kernel.memory; const putil = @import("util.zig"); const ata = @import("ata.zig"); const ps2 = @import("ps2.zig"); const usb = @import("usb.zig"); const Class = enum (u16) { IDE_Controller = 0x0101, Floppy_Controller = 0x0102, ATA_Controller = 0x0105, SATA_Controller = 0x0106, Ethernet_Controller = 0x0200, VGA_Controller = 0x0300, PCI_Host_Bridge = 0x0600, ISA_Bridge = 0x0601, PCI_To_PCI_Bridge = 0x0604, Bridge = 0x0680, USB_Controller = 0x0C03, Unknown = 0xFFFF, pub fn from_u16(value: u16) ?Class { return utils.int_to_enum(@This(), value); } pub fn to_string(self: Class) []const u8 { return switch (self) { .IDE_Controller => "IDE Controller", .Floppy_Controller => "Floppy Controller", .ATA_Controller => "ATA Controller", .SATA_Controller => "SATA Controller", .Ethernet_Controller => "Ethernet Controller", .VGA_Controller => "VGA Controller", .PCI_Host_Bridge => "PCI Host Bridge", .ISA_Bridge => "ISA Bridge", .PCI_To_PCI_Bridge => "PCI to PCI Bridge", .Bridge => "Bridge", .USB_Controller => "USB Controller", .Unknown => "Unknown", }; } }; pub const Bus = u8; pub const Device = u5; pub const Function = u3; pub const Offset = u8; pub const Location = packed struct { function: Function, device: Device, bus: Bus, }; const Config = packed struct { offset: Offset, location: Location, reserved: u7 = 0, enabled: bool = true, }; fn config_port(comptime Type: type, location: Location, offset: Offset) callconv(.Inline) u16 { const config = Config{ .offset = offset & 0xFC, .location = location, }; putil.out(u32, 0x0CF8, @bitCast(u32, config)); return 0x0CFC + @intCast(u16, if (Type == u32) 0 else (offset & 3)); } pub fn read_config(comptime Type: type, location: Location, offset: Offset) callconv(.Inline) Type { return putil.in(Type, config_port(Type, location, offset)); } pub fn write_config(comptime Type: type, location: Location, offset: Offset, value: Type) callconv(.Inline) void { putil.out(Type, config_port(Type, location, offset), value); } pub const Header = packed struct { pub const Kind = enum (u8) { Normal = 0x00, MultiFunctionNormal = 0x80, PciToPciBridge = 0x01, MultiFunctionPciToPciBridge = 0x81, CardBusBridge = 0x02, MultiFunctionCardBusBridge = 0x82, pub fn from_u8(value: u8) ?Kind { return utils.int_to_enum(@This(), value); } pub fn to_string(self: Kind) []const u8 { return switch (self) { .Normal => "Normal", .MultiFunctionNormal => "Multi-Function Normal", .PciToPciBridge => "PCI-to-PCI Bridge", .MultiFunctionPciToPciBridge => "Multi-Function PCI-to-PCI Bridge", .CardBusBridge => "CardBus Bridge", .MultiFunctionCardBusBridge => "Multi-Function CardBus Bridge", }; } pub fn is_multifunction(self: Kind) bool { return switch (self) { .MultiFunctionNormal => true, .MultiFunctionPciToPciBridge => true, .MultiFunctionCardBusBridge => true, else => false, }; } }; pub const SuperClass = enum (u8) { UnclassifiedDevice = 0x00, MassStorageController = 0x01, NetworkController = 0x02, DisplayController = 0x03, MultimediaController = 0x04, MemoryController = 0x05, BridgeDevice = 0x06, SimpleCommunicationsController = 0x07, GenericSystemPeripheral = 0x08, InputDeviceController = 0x09, DockingStation = 0x0A, Processor = 0x0B, SerialBusController = 0x0C, WirelessController = 0x0D, IntelligentController = 0x0E, SatelliteCommunicationsController = 0x0F, EncryptionController = 0x10, SignalProcessingController = 0x11, ProcessingAccelerator = 0x12, NonEssentialInstrumentation = 0x13, Coprocessor = 0x40, pub fn from_u8(value: u8) ?SuperClass { return utils.int_to_enum(@This(), value); } pub fn to_string(self: SuperClass) []const u8 { return switch (self) { .UnclassifiedDevice => "Unclassified Device", .MassStorageController => "Mass Storage Controller", .NetworkController => "Network Controller", .DisplayController => "Display Controller", .MultimediaController => "Multimedia Controller", .MemoryController => "Memory Controller", .BridgeDevice => "Bridge Device", .SimpleCommunicationsController => "Simple Communications Controller", .GenericSystemPeripheral => "Generic System Peripheral", .InputDeviceController => "Input Device Controller", .DockingStation => "Docking Station", .Processor => "Processor", .SerialBusController => "Serial Bus Controller", .WirelessController => "Wireless Controller", .IntelligentController => "Intelligent Controller", .SatelliteCommunicationsController => "Satellite Communications Controller", .EncryptionController => "Encryption Controller", .SignalProcessingController => "Signal Processing Controller", .ProcessingAccelerator => "Processing Accelerator", .NonEssentialInstrumentation => "Non-Essential Instrumentation", .Coprocessor => "Coprocessor", }; } }; vendor_id: u16 = 0, device_id: u16 = 0, command: u16 = 0, status: u16 = 0, revision_id: u8 = 0, prog_if: u8 = 0, subclass: u8 = 0, class: u8 = 0, cache_line_size: u8 = 0, latency_timer: u8 = 0, header_type: u8 = 0, bist: u8 = 0, pub fn is_invalid(self: *const Header) bool { return self.vendor_id == 0xFFFF; } pub fn get_header_type(self: *const Header) ?Kind { return Kind.from_u8(self.header_type); } pub fn get_class(self: *const Header) ?SuperClass { return SuperClass.from_u8(self.class); } pub fn print(self: *const Header, file: *io.File) io.FileError!void { try fprint.format(file, \\ - PCI Header: \\ - vendor_id: {:x} \\ - device_id: {:x} \\ - command: {:x} \\ - status: {:x} \\ - revision_id: {:x} \\ - prog_if: {:x} \\ - subclass: {:x} \\ - class: , .{ self.vendor_id, self.device_id, self.command, self.status, self.revision_id, self.prog_if, self.subclass}); if (self.get_class()) |class| { try fprint.format(file, " {}", .{class.to_string()}); } else { try fprint.format(file, " Unknown Class {:x}", .{self.class}); } try fprint.format(file, \\ \\ - cache_line_size: {:x} \\ - latency_timer: {:x} \\ - header_type: , .{ self.cache_line_size, self.latency_timer}); if (self.get_header_type()) |header_type| { try fprint.format(file, " {}", .{header_type.to_string()}); } else { try fprint.format(file, " Unknown Value {:x}", .{self.header_type}); } try fprint.format(file, \\ \\ - bist: {:x} \\ , .{self.bist}); } pub fn get(location: Location) Header { const Self = @This(); var rv: [@sizeOf(Self)]u8 = undefined; for (rv[0..]) |*ptr, i| { ptr.* = read_config(u8, location, @intCast(Offset, i)); } return @bitCast(Self, rv); } }; pub const Dev = struct { pub const BaseAddress = union(enum) { // TODO // Io: struct { // port: u16, // }, memory: struct { range: memory.Range, // TODO // prefetchable: bool, // is64b: bool, }, }; location: Location, header: Header, base_addresses: [6]?BaseAddress = [_]?BaseAddress {null} ** 6, fn read_base_addresses(self: *Dev) void { for (self.base_addresses[0..]) |*ptr, i| { const offset = @sizeOf(Header) + 4 * @intCast(Offset, i); const raw_entry = read_config(u32, self.location, offset); if (raw_entry == 0) { continue; } if (raw_entry & 1 == 1) { // TODO print.format(" - BAR {}: I/O Entry (TODO)\n", .{i}); continue; } const address = raw_entry & ~@as(u32, 0xf); write_config(u32, self.location, offset, 0xffffffff); const size = ~(read_config(u32, self.location, offset) & ~@as(u32, 1)) +% 1; write_config(u32, self.location, offset, raw_entry); print.format(" - BAR {}: {:a}+{:x}\n", .{i, address, size}, ); ptr.* = BaseAddress{.memory = .{.range = .{.start = address, .size = size}}}; } } pub fn init(self: *Dev) void { if (self.header.get_header_type()) |header_type| { if (header_type == .Normal) { self.read_base_addresses(); } } } pub fn read(self: *Dev, comptime Type: type, offset: Offset) Type { return read_config(Type, self.location, offset); } pub fn write(self: *Dev, comptime Type: type, offset: Offset, value: Type) void { write_config(Type, self.location, offset, value); } }; fn check_function(location: Location, header: *const Header) void { if (header.is_invalid()) return; print.format(" - Bus {}, Device {}, Function {}\n", .{location.bus, location.device, location.function}); _ = header.print(print.get_console_file().?) catch {}; if (header.get_class()) |class| { var dev = Dev{.location = location, .header = header.*}; dev.init(); if (class == .MassStorageController and header.subclass == 0x01) { ata.init(&dev); } else if (class == .SerialBusController and header.subclass == 0x03 and header.prog_if == 0x20) { usb.init(&dev); } ps2.anykey(); if (class == .BridgeDevice and header.subclass == 0x04) { check_bus(read_config(u8, location, 0x19)); } } } fn check_device(bus: Bus, device: Device) void { const root_location = Location{.bus = bus, .device = device, .function = 0}; const header = Header.get(root_location); check_function(root_location, &header); if (header.get_header_type()) |header_type| { if (header_type.is_multifunction()) { // Header Type is Multi-Function, Check Them var i: Function = 1; while (true) : (i += 1) { const location = Location{ .bus = bus, .device = device, .function = i}; const subheader = Header.get(location); check_function(location, &subheader); if (i == 7) break; } } } } fn check_bus(bus: u8) void { var i: Device = 0; while (true) : (i += 1) { check_device(bus, i); if (i == 31) break; } } pub fn find_pci_devices() void { print.string(" - Seaching for PCI Devices\n"); check_bus(0); }
0
repos/georgios/kernel
repos/georgios/kernel/platform/linking.ld
/* * This file defines the layout of the kernel itself and allows the kernel to * access this information through symbols. The most important aspect of this * is the real vs virtual kernel. Very early in boot this maps the lower real * memory of the kernel into a much higher virtual address that becomes the * start of the kernel mode memory space. See * https://wiki.osdev.org/Higher_Half_Kernel for info. */ ENTRY(kernel_start) /* Basic constants */ _REAL_START = 1M; _VIRTUAL_OFFSET = 3 << 30; /* 3 Gi */ _FRAME_SIZE = 4K; /* Derived Values */ _VIRTUAL_START = _REAL_START + _VIRTUAL_OFFSET; _REAL_END = _VIRTUAL_END - _VIRTUAL_OFFSET; _KERNEL_SIZE = _REAL_END - _REAL_START; _VIRTUAL_LOW_START = _REAL_LOW_START + _VIRTUAL_OFFSET; _VIRTUAL_LOW_END = _REAL_LOW_END + _VIRTUAL_OFFSET; /* Create some low versions of symbols we need */ low_page_directory = active_page_directory - _VIRTUAL_OFFSET; low_multiboot_info = multiboot_info - _VIRTUAL_OFFSET; low_kernel_range_start_available = kernel_range_start_available - _VIRTUAL_OFFSET; low_kernel_page_table_count = kernel_page_table_count - _VIRTUAL_OFFSET; low_kernel_page_tables = kernel_page_tables - _VIRTUAL_OFFSET; SECTIONS { /* * Start of the "low" kernel, which is mapped to < _VIRTUAL_OFFSET. * This memory will be recycled after it is no longer needed. * TODO: Check if physical memory is being reused * The virtual memory will be used to bootstrap and maintain memory * management. */ . = _REAL_START; _REAL_LOW_START = .; .low_text ALIGN(_FRAME_SIZE) : { *(.multiboot) *(.low_text) } .low_bss ALIGN(_FRAME_SIZE) : { *(.low_bss) } /* * Force extra space for frame access slots */ .low_force_space_begin_align ALIGN(_FRAME_SIZE) : { BYTE(0) } .low_force_space_end_align ALIGN(_FRAME_SIZE) : {} _REAL_LOW_END = .; /* * Start of the "high" kernel, which is mapped to >= _VIRTUAL_OFFSET. */ . += _VIRTUAL_OFFSET; .text ALIGN(_FRAME_SIZE) : AT(ADDR(.text) - _VIRTUAL_OFFSET) { *(.text) } .rodata ALIGN(_FRAME_SIZE) : AT(ADDR(.rodata) - _VIRTUAL_OFFSET) { *(.rodata) } .data ALIGN(_FRAME_SIZE) : AT(ADDR(.data) - _VIRTUAL_OFFSET) { *(.data) } .bss ALIGN(_FRAME_SIZE) : AT(ADDR(.bss) - _VIRTUAL_OFFSET) { *(COMMON) *(.bss) } _VIRTUAL_END = .; }
0
repos/georgios/kernel
repos/georgios/kernel/platform/vbe.zig
// VESA BIOS Extensions (VBE) Version 2 // // https://en.wikipedia.org/wiki/VESA_BIOS_Extensions // https://wiki.osdev.org/VESA_Video_Modes const std = @import("std"); const build_options = @import("build_options"); const utils = @import("utils"); const U32Point = utils.U32Point; const I32Point = utils.I32Point; const U32Rect = utils.U32Rect; const multiboot = @import("multiboot.zig"); const pmemory = @import("memory.zig"); const putil = @import("util.zig"); const bios_int = @import("bios_int.zig"); const vbe_console = @import("vbe_console.zig"); const kernel = @import("root").kernel; const print = kernel.print; const kmemory = kernel.memory; const Range = kmemory.Range; const BitmapFont = kernel.BitmapFont; // TODO Make these not fixed const find_width = 800; const find_height = 600; const find_bpp = 24; const RealModePtr = packed struct { offset: u16, segment: u16, pub fn get(self: *const RealModePtr) u32 { return @intCast(u32, self.segment) * 0x10 + self.offset; } }; const Info = packed struct { const magic_expected = "VESA"; magic: [4]u8, version: u16, oem_ptr: RealModePtr, capabilities: u32, video_modes_ptr: RealModePtr, memory: u16, software_rev: u16, vendor: RealModePtr, product_name: RealModePtr, product_rev: RealModePtr, const Version = enum (u8) { V1 = 1, V2 = 2, V3 = 3, }; pub fn get_version(self: *const Info) ?Version { return utils.int_to_enum(Version, @intCast(u8, self.version >> 8)); } pub fn get_modes(self: *const Info) []const u16 { var mode_count: usize = 0; const modes_ptr = @intToPtr([*]const u16, self.video_modes_ptr.get()); while (modes_ptr[mode_count] != 0xffff) { mode_count += 1; } const modes = kernel.alloc.alloc_array(u16, mode_count) catch @panic("vbe.Info.get_modes: alloc mode array failed"); var mode_i: usize = 0; while (modes_ptr[mode_i] != 0xffff) { modes[mode_i] = modes_ptr[mode_i]; mode_i += 1; } return modes; } }; const Mode = packed struct { attributes: u16, window_a: u8, window_b: u8, granularity: u16, window_size: u16, segment_a: u16, segment_b: u16, win_func_ptr: u32, pitch: u16, width: u16, height: u16, w_char: u8, y_char: u8, planes: u8, bpp: u8, banks: u8, memory_model: u8, bank_size: u8, image_pages: u8, reserved0: u8, red_mask: u8, red_position: u8, green_mask: u8, green_position: u8, blue_mask: u8, blue_position: u8, reserved_mask: u8, reserved_position: u8, direct_color_attributes: u8, framebuffer: u32, off_screen_mem_off: u32, off_screen_mem_size: u16, }; var vbe_setup = false; var info: Info = undefined; var mode: Mode = undefined; var mode_id: ?u16 = null; pub fn get_res() ?U32Point { return if (vbe_setup) .{.x = mode.width, .y = mode.height} else null; } fn video_memory_offset(x: u32, y: u32) callconv(.Inline) u32 { return y * mode.pitch + x * bytes_per_pixel; } fn blend(dest: *u8, color: u8, alpha: u8) callconv(.Inline) void { dest.* = @truncate(u8, (@intCast(u32, color) * alpha + @intCast(u32, dest.*) * (0xff - alpha)) >> 8); } fn draw_pixel(x: u32, y: u32, color: u32) callconv(.Inline) void { const offset = video_memory_offset(x, y); if (offset + 2 < buffer.len) { const alpha = @truncate(u8, color >> 24); blend(&buffer[offset], @truncate(u8, color), alpha); blend(&buffer[offset + 1], @truncate(u8, color >> 8), alpha); blend(&buffer[offset + 2], @truncate(u8, color >> 16), alpha); buffer_clean = false; } } pub fn draw_glyph(font: *const BitmapFont, x: u32, y: u32, codepoint: u32, fg_color: u32, bg_color: u32) void { const glyph_holder = font.get(codepoint); var xp = x; var xe = x + font.bdf_font.bounds.size.x; var yp = y; var pixit = glyph_holder.iter_pixels(); while (pixit.next_pixel()) |is_filled| { draw_pixel(xp, yp, if (is_filled) fg_color else bg_color); xp += 1; if (xp >= xe) { xp = x; yp += 1; } } } pub fn draw_line(a: U32Point, b: U32Point, color: u32) void { const d = b.minus_point(a); if (d.x > 0) { var x = a.x; while (x <= b.x) { draw_pixel(x, a.y + d.y * (x - a.x) / d.x, color); x += 1; } } else { var y = a.y; while (y <= b.y) { draw_pixel(a.x, y, color); y += 1; } } } pub fn draw_rect(rect: *const U32Rect, color: u32) void { // a > b // V V // c > d const a = rect.pos; const d = rect.pos.plus_point(rect.size); const b = .{.x = d.x, .y = a.y}; const c = .{.x = a.x, .y = d.y}; draw_line(a, b, color); draw_line(a, c, color); draw_line(b, d, color); draw_line(c, d, color); } pub fn draw_raw_image_chunk(data: []const u8, w: u32, pos: *const U32Point, last: *U32Point) void { const pixels = std.mem.bytesAsSlice(u32, data); for (pixels) |px| { draw_pixel(pos.x + last.x, pos.y + last.y, px); last.x += 1; if (last.x >= w) { last.y += 1; last.x = 0; } } } pub fn draw_raw_image(data: []const u8, w: u32, x: u32, y: u32) void { var last = U32Point{}; draw_raw_image_chunk(data, w, .{.x = x, .y = y}, &last); } var buffer: []u8 = undefined; var buffer_clean: bool = false; var video_memory: []u8 = undefined; var bytes_per_pixel: u32 = undefined; pub fn fill_buffer(color: u32) void { var y: u32 = 0; while (y < mode.height) { var x: u32 = 0; while (x < mode.width) { draw_pixel(x, y, color); x += 1; } y += 1; } buffer_clean = false; } pub fn scroll_buffer(rows: u32, color: u32) void { // Move everthing in the buffer up buffer_clean = false; var dst_offset: usize = 0; var src_offset: usize = rows * mode.pitch; const end_src_offset = @as(usize, mode.height) * mode.pitch; const row_size = @as(usize, mode.width) * bytes_per_pixel; while (src_offset < end_src_offset) { const dst = buffer[dst_offset..dst_offset + row_size]; const src = buffer[src_offset..src_offset + row_size]; for (dst) |*p, i| { p.* = src[i]; } dst_offset += mode.pitch; src_offset += mode.pitch; } // Fill in the "new" pixels var y: u32 = mode.height - rows; while (y < mode.height) { var x: u32 = 0; while (x < mode.width) { draw_pixel(x, y, color); x += 1; } y += 1; } } fn buffer_sync() callconv(.Inline) void { while ((putil.in8(0x03da) & 0x8) != 0) {} while ((putil.in8(0x03da) & 0x8) == 0) {} } // TODO: This could certainly be done faster, maybe through unrolling the loop // some or CPU features like SSE. pub fn flush_buffer() void { if (buffer_clean) return; const b = Range.from_bytes(buffer).to_slice(u64); const vm = Range.from_bytes(video_memory).to_slice(u64); buffer_sync(); for (vm) |*p, i| { p.* = b[i]; } buffer_clean = true; } pub fn flush_buffer_rect(rect: *const U32Rect) void { buffer_sync(); var offset = video_memory_offset(rect.pos.x, rect.pos.y); var row = rect.pos.y; const end = rect.pos.y + rect.size.y; const row_size = rect.size.x * bytes_per_pixel; while (row < end and offset < buffer.len) { const row_end = @minimum(buffer.len, offset + row_size); const b = buffer[offset..row_end]; for (video_memory[offset..row_end]) |*p, i| { p.* = b[i]; } offset += mode.pitch; row += 1; } } pub fn fill_rect(rect: *const U32Rect, color: u32) void { var x: usize = rect.pos.x; const x_end = x + rect.size.x; var y: usize = rect.pos.y; const y_end = y + rect.size.y; while (y < y_end) { draw_pixel(x, y, color); x += 1; if (x >= x_end) { x = rect.pos.x; y += 1; } } flush_buffer_rect(rect); } const vbe_result_ptr: u16 = 0x8000; const VbeFuncArgs = struct { bx: u16 = 0, cx: u16 = 0, di: u16 = 0, slow: bool = false, }; fn vbe_func(name: []const u8, func_num: u16, args: VbeFuncArgs) bool { var params = bios_int.Params{ .interrupt = 0x10, .eax = func_num, .ebx = args.bx, .ecx = args.cx, .edi = args.di, .slow = args.slow, }; bios_int.run(&params) catch { print.format(" - vbe_func: {}: bios_int.run failed\n", .{name}); return false; }; if (@truncate(u16, params.eax) != 0x4f) { print.format(" - vbe_func: {}: failed, eax: {:x}\n", .{name, params.eax}); return false; } return true; } fn get_vbe_info() ?*const Info { const vbe2 = "VBE2"; // Set the interface to use VBE Version 2 _ = utils.memory_copy_truncate(@intToPtr([*]u8, vbe_result_ptr)[0..vbe2.len], vbe2); return if (vbe_func("get_vbe_info", 0x4f00, .{ .di = vbe_result_ptr })) @intToPtr(*const Info, vbe_result_ptr) else null; } fn get_mode_info(mode_number: u16) ?*const Mode { return if (vbe_func("get_mode_info", 0x4f01, .{ .cx = mode_number, .di = vbe_result_ptr })) @intToPtr(*const Mode, vbe_result_ptr) else null; } fn set_mode() void { vbe_setup = vbe_func("set_mode", 0x4f02, .{ .bx = mode_id.? | 0x4000, // Use Linear Buffer .slow = true, }); } pub fn init() void { if (!build_options.vbe) { return; } print.string(" - See if we can use VESA graphics..\n"); // First see GRUB setup VBE if (multiboot.get_vbe_info()) |vbe| { print.string(" - Got VBE info from Multiboot...\n"); info = @ptrCast(*Info, &vbe.control_info[0]).*; mode_id = vbe.mode; mode = @ptrCast(*Mode, &vbe.mode_info[0]).*; vbe_setup = true; } // Then see if we can set it up using the BIOS if (!vbe_setup) { // Get Info print.string(" - Trying to get VBE info directly from BIOS...\n"); info = (get_vbe_info() orelse return).*; print.format("{}\n", .{info}); if (info.get_version()) |version| { print.format("VERSION {}\n", .{version}); } // Find the Mode We're Looking For const supported_modes = info.get_modes(); defer kernel.alloc.free_array(supported_modes) catch unreachable; for (supported_modes) |supported_mode| { print.format(" - mode {:x}\n", .{supported_mode}); const mode_ptr = get_mode_info(supported_mode) orelse return; print.format(" - {}x{}x{}\n", .{ mode_ptr.width, mode_ptr.height, mode_ptr.bpp}); if ((mode_ptr.attributes & (1 << 7)) == 0) { print.string(" - Non-linear, skipping...\n"); continue; } if (mode_ptr.width == find_width and mode_ptr.height == find_height and mode_ptr.bpp == find_bpp) { mode = mode_ptr.*; mode_id = supported_mode; break; } } if (mode_id == null) { print.string(" - Didn't Find VBE Mode\n"); return; } // Set the Mode set_mode(); } if (vbe_setup) { print.string(" - Got VBE info\n"); if (info.get_version()) |version| { print.format("{}\n", .{version}); } print.format("{}\n", .{info}); print.format("{}\n", .{mode}); // TODO // if (mode.bpp != 32 and mode.bpp != 16) { // @panic("bpp is not 32 bits or 16 bits"); // } bytes_per_pixel = mode.bpp / 8; const video_memory_size = @as(usize, mode.height) * @as(usize, mode.pitch); // TODO: Zig Bug? If catch is taken away Zig 0.5 fails to reject not // handling the error return. LLVM catches the mistake instead. print.format("vms: {}\n", .{video_memory_size}); buffer = kernel.memory_mgr.big_alloc.alloc_array(u8, video_memory_size) catch { @panic("Couldn't alloc VBE Buffer"); }; const video_memory_range = kernel.memory_mgr.impl.get_unused_kernel_space( video_memory_size) catch { @panic("Couldn't Reserve VBE Buffer"); }; video_memory = @intToPtr([*]u8, video_memory_range.start)[0..video_memory_size]; kernel.memory_mgr.impl.map( video_memory_range, mode.framebuffer, false) catch { @panic("Couldn't map VBE Buffer"); }; kernel.builtin_font.init( &kernel.builtin_font_data.bdf, kernel.builtin_font_data.glyph_indices[0..], kernel.builtin_font_data.bitmaps[0..]) catch @panic("builtin_font.init failed"); vbe_console.init(mode.width, mode.height, &kernel.builtin_font); kernel.console = &vbe_console.console; } else { print.string(" - Could not init VBE graphics\n"); } }
0
repos/georgios/kernel
repos/georgios/kernel/platform/ata.zig
// ATA Drive Interface // // Also known as Parallel ATA or IDE. This is a simple PIO-based driver. // // For Reference See: // https://wiki.osdev.org/ATA_PIO_Mode // https://en.wikipedia.org/wiki/Parallel_ATA // FYSOS: Media Storage Devices https://www.amazon.com/dp/1514111888/ const std = @import("std"); const utils = @import("utils"); const kernel = @import("root").kernel; const console_writer = kernel.console_writer; const print = kernel.print; const io = kernel.io; const memory = kernel.memory; const MemoryError = memory.MemoryError; const Allocator = memory.Allocator; const devices = kernel.devices; const pci = @import("pci.zig"); const putil = @import("util.zig"); const timing = @import("timing.zig"); const Error = error { FailedToSelectDrive, Timeout, UnexpectedValues, OperationError, } || MemoryError; const log_indent = " "; const Sector = struct { const size: u64 = 512; address: u64, data: [size]u8 align(8) = undefined, }; const CommandStatus = packed struct { in_error: bool, unused_index: bool, unused_corrected: bool, data_ready: bool, unused_seek_complete: bool, fault: bool, drive_ready: bool, busy: bool, fn assert_selectable(self: *const CommandStatus) Error!void { if (self.busy or self.data_ready) { print.format("ERROR: assert_selectable: {}\n", .{self}); return Error.FailedToSelectDrive; } } // TODO: Make these checks simpler? fn drive_is_ready(self: *const CommandStatus) Error!bool { if (self.busy) { return false; } if (self.in_error or self.fault) { return Error.OperationError; } return self.drive_ready; } fn data_is_ready(self: *const CommandStatus) Error!bool { if (self.busy) { return false; } if (self.in_error or self.fault) { return Error.OperationError; } return self.data_ready; } }; const Control = packed struct { unused_bit_0: bool = false, interrupts_disabled: bool, reset: bool, unused_bits_3_7: u5 = 0, }; const DriveHeadSelect = packed struct { lba28_bits_24_27: u4 = 0, select_slave: bool, always_1_bit_5: bool = true, lba: bool = false, always_1_bit_7: bool = true, }; const IndentifyResults = struct { const Raw = packed struct { // Word 0 unused_word_0_bits_0_14: u15, is_atapi: bool, // Words 1 - 9 unused_words_1_9: [9]u16, // Words 10 - 19 serial_number: [10]u16, // Words 20 - 22 used_words_20_22: [3]u16, // Words 23 - 26 firmware_revision: [4]u16, // Words 27 - 46 model: [20]u16, // Words 47 - 48 used_words_47_48: [2]u16, // Word 49 unused_word_49_bits_0_8: u9, lba: bool, unused_word_49_bits_10_15: u6, // Words 50 - 59 unused_words_50_59: [10]u16, // Words 60 - 61 lba28_sector_count: u32, // Words 62 - 85 unused_words_62_85: [24]u16, // Word 86 unused_word_86_bits_0_9: u10, lba48: bool, unused_word_86_bits_11_15: u5, // Words 87 - 99 unused_words_87_99: [13]u16, // Words 100 - 103 lba48_sector_count: u64, // Words 104 - 255 unused_words_104_255: [152]u16, }; comptime { const raw_bit_size = utils.packed_bit_size(Raw); const sector_bit_size = Sector.size * 8; if (raw_bit_size != sector_bit_size) { @compileLog("IndentifyResults.Raw is ", raw_bit_size, " bits"); @compileLog("Sector is ", sector_bit_size, " bits"); @compileError("IndentifyResults.Raw must match the size of a sector"); } } const AddressType = enum(u8) { Lba28, Lba48, fn to_string(self: AddressType) []const u8 { return switch (self) { .Lba28 => "LBA 28", .Lba48 => "LBA 48", }; } }; model: []u8, sector_count: u64, address_type: AddressType, fn from_sector(sector: *Sector) Error!IndentifyResults { var results: IndentifyResults = undefined; const raw = @ptrCast(*Raw, &sector.data[0]); results.model.ptr = @ptrCast([*]u8, &raw.model[0]); results.model.len = raw.model.len * 2; for (raw.model) |*i| { i.* = @byteSwap(u16, i.*); } results.model.len = utils.stripped_string_size(results.model); // TODO: Other Strings if (raw.lba) { if (raw.lba48) { results.address_type = .Lba48; results.sector_count = raw.lba48_sector_count; } else { results.address_type = .Lba28; results.sector_count = raw.lba28_sector_count; } } else { print.string("Error: Drive does not support LBA\n"); return Error.UnexpectedValues; } return results; } }; const Controller = struct { const default_primary_io_base_port: u16 = 0x01F0; const default_primary_control_base_port: u16 = 0x03F4; const default_primary_irq: u8 = 14; const default_secondary_io_base_port: u16 = 0x0170; const default_secondary_control_base_port: u16 = 0x0374; const default_secondary_irq: u8 = 16; const Device = struct { const Id = enum(u1) { Master, Slave, }; id: Id, present: bool = false, selected: bool = false, alloc: *memory.Allocator = undefined, block_store_if: io.BlockStore = undefined, sector_count: u64 = 0, desc: []const u8 = undefined, device_if: devices.Device = undefined, fn get_channel(self: *Device) *Channel { return if (self.id == .Master) @fieldParentPtr(Channel, "master", self) else @fieldParentPtr(Channel, "slave", self); } fn select(self: *Device) Error!void { if (self.selected) return; const channel = self.get_channel(); try channel.read_command_status().assert_selectable(); channel.write_select(self.id); timing.wait_microseconds(1); _ = channel.read_command_status(); try channel.read_command_status().assert_selectable(); self.selected = true; channel.selected(self.id); } const wait_timeout_ms = 100; // TODO: Merge these wait functions? fn wait_while_busy(self: *Device) Error!void { const channel = self.get_channel(); var milliseconds_left: u64 = wait_timeout_ms; while (channel.read_command_status().busy) { milliseconds_left -= 1; if (milliseconds_left == 0) { print.string("wait_while_busy Timeout\n"); return Error.Timeout; } timing.wait_milliseconds(1); } } fn wait_for_drive(self: *Device) Error!void { const channel = self.get_channel(); var milliseconds_left: u64 = wait_timeout_ms; _ = channel.read_control_status(); while (!try channel.read_control_status().drive_is_ready()) { milliseconds_left -= 1; if (milliseconds_left == 0) { print.format("wait_for_drive Timeout {}\n", .{ channel.read_control_status()}); return Error.Timeout; } timing.wait_milliseconds(1); } } fn wait_for_data(self: *Device) Error!void { const channel = self.get_channel(); var milliseconds_left: u64 = wait_timeout_ms; _ = channel.read_control_status(); while (!try channel.read_control_status().data_is_ready()) { milliseconds_left -= 1; if (milliseconds_left == 0) { print.string("wait_for_data Timeout\n"); return Error.Timeout; } timing.wait_milliseconds(1); } } fn reset(self: *Device) Error!void { try self.select(); const channel = self.get_channel(); // Enable Reset channel.write_control(Control{.interrupts_disabled = true, .reset = true}); // Wait 5+ us timing.wait_microseconds(5); // Disable Reset channel.write_control(Control{.interrupts_disabled = true, .reset = false}); // Wait 2+ ms timing.wait_milliseconds(2); // Wait for controller to stop being busy try self.wait_while_busy(); // Wait 5+ ms timing.wait_milliseconds(5); _ = channel.read_error(); // Read Expected Values try channel.check_sector_registers(); print.format(log_indent ++ " - type: {:x}\n", .{channel.read_cylinder()}); } fn dev_deinit_impl(device: *devices.Device) void { _ = device; const self = @fieldParentPtr(Device, "device_if", device); const std_alloc = self.alloc.std_allocator(); std_alloc.free(self.desc); // TODO: Make sure disk is done writing? Make sure nothing is using // the disk? } fn dev_desc_impl(device: *devices.Device) []const u8 { const self = @fieldParentPtr(Device, "device_if", device); return self.desc; } fn as_block_store_impl(device: *devices.Device) *io.BlockStore { const self = @fieldParentPtr(Device, "device_if", device); return &self.block_store_if; } fn init(self: *Device, controller_dev: *devices.Device, temp_sector: *Sector, alloc: *memory.Allocator) Error!void { print.format(log_indent ++ " - {}\n", .{self.id}); const channel = self.get_channel(); self.alloc = alloc; try self.reset(); try self.wait_for_drive(); channel.identify_command(); _ = channel.read_command_status(); try self.wait_for_data(); channel.read_sector(temp_sector); const identity = try IndentifyResults.from_sector(temp_sector); const total_size = std.fmt.fmtIntSizeBin(identity.sector_count * Sector.size); try console_writer.print( log_indent ++ " - Drive Model: \"{s}\"\n" ++ log_indent ++ " - Address Type: {s}\n" ++ log_indent ++ " - Sector Count: {}\n" ++ log_indent ++ " - Total Size: {}\n", .{ identity.model, identity.address_type.to_string(), identity.sector_count, total_size, } ); self.present = true; self.sector_count = identity.sector_count; self.block_store_if = .{ .page_alloc = kernel.big_alloc.std_allocator(), .block_size = Sector.size, .max_address = identity.sector_count, .read_block_impl = Device.read_block, .write_block_impl = Device.write_block, }; self.device_if = .{ .class = .Disk, .deinit_impl = dev_deinit_impl, .desc_impl = dev_desc_impl, .as_block_store_impl = as_block_store_impl }; var sw = utils.StringWriter.init(alloc.std_allocator()); try sw.writer().print("{} ATA Disk \"{s}\"", .{total_size, identity.model}); self.desc = sw.get(); try controller_dev.add_child_device(&self.device_if, "disk"); } fn read_write_common(self: *Device, address: u64) Error!*Channel { if (address >= self.sector_count) { print.format("ATA: read address {} is too large for {} sector device\n", .{address, self.sector_count}); return Error.OperationError; } try self.select(); const channel = self.get_channel(); try self.wait_for_drive(); channel.write_lba48(self.id, address, 1); timing.wait_microseconds(5); return channel; } fn read_impl(self: *Device, address: u64, data: []u8) Error!void { const channel = try self.read_write_common(address); channel.read_sectors_command(); _ = channel.read_command_status(); const error_reg = channel.read_error(); const status_reg = channel.read_command_status(); if (((error_reg & 0x80) != 0) or status_reg.in_error or status_reg.fault) { print.string("ATA Read Error\n"); return Error.OperationError; } try self.wait_for_data(); channel.read_sector_impl(data); } fn read_sector(self: *Device, sector: *Sector) Error!void { try self.read_impl(sector.address, sector.data[0..]); } fn read_block(block_store: *io.BlockStore, block: *io.Block) io.FileError!void { const self = @fieldParentPtr(Device, "block_store_if", block_store); if (block.data == null) return io.FileError.NotEnoughDestination; self.read_impl(block.address, block.data.?[0..]) catch return io.FileError.Internal; } fn write_impl(self: *Device, address: u64, data: []const u8) Error!void { const channel = self.read_write_common(address) catch |e| { print.format("read_write_common failed: {}\n", .{@errorName(e)}); return e; }; channel.write_sectors_command(); _ = channel.read_command_status(); const error_reg = channel.read_error(); const status_reg = channel.read_command_status(); if (((error_reg & 0x80) != 0) or status_reg.in_error or status_reg.fault) { print.string("ATA Write Error\n"); return Error.OperationError; } self.wait_for_data() catch |e| { print.format("wait_for_data failed: {}\n", .{@errorName(e)}); return e; }; channel.write_sector_impl(data); channel.flush_command(); // TODO: Lunt says this isn't needed everytime self.wait_while_busy() catch |e| { print.format("wait_while_busy failed: {}\n", .{@errorName(e)}); return e; }; } fn write_block(block_store: *io.BlockStore, block: *io.Block) io.FileError!void { const self = @fieldParentPtr(Device, "block_store_if", block_store); if (block.data == null) return io.FileError.NotEnoughSource; self.write_impl(block.address, block.data.?[0..]) catch return io.FileError.Internal; } }; const Channel = struct { const Id = enum(u1) { Primary, Secondary, }; id: Id, io_base_port: u16, pio_data_port: u16 = 0, error_port: u16 = 1, sector_count_port: u16 = 2, lba_low_port: u16 = 3, // AKA sector number lba_mid_port: u16 = 4, // AKA cylinder low lba_high_port: u16 = 5, // AKA cylinder high drive_head_port: u16 = 6, command_port: u16 = 7, control_base_port: u16, irq: u8, master: Device = Device{.id = .Master}, slave: Device = Device{.id = .Slave}, fn init(self: *Channel, controller_dev: *devices.Device, temp_sector: *Sector, alloc: *Allocator) void { self.pio_data_port += self.io_base_port; self.error_port += self.io_base_port; self.sector_count_port += self.io_base_port; self.lba_low_port += self.io_base_port; self.lba_mid_port += self.io_base_port; self.lba_high_port += self.io_base_port; self.drive_head_port += self.io_base_port; self.command_port += self.io_base_port; print.format(log_indent ++ "- {}\n", .{self.id}); self.master.init(controller_dev, temp_sector, alloc) catch { print.string(log_indent ++ " - Master Failed\n"); }; self.slave.init(controller_dev, temp_sector, alloc) catch { print.string(log_indent ++ " - Slave Failed\n"); }; } fn selected(self: *Channel, id: Device.Id) void { if (id == Device.Id.Master) { self.slave.selected = false; } else { self.master.selected = false; } } fn read_command_status(self: *Channel) CommandStatus { return @bitCast(CommandStatus, putil.in8(self.command_port)); } fn read_control_status(self: *Channel) CommandStatus { return @bitCast(CommandStatus, putil.in8(self.control_base_port + 2)); } fn read_error(self: *Channel) u8 { // TODO: Create Struct? return putil.in8(self.error_port); } fn check_sector_registers(self: *Channel) Error!void { const sector_count = putil.in8(self.sector_count_port); const sector_number = putil.in8(self.lba_low_port); if (sector_count != 1 and sector_number != 1) { print.format(log_indent ++ " - reset: expected 1, 1 for sector count " ++ "and number, but got {}, {}\n", .{sector_count, sector_number}); return Error.UnexpectedValues; } } fn read_cylinder(self: *Channel) u16 { const low = @intCast(u16, putil.in8(self.lba_mid_port)); const high = @intCast(u16, putil.in8(self.lba_high_port)); return (high << 8) | low; } fn write_drive_head_select(self: *Channel, value: DriveHeadSelect) void { putil.out8(self.drive_head_port, @bitCast(u8, value)); } fn write_select(self: *Channel, value: Device.Id) void { self.write_drive_head_select( DriveHeadSelect{.select_slave = value == Device.Id.Slave}); } fn out8(port: u16, value: anytype) void { putil.out8(port, @truncate(u8, value)); } fn write_lba48(self: *Channel, device: Device.Id, lba: u64, sector_count: u16) void { out8(self.sector_count_port, sector_count >> 8); out8(self.lba_low_port, lba >> 24); out8(self.lba_mid_port, lba >> 32); out8(self.lba_high_port, lba >> 40); out8(self.sector_count_port, sector_count); out8(self.lba_low_port, lba); out8(self.lba_mid_port, lba >> 8); out8(self.lba_high_port, lba >> 16); self.write_drive_head_select(DriveHeadSelect{ .lba = true, .select_slave = device == Device.Id.Slave, }); } fn read_sectors_command(self: *const Channel) void { putil.out8(self.command_port, 0x24); } fn write_sectors_command(self: *const Channel) void { putil.out8(self.command_port, 0x34); } fn flush_command(self: *const Channel) void { putil.out8(self.command_port, 0xe7); } fn identify_command(self: *const Channel) void { putil.out8(self.io_base_port + 7, 0xEC); } fn write_control(self: *Channel, value: Control) void { putil.out8(self.control_base_port + 2, @bitCast(u8, value)); } fn read_sector(self: *Channel, sector: *Sector) void { self.read_sector_impl(sector.data[0..]); } fn read_sector_impl(self: *Channel, data: []u8) void { putil.in_bytes(self.pio_data_port, data); } fn write_sector_impl(self: *Channel, data: []const u8) void { for (std.mem.bytesAsSlice(u16, data)) |word| { putil.out16(self.pio_data_port, word); } } }; primary: Channel = Channel{ .id = Channel.Id.Primary, .io_base_port = default_primary_io_base_port, .control_base_port = default_primary_control_base_port, .irq = default_primary_irq, }, secondary: Channel = Channel{ .id = Channel.Id.Secondary, .io_base_port = default_secondary_io_base_port, .control_base_port = default_secondary_control_base_port, .irq = default_secondary_irq, }, device_if: devices.Device = undefined, alloc: *Allocator = undefined, fn init(self: *Controller, alloc: *Allocator) void { self.alloc = alloc; self.device_if = .{ .class = .Bus, .deinit_impl = deinit_impl, }; // Make sure this is Triton II controller emulated by QEMU // if (header.vendor_id != 0x8086 or header.device_id != 0x7010 or // header.prog_if != 0x80) { // print.string(log_indent ++ "- Unknown IDE Controller\n"); // return; // } } fn init_disks(self: *Controller) void { const temp_sector = self.alloc.alloc(Sector) catch { print.string("ERROR: Failed to allocate sector for ATA initialization\n"); return; }; defer self.alloc.free(temp_sector) catch unreachable; self.primary.init(&self.device_if, temp_sector, self.alloc); self.secondary.init(&self.device_if, temp_sector, self.alloc); } fn deinit_impl(device: *devices.Device) void { const self = @fieldParentPtr(Controller, "device_if", device); // TODO: Make sure disks can be safely stop being used. self.alloc.free(self) catch unreachable; } }; pub fn init(dev: *const pci.Dev) void { _ = dev; var controller = kernel.alloc.alloc(Controller) catch { @panic("Failure"); }; controller.* = .{}; controller.init(kernel.alloc); kernel.device_mgr.root_device.add_child_device(&controller.device_if, "ata") catch { @panic("Failure"); }; controller.init_disks(); }
0
repos/georgios/kernel
repos/georgios/kernel/platform/ps2_scan_codes.zig
// Generated by scripts/codegen/scan_codes.py const georgios = @import("georgios"); const kb = georgios.keyboard; pub const Entry = struct { key: ?kb.Key, shifted_key: ?kb.Key, kind: ?kb.Kind, }; pub const one_byte = [256]Entry { Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = .Key_Escape, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_1, .shifted_key = .Key_Exclamation, .kind = .Pressed}, Entry{.key = .Key_2, .shifted_key = .Key_At, .kind = .Pressed}, Entry{.key = .Key_3, .shifted_key = .Key_Pound, .kind = .Pressed}, Entry{.key = .Key_4, .shifted_key = .Key_Dollar, .kind = .Pressed}, Entry{.key = .Key_5, .shifted_key = .Key_Percent, .kind = .Pressed}, Entry{.key = .Key_6, .shifted_key = .Key_Caret, .kind = .Pressed}, Entry{.key = .Key_7, .shifted_key = .Key_Ampersand, .kind = .Pressed}, Entry{.key = .Key_8, .shifted_key = .Key_Asterisk, .kind = .Pressed}, Entry{.key = .Key_9, .shifted_key = .Key_LeftParentheses, .kind = .Pressed}, Entry{.key = .Key_0, .shifted_key = .Key_RightParentheses, .kind = .Pressed}, Entry{.key = .Key_Minus, .shifted_key = .Key_Underscore, .kind = .Pressed}, Entry{.key = .Key_Equals, .shifted_key = .Key_Plus, .kind = .Pressed}, Entry{.key = .Key_Backspace, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_Tab, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_q, .shifted_key = .Key_Q, .kind = .Pressed}, Entry{.key = .Key_w, .shifted_key = .Key_W, .kind = .Pressed}, Entry{.key = .Key_e, .shifted_key = .Key_E, .kind = .Pressed}, Entry{.key = .Key_r, .shifted_key = .Key_R, .kind = .Pressed}, Entry{.key = .Key_t, .shifted_key = .Key_T, .kind = .Pressed}, Entry{.key = .Key_y, .shifted_key = .Key_Y, .kind = .Pressed}, Entry{.key = .Key_u, .shifted_key = .Key_U, .kind = .Pressed}, Entry{.key = .Key_i, .shifted_key = .Key_I, .kind = .Pressed}, Entry{.key = .Key_o, .shifted_key = .Key_O, .kind = .Pressed}, Entry{.key = .Key_p, .shifted_key = .Key_P, .kind = .Pressed}, Entry{.key = .Key_LeftSquareBracket, .shifted_key = .Key_LeftBrace, .kind = .Pressed}, Entry{.key = .Key_RightSquareBracket, .shifted_key = .Key_RightBrace, .kind = .Pressed}, Entry{.key = .Key_Enter, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_LeftControl, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_a, .shifted_key = .Key_A, .kind = .Pressed}, Entry{.key = .Key_s, .shifted_key = .Key_S, .kind = .Pressed}, Entry{.key = .Key_d, .shifted_key = .Key_D, .kind = .Pressed}, Entry{.key = .Key_f, .shifted_key = .Key_F, .kind = .Pressed}, Entry{.key = .Key_g, .shifted_key = .Key_G, .kind = .Pressed}, Entry{.key = .Key_h, .shifted_key = .Key_H, .kind = .Pressed}, Entry{.key = .Key_j, .shifted_key = .Key_J, .kind = .Pressed}, Entry{.key = .Key_k, .shifted_key = .Key_K, .kind = .Pressed}, Entry{.key = .Key_l, .shifted_key = .Key_L, .kind = .Pressed}, Entry{.key = .Key_SemiColon, .shifted_key = .Key_Colon, .kind = .Pressed}, Entry{.key = .Key_SingleQuote, .shifted_key = .Key_DoubleQuote, .kind = .Pressed}, Entry{.key = .Key_BackTick, .shifted_key = .Key_Tilde, .kind = .Pressed}, Entry{.key = .Key_LeftShift, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_Backslash, .shifted_key = .Key_Pipe, .kind = .Pressed}, Entry{.key = .Key_z, .shifted_key = .Key_Z, .kind = .Pressed}, Entry{.key = .Key_x, .shifted_key = .Key_X, .kind = .Pressed}, Entry{.key = .Key_c, .shifted_key = .Key_C, .kind = .Pressed}, Entry{.key = .Key_v, .shifted_key = .Key_V, .kind = .Pressed}, Entry{.key = .Key_b, .shifted_key = .Key_B, .kind = .Pressed}, Entry{.key = .Key_n, .shifted_key = .Key_N, .kind = .Pressed}, Entry{.key = .Key_m, .shifted_key = .Key_M, .kind = .Pressed}, Entry{.key = .Key_Comma, .shifted_key = .Key_LessThan, .kind = .Pressed}, Entry{.key = .Key_Period, .shifted_key = .Key_GreaterThan, .kind = .Pressed}, Entry{.key = .Key_Slash, .shifted_key = .Key_Question, .kind = .Pressed}, Entry{.key = .Key_RightShift, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_KeypadAsterisk, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_LeftAlt, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_Space, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_CapsLock, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_F1, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_F2, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_F3, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_F4, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_F5, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_F6, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_F7, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_F8, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_F9, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_F10, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_NumberLock, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_ScrollLock, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_Keypad7, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_Keypad8, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_Keypad9, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_KeypadMinus, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_Keypad4, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_Keypad5, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_Keypad6, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_KeypadPlus, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_Keypad1, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_Keypad2, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_Keypad3, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_Keypad0, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_KeypadPeriod, .shifted_key = null, .kind = .Pressed}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = .Key_F11, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_F12, .shifted_key = null, .kind = .Pressed}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = .Key_Escape, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_1, .shifted_key = .Key_Exclamation, .kind = .Released}, Entry{.key = .Key_2, .shifted_key = .Key_At, .kind = .Released}, Entry{.key = .Key_3, .shifted_key = .Key_Pound, .kind = .Released}, Entry{.key = .Key_4, .shifted_key = .Key_Dollar, .kind = .Released}, Entry{.key = .Key_5, .shifted_key = .Key_Percent, .kind = .Released}, Entry{.key = .Key_6, .shifted_key = .Key_Caret, .kind = .Released}, Entry{.key = .Key_7, .shifted_key = .Key_Ampersand, .kind = .Released}, Entry{.key = .Key_8, .shifted_key = .Key_Asterisk, .kind = .Released}, Entry{.key = .Key_9, .shifted_key = .Key_LeftParentheses, .kind = .Released}, Entry{.key = .Key_0, .shifted_key = .Key_RightParentheses, .kind = .Released}, Entry{.key = .Key_Minus, .shifted_key = .Key_Underscore, .kind = .Released}, Entry{.key = .Key_Equals, .shifted_key = .Key_Plus, .kind = .Released}, Entry{.key = .Key_Backspace, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_Tab, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_q, .shifted_key = .Key_Q, .kind = .Released}, Entry{.key = .Key_w, .shifted_key = .Key_W, .kind = .Released}, Entry{.key = .Key_e, .shifted_key = .Key_E, .kind = .Released}, Entry{.key = .Key_r, .shifted_key = .Key_R, .kind = .Released}, Entry{.key = .Key_t, .shifted_key = .Key_T, .kind = .Released}, Entry{.key = .Key_y, .shifted_key = .Key_Y, .kind = .Released}, Entry{.key = .Key_u, .shifted_key = .Key_U, .kind = .Released}, Entry{.key = .Key_i, .shifted_key = .Key_I, .kind = .Released}, Entry{.key = .Key_o, .shifted_key = .Key_O, .kind = .Released}, Entry{.key = .Key_p, .shifted_key = .Key_P, .kind = .Released}, Entry{.key = .Key_LeftSquareBracket, .shifted_key = .Key_LeftBrace, .kind = .Released}, Entry{.key = .Key_RightSquareBracket, .shifted_key = .Key_RightBrace, .kind = .Released}, Entry{.key = .Key_Enter, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_LeftControl, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_a, .shifted_key = .Key_A, .kind = .Released}, Entry{.key = .Key_s, .shifted_key = .Key_S, .kind = .Released}, Entry{.key = .Key_d, .shifted_key = .Key_D, .kind = .Released}, Entry{.key = .Key_f, .shifted_key = .Key_F, .kind = .Released}, Entry{.key = .Key_g, .shifted_key = .Key_G, .kind = .Released}, Entry{.key = .Key_h, .shifted_key = .Key_H, .kind = .Released}, Entry{.key = .Key_j, .shifted_key = .Key_J, .kind = .Released}, Entry{.key = .Key_k, .shifted_key = .Key_K, .kind = .Released}, Entry{.key = .Key_l, .shifted_key = .Key_L, .kind = .Released}, Entry{.key = .Key_SemiColon, .shifted_key = .Key_Colon, .kind = .Released}, Entry{.key = .Key_SingleQuote, .shifted_key = .Key_DoubleQuote, .kind = .Released}, Entry{.key = .Key_BackTick, .shifted_key = .Key_Tilde, .kind = .Released}, Entry{.key = .Key_LeftShift, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_Backslash, .shifted_key = .Key_Pipe, .kind = .Released}, Entry{.key = .Key_z, .shifted_key = .Key_Z, .kind = .Released}, Entry{.key = .Key_x, .shifted_key = .Key_X, .kind = .Released}, Entry{.key = .Key_c, .shifted_key = .Key_C, .kind = .Released}, Entry{.key = .Key_v, .shifted_key = .Key_V, .kind = .Released}, Entry{.key = .Key_b, .shifted_key = .Key_B, .kind = .Released}, Entry{.key = .Key_n, .shifted_key = .Key_N, .kind = .Released}, Entry{.key = .Key_m, .shifted_key = .Key_M, .kind = .Released}, Entry{.key = .Key_Comma, .shifted_key = .Key_LessThan, .kind = .Released}, Entry{.key = .Key_Period, .shifted_key = .Key_GreaterThan, .kind = .Released}, Entry{.key = .Key_Slash, .shifted_key = .Key_Question, .kind = .Released}, Entry{.key = .Key_RightShift, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_KeypadAsterisk, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_LeftAlt, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_Space, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_CapsLock, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_F1, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_F2, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_F3, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_F4, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_F5, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_F6, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_F7, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_F8, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_F9, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_F10, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_NumberLock, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_ScrollLock, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_Keypad7, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_Keypad8, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_Keypad9, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_KeypadMinus, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_Keypad4, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_Keypad5, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_Keypad6, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_KeypadPlus, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_Keypad1, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_Keypad2, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_Keypad3, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_Keypad0, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_KeypadPeriod, .shifted_key = null, .kind = .Released}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = .Key_F11, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_F12, .shifted_key = null, .kind = .Released}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, }; pub const two_byte = [256]Entry { Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = .Key_KeypadEnter, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_RightControl, .shifted_key = null, .kind = .Pressed}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = .Key_KeypadSlash, .shifted_key = null, .kind = .Pressed}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = .Key_RightAlt, .shifted_key = null, .kind = .Pressed}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = .Key_Home, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_CursorUp, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_PageUp, .shifted_key = null, .kind = .Pressed}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = .Key_CursorLeft, .shifted_key = null, .kind = .Pressed}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = .Key_CursorRight, .shifted_key = null, .kind = .Pressed}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = .Key_End, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_CursorDown, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_PageDown, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_Insert, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_Delete, .shifted_key = null, .kind = .Pressed}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = .Key_AcpiPower, .shifted_key = null, .kind = .Pressed}, Entry{.key = .Key_AcpiSleep, .shifted_key = null, .kind = .Pressed}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = .Key_AcpiWake, .shifted_key = null, .kind = .Pressed}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = .Key_KeypadEnter, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_RightControl, .shifted_key = null, .kind = .Released}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = .Key_KeypadSlash, .shifted_key = null, .kind = .Released}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = .Key_RightAlt, .shifted_key = null, .kind = .Released}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = .Key_Home, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_CursorUp, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_PageUp, .shifted_key = null, .kind = .Released}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = .Key_CursorLeft, .shifted_key = null, .kind = .Released}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = .Key_CursorRight, .shifted_key = null, .kind = .Released}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = .Key_End, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_CursorDown, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_PageDown, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_Insert, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_Delete, .shifted_key = null, .kind = .Released}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = .Key_AcpiPower, .shifted_key = null, .kind = .Released}, Entry{.key = .Key_AcpiSleep, .shifted_key = null, .kind = .Released}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = .Key_AcpiWake, .shifted_key = null, .kind = .Released}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, Entry{.key = null, .shifted_key = null, .kind = null}, };
0
repos/georgios/kernel
repos/georgios/kernel/platform/system_calls.zig
// System Call Handling const utils = @import("utils"); const georgios = @import("georgios"); const ValueOrErrorT = georgios.system_calls.ValueOrError; const kernel = @import("root").kernel; const print = kernel.print; const kthreading = kernel.threading; const ps2 = @import("ps2.zig"); const interrupts = @import("interrupts.zig"); const vbe = @import("vbe.zig"); const vbe_console = @import("vbe_console.zig"); pub const interrupt_number: u8 = 100; pub fn handle(_: u32, interrupt_stack: *const interrupts.Stack) void { const call_number = interrupt_stack.eax; const arg1 = interrupt_stack.ebx; const arg2 = interrupt_stack.ecx; const arg3 = interrupt_stack.edx; const arg4 = interrupt_stack.edi; const arg5 = interrupt_stack.esi; _ = arg5; // TODO: Using pointers for args can cause Zig's alignment checks to fail. // Find a way around this without turning off safety? @setRuntimeSafety(false); switch (call_number) { // This file is parsed by generate_system_calls.py to generate the // system call interface functions used by programs. Before a system // call implementation there should be a SYSCALL comment with something // like the intended Zig signature in it. This pseudo-signature is the // same as normal, but with 2 differences: // // - One is a & before names of arguments intended to be passed to the // system call implementation as pointers. This is necessary for things // larger than a register. // Example: \\ SYSCALL: cool_syscall(&cool_arg: []const u8) void // // - The other is an optional name after the arguments that sets the name // of the return value in the generated function. // Example: \\ SYSCALL: cool_syscall() cool_return: u32` // // What registers the arguments and return values use depend on the // argN constants above and the order they appear in the signature. // Example: \\ SYSCALL: cool_syscall(a: u32, b: u32) c: u32 // a should be read from arg1, b should be read from arg2, and the // return value should be written to arg3. // // System calls that return Zig errors should use ValueOrError and must // set something. This type exists because Zig errors can only safely // be used within the same compilation. To get around that this type // translates the kernel Zig errors to ABI-stable values to pass across // the system call boundary. In user space, the same type tries to // translate the values back to Zig errors. If the kernel error type is // unknown to the user program it gets the utils.Error.Unknown error. // // The following must come after a SYSCALL comment and before the // system call implementation: // // - An IMPORT comment will combine with other system call imports and // import Zig namespace needed for the system calls arguments and // return. // Example: \\ IMPORT: cool "cool" // Will insert: const cool = @import("cool") // // TODO: Documentation Comments // TODO: C alternative interface syscalls? // SYSCALL: send(&dispatch: georgios.Dispatch, &opts: georgios.SendOpts) georgios.DispatchError!void 100 => { const E = georgios.DispatchError; const ValueOrError = ValueOrErrorT(void, E); const dispatch = @intToPtr(*georgios.Dispatch, arg1); const opts = @intToPtr(*georgios.SendOpts, arg2); const rv = @intToPtr(*ValueOrError, arg3); if (kernel.threading_mgr.current_process) |p| { rv.set_value(p.dispatcher.send(dispatch.*, opts.*) catch |e| { rv.set_error(e); return; }); } else { rv.set_error(E.Unknown); } }, // SYSCALL: recv(dst: georgios.PortId, &opts: georgios.RecvOpts) georgios.DispatchError!?georgios.Dispatch 101 => { const E = georgios.DispatchError; const ValueOrError = ValueOrErrorT(?georgios.Dispatch, E); const dst = arg1; const opts = @intToPtr(*georgios.RecvOpts, arg2); const rv = @intToPtr(*ValueOrError, arg3); if (kernel.threading_mgr.current_process) |p| { rv.set_value(p.dispatcher.recv(dst, opts.*) catch |e| { rv.set_error(e); return; }); } else { rv.set_error(E.Unknown); } }, // SYSCALL: call(&dispatch: georgios.Dispatch, &opts: georgios.CallOpts) georgios.DispatchError!georgios.Dispatch 102 => { const E = georgios.DispatchError; const ValueOrError = ValueOrErrorT(georgios.Dispatch, E); const dispatch = @intToPtr(*georgios.Dispatch, arg1); const opts = @intToPtr(*georgios.CallOpts, arg2); const rv = @intToPtr(*ValueOrError, arg3); if (kernel.threading_mgr.current_process) |p| { rv.set_value(p.dispatcher.call(dispatch.*, opts.*) catch |e| { rv.set_error(e); return; }); } else { rv.set_error(E.Unknown); } }, // SYSCALL: print_string(&s: []const u8) void 0 => print.string(@intToPtr(*[]const u8, arg1).*), // SYSCALL: add_dynamic_memory(inc: usize) georgios.BasicError![]u8 1 => { const ValueOrError = ValueOrErrorT([]u8, georgios.BasicError); const inc = arg1; const rv = @intToPtr(*ValueOrError, arg2); if (kernel.threading_mgr.current_process) |p| { rv.set_value(p.add_dynamic_memory(inc) catch |e| { rv.set_error(e); return; }); } }, // SYSCALL: yield() void 2 => { if (kthreading.debug) print.string("\nY"); kernel.threading_mgr.yield(); }, // SYSCALL: exit(&info: georgios.ExitInfo) noreturn // IMPORT: georgios "georgios.zig" 3 => { const info = @intToPtr(*georgios.ExitInfo, arg1); if (kthreading.debug) print.string("\nE"); kernel.threading_mgr.exit_current_process(info.*); }, // SYSCALL: exec(info: *const georgios.ProcessInfo) georgios.ExecError!georgios.ExitInfo // IMPORT: georgios "georgios.zig" 4 => { const ValueOrError = ValueOrErrorT(georgios.ExitInfo, georgios.ExecError); // Should not be able to create kernel mode process from a system // call that can be called from user mode. var info = @intToPtr(*const georgios.ProcessInfo, arg1).*; info.kernel_mode = false; const rv = @intToPtr(*ValueOrError, arg2); if (kernel.exec(&info)) |pid| { const exit_info = kernel.threading_mgr.wait_for_process(pid) catch @panic("wait_for_process failed"); rv.set_value(exit_info); } else |e| { rv.set_error(e); } }, // SYSCALL: get_key(&blocking: georgios.Blocking) key: ?georgios.keyboard.Event // IMPORT: georgios "georgios.zig" 5 => { const blocking = @intToPtr(*georgios.Blocking, arg1).* == .Blocking; const rv = @intToPtr(*?georgios.keyboard.Event, arg2); while (true) { if (ps2.get_key()) |key| { rv.* = key; break; } else if (blocking) { kernel.threading_mgr.wait_for_keyboard(); } else { rv.* = null; break; } } }, // SYSCALL: get_mouse_event(&blocking: georgios.Blocking) key: ?georgios.MouseEvent // IMPORT: georgios "georgios.zig" 28 => { const blocking = @intToPtr(*georgios.Blocking, arg1).* == .Blocking; const rv = @intToPtr(*?georgios.MouseEvent, arg2); while (true) { if (ps2.get_mouse_event()) |event| { rv.* = event; break; } else if (blocking) { kernel.threading_mgr.wait_for_mouse(); } else { rv.* = null; break; } } }, // SYSCALL: print_uint(value: u32, base: u8) void 7 => { switch (arg2) { 16 => print.hex(arg1), else => print.uint(arg1), } }, // SYSCALL: file_open(&path: []const u8, &opts: georgios.fs.OpenOpts) georgios.fs.Error!georgios.io.File.Id 8 => { const ValueOrError = ValueOrErrorT(georgios.io.File.Id, georgios.fs.Error); const path = @intToPtr(*[]const u8, arg1); const opts = @intToPtr(*georgios.fs.OpenOpts, arg2); const rv = @intToPtr(*ValueOrError, arg3); if (kernel.threading_mgr.current_process) |p| { rv.set_value(p.fs_submgr.open(path.*, opts.*) catch |e| { rv.set_error(e); return; }); } }, // SYSCALL: file_read(id: georgios.io.File.Id, &to: []u8) georgios.io.FileError!usize 9 => { const ValueOrError = ValueOrErrorT(usize, georgios.io.FileError); const id = arg1; const to = @intToPtr(*[]u8, arg2); const rv = @intToPtr(*ValueOrError, arg3); if (kernel.threading_mgr.current_process) |p| { rv.set_value(p.fs_submgr.read(id, to.*) catch |e| { rv.set_error(e); return; }); } }, // SYSCALL: file_write(id: georgios.io.File.Id, &from: []const u8) georgios.io.FileError!usize 10 => { const ValueOrError = ValueOrErrorT(usize, georgios.io.FileError); const id = arg1; const from = @intToPtr(*[]const u8, arg2); const rv = @intToPtr(*ValueOrError, arg3); if (kernel.threading_mgr.current_process) |p| { rv.set_value(p.fs_submgr.write(id, from.*) catch |e| { rv.set_error(e); return; }); } }, // SYSCALL: file_seek(id: georgios.io.File.Id, offset: isize, seek_type: georgios.io.File.SeekType) georgios.io.FileError!usize 11 => { const ValueOrError = ValueOrErrorT(usize, georgios.io.FileError); const id = arg1; const offset = @bitCast(isize, arg2); // TODO Check arg3 is valid? const seek_type = utils.int_to_enum(georgios.io.File.SeekType, @intCast(u2, arg3)).?; const rv = @intToPtr(*ValueOrError, arg4); if (kernel.threading_mgr.current_process) |p| { rv.set_value(p.fs_submgr.seek(id, offset, seek_type) catch |e| { rv.set_error(e); return; }); } }, // SYSCALL: file_close(id: georgios.io.File.Id) georgios.fs.Error!void 12 => { const ValueOrError = ValueOrErrorT(void, georgios.fs.Error); const id = arg1; const rv = @intToPtr(*ValueOrError, arg2); if (kernel.threading_mgr.current_process) |p| { rv.set_value(p.fs_submgr.close(id) catch |e| { rv.set_error(e); return; }); } }, // SYSCALL: get_cwd(&buffer: []u8) georgios.threading.Error![]const u8 13 => { const ValueOrError = ValueOrErrorT([]const u8, georgios.threading.Error); const buffer = @intToPtr(*[]u8, arg1).*; const rv = @intToPtr(*ValueOrError, arg2); if (kernel.threading_mgr.get_cwd(buffer)) |dir| { rv.set_value(dir); } else |e| { rv.set_error(e); } }, // SYSCALL: set_cwd(&dir: []const u8) georgios.ThreadingOrFsError!void 14 => { const ValueOrError = ValueOrErrorT(void, georgios.ThreadingOrFsError); const dir = @intToPtr(*[]const u8, arg1).*; const rv = @intToPtr(*ValueOrError, arg2); if (kernel.threading_mgr.set_cwd(dir)) { rv.set_value(.{}); } else |e| { rv.set_error(e); } }, // SYSCALL: sleep_milliseconds(&ms: u64) void 15 => { kernel.threading_mgr.sleep_milliseconds(@intToPtr(*u64, arg1).*); }, // SYSCALL: sleep_seconds(&s: u64) void 16 => { kernel.threading_mgr.sleep_seconds(@intToPtr(*u64, arg1).*); }, // SYSCALL: time() u64 17 => { @intToPtr(*u64, arg1).* = kernel.platform.time(); }, // SYSCALL: get_process_id() u32 18 => { const r = @intToPtr(*u32, arg1); if (kernel.threading_mgr.current_process) |p| { r.* = p.id; } else { r.* = 0; } }, // SYSCALL: get_thread_id() u32 19 => { const r = @intToPtr(*u32, arg1); if (kernel.threading_mgr.current_thread) |t| { r.* = t.id; } else { r.* = 0; } }, // SYSCALL: overflow_kernel_stack() void 20 => { overflow_kernel_stack(); }, // SYSCALL: console_width() u32 21 => { const r = @intToPtr(*u32, arg1); r.* = kernel.console.width; }, // SYSCALL: console_height() u32 22 => { const r = @intToPtr(*u32, arg1); r.* = kernel.console.height; }, // SYSCALL: vbe_res() ?utils.U32Point 23 => { const rv = @intToPtr(*?utils.U32Point, arg1); rv.* = vbe.get_res(); }, // SYSCALL: vbe_draw_raw_image_chunk(&data: []const u8, w: u32, &pos: utils.U32Point, last: *utils.U32Point) void 24 => { const data = @intToPtr(*[]const u8, arg1).*; const width = arg2; const pos = @intToPtr(*utils.U32Point, arg3); const last = @intToPtr(*utils.U32Point, arg4); vbe.draw_raw_image_chunk(data, width, pos, last); }, // SYSCALL: vbe_flush_buffer() void 25 => { vbe.flush_buffer(); }, // SYSCALL: get_vbe_console_info(last_scroll_count: *u32, size: *utils.U32Point, pos: *utils.U32Point, glyph_size: *utils.U32Point) void 26 => { const last_scroll_count = @intToPtr(*u32, arg1); const size = @intToPtr(*utils.U32Point, arg2); const pos = @intToPtr(*utils.U32Point, arg3); const glyph_size = @intToPtr(*utils.U32Point, arg4); vbe_console.get_info(last_scroll_count, size, pos, glyph_size); }, // SYSCALL: vbe_fill_rect(rect: *const utils.U32Rect, pixel: u32) void 27 => { const rect = @intToPtr(*utils.U32Rect, arg1); const color = @truncate(u32, arg2); vbe.fill_rect(rect, color); }, else => @panic("Invalid System Call"), } } fn overflow_kernel_stack() void { if (kernel.threading_mgr.current_thread) |thread| { print.format("kernelmode_stack: {:a} - {:a}", .{ thread.impl.kernelmode_stack.start, thread.impl.kernelmode_stack.end(), }); } overflow_kernel_stack_i(); } fn overflow_kernel_stack_i() void { var use_to_find_guard_page: [128]u8 = undefined; print.format("overflow_kernel_stack: esp: {:a}\n", .{ asm volatile ("mov %%esp, %[x]" : [x] "=r" (-> usize))}); for (use_to_find_guard_page) |*ptr, i| { ptr.* = @truncate(u8, i); } overflow_kernel_stack_i(); }
0
repos/georgios/kernel
repos/georgios/kernel/platform/bios_int.zig
// Invoke BIOS interrupts using an emulated CPU so we don't have to mess with // how our CPU is setup by going to real mode ourselves or using v8086 mode // and a monitor. // // Uses libx86emu https://github.com/wfeldt/libx86emu // This lives in a submodule in bios_int/libx86emu/, with C support code in // bios_int/. const utils = @import("utils"); const kernel = @import("root").kernel; const print = kernel.print; const memory = kernel.memory; const platform = @import("platform.zig"); const util = @import("util.zig"); const timing = @import("timing.zig"); const c = @cImport({ @cInclude("georgios_bios_int.h"); }); pub const Error = error { BiosIntCallFailed, }; pub const Params = struct { interrupt: u8, eax: u32, ebx: u32 = 0, ecx: u32 = 0, edx: u32 = 0, edi: u32 = 0, slow: bool = false, }; const debug_io_access = false; const debug_mem_access = false; const exec_trace = false; export fn georgios_bios_int_to_string( buffer: [*]u8, buffer_size: usize, got: *usize, kind: u8, value: *anyopaque) bool { var ts = utils.ToString{.buffer = buffer[0..buffer_size]}; switch (kind) { 's' => { ts.cstring(@ptrCast([*:0]const u8, value)) catch return true; }, 'x' => { var v: usize = undefined; utils.memory_copy_anyptr(utils.to_bytes(&v), value); ts.hex(v) catch return true; }, else => { print.format("georgios_bios_to_string: Unexpected kind {:c}\n", .{kind}); }, } got.* = ts.got; return false; } export fn georgios_bios_int_print_string(str: [*:0]const u8) void { var i: usize = 0; while (str[i] != 0) { print.char(str[i]); i += 1; } } export fn georgios_bios_int_print_value(value: u32) void { print.hex(value); } export fn georgios_bios_int_wait() void { timing.wait_microseconds(500); } export fn georgios_bios_int_malloc(size: usize) ?*anyopaque { const a = kernel.alloc.alloc_array(u8, size) catch return null; return @ptrCast(*anyopaque, a.ptr); } export fn georgios_bios_int_calloc(num: usize, size: usize) ?*anyopaque { const a = kernel.alloc.alloc_array(u8, size * num) catch return null; utils.memory_set(a, 0); return @ptrCast(*anyopaque, a.ptr); } export fn georgios_bios_int_free(ptr: ?*anyopaque) void { if (ptr) |p| { kernel.alloc.free_array(utils.empty_slice(u8, p)) catch {}; } } export fn georgios_bios_int_strcat(dest: [*c]u8, src: [*c]const u8) [*c]u8 { var dest_i: usize = 0; while (dest[dest_i] != 0) { dest_i += 1; } var src_i: usize = 0; while (src[src_i] != 0) { dest[dest_i] = src[src_i]; dest_i += 1; src_i += 1; } dest[dest_i] = 0; return dest; } // For Access to I/O Ports export fn georgios_bios_int_inb(port: u16) callconv(.C) u8 { if (debug_io_access) print.format("georgios_bios_int_inb {:x}\n", .{port}); return util.in8(port); } export fn georgios_bios_int_inw(port: u16) callconv(.C) u16 { if (debug_io_access) print.format("georgios_bios_int_inw {:x}\n", .{port}); return util.in16(port); } export fn georgios_bios_int_inl(port: u16) callconv(.C) u32 { if (debug_io_access) print.format("georgios_bios_int_inl {:x}\n", .{port}); return util.in32(port); } export fn georgios_bios_int_outb(port: u16, value: u8) callconv(.C) void { if (debug_io_access) print.format("georgios_bios_int_outb {:x}, {:x}\n", .{port, value}); return util.out8(port, value); } export fn georgios_bios_int_outw(port: u16, value: u16) callconv(.C) void { if (debug_io_access) print.format("georgios_bios_int_outw {:x}, {:x}\n", .{port, value}); return util.out16(port, value); } export fn georgios_bios_int_outl(port: u16, value: u32) callconv(.C) void { if (debug_io_access) print.format("georgios_bios_int_outl {:x}, {:x}\n", .{port, value}); return util.out32(port, value); } export fn georgios_bios_int_fush_log_impl(buf: [*c]u8, size: c_uint) void { print.string(buf[0..size]); } // For Access to Memory export fn georgios_bios_int_rdb(addr: u32) callconv(.C) u8 { @setRuntimeSafety(false); const value = @intToPtr(*allowzero u8, addr).*; if (debug_mem_access) print.format("georgios_bios_int_rdb {:x} ({:x})\n", .{addr, value}); return value; } export fn georgios_bios_int_rdw(addr: u32) callconv(.C) u16 { @setRuntimeSafety(false); const value = @intToPtr(*allowzero u16, addr).*; if (debug_mem_access) print.format("georgios_bios_int_rdw {:x} ({:x})\n", .{addr, value}); return value; } export fn georgios_bios_int_rdl(addr: u32) callconv(.C) u32 { @setRuntimeSafety(false); const value = @intToPtr(*allowzero u32, addr).*; if (debug_mem_access) print.format("georgios_bios_int_rdl {:x} ({:x})\n", .{addr, value}); return value; } export fn georgios_bios_int_wrb(addr: u32, value: u8) callconv(.C) void { if (debug_mem_access) print.format("georgios_bios_int_wrb {:x}, {:x}\n", .{addr, value}); @setRuntimeSafety(false); @intToPtr(*allowzero u8, addr).* = value; } export fn georgios_bios_int_wrw(addr: u32, value: u16) callconv(.C) void { if (debug_mem_access) print.format("georgios_bios_int_wrw {:x}, {:x}\n", .{addr, value}); @setRuntimeSafety(false); @intToPtr(*allowzero u16, addr).* = value; } export fn georgios_bios_int_wrl(addr: u32, value: u32) callconv(.C) void { if (debug_mem_access) print.format("georgios_bios_int_wrl {:x}, {:x}\n", .{addr, value}); @setRuntimeSafety(false); @intToPtr(*allowzero u32, addr).* = value; } pub fn init() void { c.georgios_bios_int_init(exec_trace); } pub fn run(params: *Params) Error!void { const pmem = &kernel.memory_mgr.impl; pmem.map(.{.start = 0, .size = utils.Mi(1)}, 0, false) catch @panic("bios_int map"); var c_params = c.GeorgiosBiosInt{ .interrupt = params.interrupt, .eax = params.eax, .ebx = params.ebx, .ecx = params.ecx, .edx = params.edx, .edi = params.edi, .slow = params.slow, }; const failed = c.georgios_bios_int_run(&c_params); params.eax = c_params.eax; params.ebx = c_params.ebx; params.ecx = c_params.ecx; params.edx = c_params.edx; params.edi = c_params.edi; params.slow = false; if (failed) { return Error.BiosIntCallFailed; } } pub fn done() void { c.georgios_bios_int_done(); }
0
repos/georgios/kernel
repos/georgios/kernel/platform/timing.zig
// Timing Control // Specifically for the Intel 8253 and 8354 Programmable Interval Timers // (PITs). // // For Reference See: // https://en.wikipedia.org/wiki/Intel_8253 // https://wiki.osdev.org/Programmable_Interval_Timer const util = @import("util.zig"); const acpi = @import("acpi.zig"); /// Base Frequency const oscillator: u32 = 1_193_180; // I/O Ports const channel_arg_base_port: u16 = 0x40; const command_port: u16 = 0x43; const pc_speaker_port: u16 = 0x61; // Set Operating Mode of PITs ================================================= // Use this Python to help decode a raw command byte: // def command(c): // if c & 1: // print("BCD") // print("Mode:", (c >> 1) & 7) // print("Access:", (c >> 4) & 3) // print("Channel:", (c >> 6) & 3) const Mode = enum(u3) { Terminal, OneShot, Rate, Square, SwStrobe, HwStrobe, RateAgain, SquareAgain, }; const Channel = enum(u2) { Irq0, // (Channel 0) Channel1, // Assume to be Unusable Speaker, // (Channel 2) Channel3, // ? pub fn get_arg_port(self: Channel) u16 { return channel_arg_base_port + @enumToInt(self); } }; const Command = packed struct { bcd: bool = false, mode: Mode, access: enum(u2) { Latch, LowByte, HighByte, BothBytes, }, channel: Channel, pub fn perform(self: *const Command) void { util.out8(command_port, @bitCast(u8, self.*)); } }; pub fn set_pit_both_bytes(channel: Channel, mode: Mode, arg: u16) void { // Issue Command const cmd = Command{.channel=channel, .access=.BothBytes, .mode=mode}; cmd.perform(); // Issue Two Byte Argument Required by BothBytes const port: u16 = channel.get_arg_port(); util.out8(port, @truncate(u8, arg)); util.out8(port, @truncate(u8, arg >> 8)); } pub fn set_pit_freq(channel: Channel, frequency: u32) void { set_pit_both_bytes(channel, .Square, @truncate(u16, oscillator / frequency)); } // PC Speaker ================================================================= fn speaker_enabled(enable: bool) callconv(.Inline) void { const mask: u8 = 0b10; const current = util.in8(pc_speaker_port); const desired = if (enable) current | mask else current & ~mask; if (current != desired) { util.out8(pc_speaker_port, desired); } } pub fn beep(frequency: u32, milliseconds: u64) void { set_pit_freq(.Speaker, frequency); speaker_enabled(true); wait_milliseconds(milliseconds); speaker_enabled(false); } // Crude rdtsc-based Timer ==================================================== // Uses the PIC and rdtsc instruction to estimate the clock speed and then use // rdtsc as a crude timer. pub fn rdtsc() u64 { // Based on https://github.com/ziglang/zig/issues/215#issuecomment-261581922 // because I wasn't sure how to handle the fact rdtsc output is broken up // into two registers. const low = asm volatile ("rdtsc" : [low] "={eax}" (-> u32)); const high = asm volatile ("movl %%edx, %[high]" : [high] "=r" (-> u32)); return (@as(u64, high) << 32) | @as(u64, low); } pub var estimated_ticks_per_second: u64 = 0; pub var estimated_ticks_per_millisecond: u64 = 0; pub var estimated_ticks_per_microsecond: u64 = 0; pub var estimated_ticks_per_nanosecond: u64 = 0; pub fn estimate_cpu_speed() void { // Setup the PIT counter to count down oscillator / ticks seconds (About // 1.138 seconds). util.out8(pc_speaker_port, (util.in8(pc_speaker_port) & ~@as(u8, 0x02)) | 0x01); const ticks: u16 = 0xffff; set_pit_both_bytes(.Speaker, .Terminal, ticks); // Record Start rdtsc const start = rdtsc(); // Wait Until PIT Counter is Zero while ((util.in8(pc_speaker_port) & 0x20) == 0) {} // Estimate CPU Tick Rate estimated_ticks_per_second = (rdtsc() - start) * oscillator / ticks; estimated_ticks_per_millisecond = estimated_ticks_per_second / 1000; estimated_ticks_per_microsecond = estimated_ticks_per_millisecond / 1000; estimated_ticks_per_nanosecond = estimated_ticks_per_microsecond / 1000; } pub fn seconds_to_ticks(s: u64) u64{ return s * estimated_ticks_per_second; } pub fn milliseconds_to_ticks(ms: u64) u64 { return ms * estimated_ticks_per_millisecond; } fn wait_ticks(ticks: u64) callconv(.Inline) void { const until = rdtsc() + ticks; while (until > rdtsc()) { asm volatile ("nop"); } } pub fn wait_seconds(s: u64) void { wait_ticks(s * estimated_ticks_per_second); } pub fn wait_milliseconds(ms: u64) void { wait_ticks(ms * estimated_ticks_per_millisecond); } pub fn wait_microseconds(us: u64) void { wait_ticks(us * estimated_ticks_per_microsecond); } pub fn wait_nanoseconds(ns : u64) void { wait_ticks(ns * estimated_ticks_per_nanosecond); } // High Precision Event Timer (HPET) ========================================== pub const HpetTable = packed struct { pub const PageProtection = enum(u4) { None = 0, For4KibPages, For64KibPages, _, }; header: acpi.TableHeader, hardware_rev_id: u8, comparator_count: u5, counter_size: bool, reserved: bool, legacy_replacment: bool, pci_vendor_id: u16, base_address: acpi.Address, hpet_number: u8, minimum_tick: u16, page_protection: PageProtection, oem_attrs: u4, };
0
repos/georgios/kernel
repos/georgios/kernel/platform/vbe_console.zig
const utils = @import("utils"); const Point = utils.U32Point; const Rect = utils.U32Rect; const kernel = @import("root").kernel; const Console = kernel.Console; const HexColor = Console.HexColor; const BitmapFont = kernel.BitmapFont; const platform = @import("platform.zig"); const vbe = platform.vbe; pub fn color_value_from_hex_color(hex_color: HexColor) u32 { return switch (hex_color) { HexColor.White => 0xffe8e6e3, HexColor.LightGray => 0xffd0cfcc, HexColor.DarkGray => 0xff5e5c64, HexColor.Black => 0xff171421, HexColor.Red => 0xffc01c28, HexColor.Green => 0xff26a269, HexColor.Yellow => 0xffa2734c, HexColor.Blue => 0xff12488b, HexColor.Magenta => 0xffa347ba, HexColor.Cyan => 0xff2aa1b3, HexColor.LightRed => 0xfff66151, HexColor.LightGreen => 0xff33da7a, HexColor.LightYellow => 0xffe9ad0c, HexColor.LightBlue => 0xff2a7bde, HexColor.LightMagenta => 0xffc061cb, HexColor.LightCyan => 0xff33c7de, }; } const default_fg_color = HexColor.Black; const default_fg_color_value = color_value_from_hex_color(default_fg_color); const default_bg_color = HexColor.White; const default_bg_color_value = color_value_from_hex_color(default_bg_color); var font: *const BitmapFont = undefined; var glyph_width: usize = undefined; var glyph_height: usize = undefined; var fg_color: HexColor = undefined; var bg_color: HexColor = undefined; var fg_color_value: u32 = undefined; var bg_color_value: u32 = undefined; var scroll_count: u32 = 0; var show_cursor = true; pub var console = Console{ .place_impl = place_impl, .scroll_impl = scroll_impl, .set_hex_color_impl = set_hex_color_impl, .get_hex_color_impl = get_hex_color_impl, .use_default_color_impl = use_default_color_impl, .reset_attributes_impl = reset_attributes_impl, .move_cursor_impl = move_cursor_impl, .show_cursor_impl = show_cursor_impl, .clear_screen_impl = clear_screen_impl, }; pub fn init(screen_width: u32, screen_height: u32, bitmap_font: *const BitmapFont) void { font = bitmap_font; glyph_width = font.bdf_font.bounds.size.x; glyph_height = font.bdf_font.bounds.size.y; console.init(screen_width / glyph_width, screen_height / glyph_height); clear_screen_impl(&console); } fn place_impl_no_flush(c: *Console, utf32_value: u32, row: u32, col: u32) Rect { _ = c; const x = col * glyph_width; const y = row * glyph_height; vbe.draw_glyph(font, x, y, utf32_value, fg_color_value, bg_color_value); return .{.pos = .{.x = x, .y = y}, .size = .{.x = glyph_width, .y = glyph_height}}; } fn place_impl(c: *Console, utf32_value: u32, row: u32, col: u32) void { vbe.flush_buffer_rect(&place_impl_no_flush(c, utf32_value, row, col)); } pub fn set_hex_color_impl(c: *Console, color: HexColor, layer: Console.Layer) void { _ = c; if (layer == .Foreground) { fg_color = color; fg_color_value = color_value_from_hex_color(color); } else { bg_color = color; bg_color_value = color_value_from_hex_color(color); } } pub fn get_hex_color_impl(c: *Console, layer: Console.Layer) HexColor { _ = c; return if (layer == .Foreground) fg_color else bg_color; } fn use_default_color_impl(c: *Console, layer: Console.Layer) void { c.set_hex_color(if (layer == .Foreground) default_fg_color else default_bg_color, layer); } pub fn reset_attributes_impl(c: *Console) void { _ = c; scroll_count = 0; } pub fn clear_screen_impl(c: *Console) void { _ = c; vbe.fill_buffer(bg_color_value); vbe.flush_buffer(); } pub fn move_cursor_impl(c: *Console, row: u32, col: u32) void { _ = c; if (show_cursor and false) { // TODO: Finish cursor const pos = Rect.Pos{.x = col * glyph_width, .y = row * glyph_height}; const size = font.bdf_font.bounds.size.as(Rect.Size.Num); vbe.draw_rect(&.{.pos = pos, .size = size.minus_int(1)}, 0xff000000); vbe.flush_buffer_rect(&.{.pos = pos, .size = size}); } } pub fn show_cursor_impl(c: *Console, show: bool) void { _ = c; show_cursor = show; } pub fn scroll_impl(c: *Console) void { _ = c; scroll_count += 1; vbe.scroll_buffer(glyph_height, default_bg_color_value); vbe.flush_buffer(); } pub fn get_info(last_scroll_count: *u32, size: *Point, pos: *Point, glyph_size: *Point) void { last_scroll_count.* = scroll_count; scroll_count = 0; size.* = .{.x = console.width, .y = console.height}; pos.* = .{.x = console.column, .y = console.row}; const gs = font.bdf_font.bounds.size; glyph_size.* = .{.x = gs.x, .y = gs.y}; }
0
repos/georgios/kernel
repos/georgios/kernel/platform/util.zig
// Miscellaneous Assembly-based Utilities // x86 I/O Port Access ======================================================== pub fn out8(port: u16, val: u8) void { asm volatile ("outb %[val], %[port]" : : [val] "{al}" (val), [port] "N{dx}" (port)); } pub fn out16(port: u16, val: u16) void { asm volatile ("outw %[val], %[port]" : : [val] "{al}" (val), [port] "N{dx}" (port)); } pub fn out32(port: u16, val: u32) void { asm volatile ("outl %[val], %[port]" : : [val] "{al}" (val), [port] "N{dx}" (port)); } pub fn in8(port: u16) u8 { return asm volatile ("inb %[port], %[rv]" : [rv] "={al}" (-> u8) : [port] "N{dx}" (port) ); } pub fn in16(port: u16) u16 { return asm volatile ("inw %[port], %[rv]" : [rv] "={al}" (-> u16) : [port] "N{dx}" (port) ); } pub fn in32(port: u16) u32 { return asm volatile ("inl %[port], %[rv]" : [rv] "={al}" (-> u32) : [port] "N{dx}" (port) ); } pub fn out(comptime Type: type, port: u16, val: Type) void { switch (Type) { u8 => out8(port, val), u16 => out16(port, val), u32 => out32(port, val), else => @compileError("Invalid Type: " ++ @typeName(Type)), } } pub fn in(comptime Type: type, port: u16) Type { return switch (Type) { u8 => in8(port), u16 => in16(port), u32 => in32(port), else => @compileError("Invalid Type: " ++ @typeName(Type)), }; } /// Copy a series of bytes into destination, like using in8 over the slice. /// /// https://c9x.me/x86/html/file_module_x86_id_141.html pub fn in_bytes(port: u16, destination: []u8) void { asm volatile ("rep insw" : : [port] "{dx}" (port), [dest_ptr] "{di}" (@truncate(u32, @ptrToInt(destination.ptr))), [dest_size] "{ecx}" (@truncate(u32, destination.len) >> 1) : "memory"); } // Mask/Unmask Interrupts ===================================================== pub fn enable_interrupts() void { asm volatile ("sti"); } pub fn disable_interrupts() void { asm volatile ("cli"); } // Halt ======================================================================= pub fn halt() void { asm volatile ("hlt"); } pub fn idle() noreturn { while (true) { enable_interrupts(); halt(); } unreachable; } pub fn halt_forever() noreturn { disable_interrupts(); while (true) { halt(); } unreachable; } // x86 Control Registers ====================================================== /// Page Fault Address pub fn cr2() u32 { return asm volatile ("mov %%cr2, %[rv]" : [rv] "={eax}" (-> u32)); }
0
repos/georgios/kernel
repos/georgios/kernel/platform/memory.zig
// x86 Memory Management // // Memory management consistents of frame management and page management. // Frames are chunks of real/physical memory that are joined in a // linked list when unused: // // +-----+ +-----+ // next_free_frame->|Frame|->|Frame|->...->null // +-----+ +-----+ // // Pages are the in-use frames that mapped into the virtual memory that the // kernel and programs can directly access. They are accessed by the CPU using // a set of strutures the kernel has to set up: // // Page Directory Page Tables Used Frames // +-------------+ +------+ +----------------+ // %cr3->|Table 0 Ptr. |->|Page 0|---->|Frame for Page 0| // +-------------+ +------+ +----------------+ // |Table 1 Ptr. | |Page 1|---->|Frame for Page 0| // +-------------+ +------+ +----------------+ // |... | |... | |... | // +-------------+ +------+ +----------------+ // // NOTE: In Georgios %cr3 is always set to the active_page_directory array. // With the exception of kernel space, whole new virtual memory layouts are // copied to and from active_page_directory to swap memory, followed by a call // to reload_active_page_directory to inform the CPU the page directory // changed. // // For Reference See: // https://wiki.osdev.org/Paging // https://ethv.net/workshops/osdev/notes/notes-2.html const std = @import("std"); const sliceAsBytes = std.mem.sliceAsBytes; const georgios = @import("georgios"); const utils = @import("utils"); const kernel = @import("root").kernel; const memory = kernel.memory; const RealMemoryMap = memory.RealMemoryMap; const AllocError = memory.AllocError; const FreeError = memory.FreeError; const Range = memory.Range; const print = kernel.print; const BuddyAllocator = @import("../buddy_allocator.zig").BuddyAllocator; const platform = @import("platform.zig"); pub const frame_size = utils.Ki(4); pub const page_size = frame_size; const pages_per_table = utils.Ki(1); const table_pages_size = page_size * pages_per_table; const tables_per_directory = utils.Ki(1); const table_size = @sizeOf(u32) * pages_per_table; export var active_page_directory: [tables_per_directory]u32 align(frame_size) linksection(".data") = undefined; export var kernel_page_tables: []u32 = undefined; pub export var kernel_range_start_available: u32 = undefined; export var kernel_page_table_count: u32 = 0; extern var _VIRTUAL_LOW_START: u32; pub fn get_address(dir_index: usize, table_index: usize) callconv(.Inline) usize { return dir_index * table_pages_size + table_index * page_size; } // Page Directory Operations pub fn get_directory_index(address: u32) callconv(.Inline) u32 { return (address & 0xffc00000) >> 22; } extern var _VIRTUAL_OFFSET: u32; pub fn get_kernel_space_start_directory_index() callconv(.Inline) u32 { return get_directory_index(@ptrToInt(&_VIRTUAL_OFFSET)); } pub fn table_is_present(entry: u32) callconv(.Inline) bool { return (entry & 1) == 1; } pub fn get_table_address(entry: u32) callconv(.Inline) u32 { return entry & 0xfffff000; } // (End of Page Directory Operations) // Page Table Operations pub fn get_table_index(address: u32) callconv(.Inline) u32 { return (address & 0x003ff000) >> 12; } pub fn page_is_present(entry: u32) callconv(.Inline) bool { // Bit 9 (0x200) marks a guard page to Georgios. This will be marked as not // present in the entry itself (bit 1) so that it causes a page fault if // accessed. return (entry & 0x201) != 0; } pub fn as_guard_page(entry: u32) callconv(.Inline) u32 { return (entry & 0xfffffffe) | 0x200; } pub fn page_is_guard_page(entry: u32) callconv(.Inline) bool { return (entry & 0x201) == 0x200; } pub fn get_page_address(entry: u32) callconv(.Inline) u32 { return entry & 0xfffff000; } pub fn present_entry(address: u32) callconv(.Inline) u32 { return (address & 0xfffff000) | 1; } pub fn set_entry(entry: *allowzero u32, address: usize, user: bool) callconv(.Inline) void { // TODO: Seperate User and Write entry.* = present_entry(address) | (if (user) @as(u32, 0b110) else @as(u32, 0)); } // (End of Page Table Operations) pub fn invalidate_page(address: u32) void { asm volatile ("invlpg (%[address])" : : [address] "{eax}" (address)); } pub fn reload_active_page_directory() void { asm volatile ( \\ movl $low_page_directory, %%eax \\ movl %%eax, %%cr3 ::: "eax" ); } pub fn load_page_directory(new: []const u32, old: ?[]u32) utils.Error!void { const end = get_kernel_space_start_directory_index(); if (old) |o| { _ = try utils.memory_copy_error( sliceAsBytes(o[0..end]), sliceAsBytes(active_page_directory[0..end])); } _ = try utils.memory_copy_error( sliceAsBytes(active_page_directory[0..end]), sliceAsBytes(new[0..end])); reload_active_page_directory(); } const FrameAccessSlot = struct { i: u16, current_frame_address: ?u32 = null, page_address: u32 = undefined, page_table_entry: *u32 = undefined, pub fn init(self: *FrameAccessSlot) void { self.page_address = @ptrToInt(&_VIRTUAL_LOW_START) + page_size * self.i; self.page_table_entry = &kernel_page_tables[get_table_index(self.page_address)]; } }; /// Before we can allocate memory properly we need to be able to manually /// change physical memory to setup frame allocation and create new page /// tables. We can bootstrap this process by using a bit of real and virtual /// memory we know is safe to use and map it to the frame want to change. /// /// This involves reserving a FrameAccessSlot using a FrameAccess object for /// the type to map. There can only be one FrameAccess using a slot at a time /// or else there will be a panic. See below for the slot objects. fn FrameAccess(comptime Type: type) type { const Traits = @typeInfo(Type); comptime var slice_len: ?comptime_int = null; comptime var PtrType: type = undefined; const GetType = switch (Traits) { std.builtin.TypeId.Array => |array_type| blk: { slice_len = array_type.len; PtrType = [*]array_type.child; break :blk []array_type.child; }, else => else_blk: { PtrType = *Type; break :else_blk *Type; } }; return struct { const Self = @This(); slot: *FrameAccessSlot, ptr: PtrType, pub fn new(slot: *FrameAccessSlot, frame_address: u32) Self { if (slot.current_frame_address != null) { @panic("The FrameAccess slot is already active!"); } slot.current_frame_address = frame_address; const needed_entry = (frame_address & 0xfffff000) | 1; if (slot.page_table_entry.* != needed_entry) { slot.page_table_entry.* = needed_entry; invalidate_page(slot.page_address); } return Self{.slot = slot, .ptr = @intToPtr(PtrType, slot.page_address)}; } pub fn get(self: *const Self) GetType { return if (slice_len) |l| self.ptr[0..l] else self.ptr; } pub fn done(self: *const Self) void { if (self.slot.current_frame_address == null) { @panic("Done called, but slot is already inactive"); } self.slot.current_frame_address = null; } }; } var pmem_frame_access_slot: FrameAccessSlot = .{.i = 0}; var page_table_frame_access_slot: FrameAccessSlot = .{.i = 1}; var page_frame_access_slot: FrameAccessSlot = .{.i = 2}; // NOTE: More cannot be added unless room is made in the linking script by // adjusting .low_force_space_begin_align to make _REAL_LOW_END increase. /// Add Frame Groups to Our Memory Map from Multiboot Memory Map pub fn process_multiboot2_mmap(map: *RealMemoryMap, tag: *const Range) void { const entry_size = @intToPtr(*u32, tag.start + 8).*; const entries_end = tag.start + tag.size; var entry_ptr = tag.start + 16; while (entry_ptr < entries_end) : (entry_ptr += entry_size) { if (@intToPtr(*u32, entry_ptr + 16).* == 1) { var range_start = @intCast(usize, @intToPtr(*u64, entry_ptr).*); var range_size = @intCast(usize, @intToPtr(*u64, entry_ptr + 8).*); const range_end = range_start + range_size; if (range_start >= platform.kernel_real_start() and platform.kernel_real_end() <= range_end) { // This is the kernel, remove it from the range. range_size = range_end - kernel_range_start_available; range_start = kernel_range_start_available; } if (range_start < frame_size) { // This is the Real Mode IVT and BDA, remove it from the range. range_start = frame_size; } map.add_frame_group(range_start, range_size); } } } pub const ManagerImpl = struct { const FreeFramePtr = ?usize; const FreeFramePtrAccess = FrameAccess(FreeFramePtr); fn access_free_frame(frame: u32) FreeFramePtrAccess { return FreeFramePtrAccess.new(&pmem_frame_access_slot, frame); } const TableAccess = FrameAccess([pages_per_table]u32); fn access_page_table(frame: u32) TableAccess { return TableAccess.new(&page_table_frame_access_slot, frame); } const PageAccess = FrameAccess([page_size]u8); fn access_page(frame: u32) PageAccess { return PageAccess.new(&page_frame_access_slot, frame); } const kernel_space_size = utils.Gi(1); const kernel_space_start = 0xc0000000; const kernel_space = @intToPtr([*]u8, kernel_space_start)[0..kernel_space_size]; const KernelSpacePageAlloc = BuddyAllocator(kernel_space_size, page_size, .InSelf); parent: *memory.Manager = undefined, next_free_frame: FreeFramePtr = null, kernel_tables_index_start: usize = 0, start_of_virtual_space: usize = 0, kernel_space_page_alloc: KernelSpacePageAlloc = undefined, page_allocator: memory.Allocator = undefined, pub fn init(self: *ManagerImpl, parent: *memory.Manager, memory_map: *RealMemoryMap) void { self.parent = parent; self.page_allocator.alloc_impl = ManagerImpl.page_alloc; self.page_allocator.free_impl = ManagerImpl.page_free; parent.big_alloc = &self.page_allocator; pmem_frame_access_slot.init(); page_table_frame_access_slot.init(); page_frame_access_slot.init(); for (memory_map.frame_groups[0..memory_map.frame_group_count]) |*i| { parent.total_frame_count += i.frame_count; var frame: usize = 0; while (frame < i.frame_count) { self.push_frame(i.start + frame * frame_size); frame += 1; } } parent.free_frame_count = parent.total_frame_count; // var counted: usize = 0; // while (true) { // _ = self.pop_frame() catch break; // counted += 1; // } // print.format("total_count: {}, counted: {}\n", total_count, counted); self.start_of_virtual_space = utils.align_up( @ptrToInt(kernel_page_tables.ptr) + kernel_page_tables.len * table_size, table_pages_size); self.kernel_space_page_alloc.init(kernel_space) catch @panic("failed to init kernel page allocator"); const range = kernel_space[0..self.start_of_virtual_space - kernel_space_start]; self.kernel_space_page_alloc.reserve(range) catch @panic("failed to reserve space in kernel page allocator"); } pub fn push_frame(self: *ManagerImpl, frame: usize) void { // Put the current next_free_frame into the frame. const access = access_free_frame(frame); access.get().* = self.next_free_frame; access.done(); // Point to that frame. self.next_free_frame = frame; self.parent.free_frame_count += 1; } pub fn pop_frame(self: *ManagerImpl) AllocError!usize { if (self.next_free_frame) |frame| { const prev = frame; // Get the "next" next_free_frame from the contents of the current // one. const access = access_free_frame(frame); self.next_free_frame = access.get().*; access.done(); self.parent.free_frame_count -= 1; // Return the previous next_free_frame return prev; } return AllocError.OutOfMemory; } const PageIter = struct { mgr: *ManagerImpl, page_directory: []u32, virtual_range: Range, offset: usize, user: bool, dir_index: usize, table_index: usize, left: usize, initial_call: bool = true, changed_table: bool = undefined, fn new(mgr: *ManagerImpl, page_directory: []u32, virtual_range: Range, align_to_page_size: bool, user: bool) PageIter { return .{ .mgr = mgr, .page_directory = page_directory, .virtual_range = virtual_range, .offset = virtual_range.start % page_size, .user = user, .dir_index = get_directory_index(virtual_range.start), .table_index = get_table_index(virtual_range.start), .left = if (align_to_page_size) utils.align_up(virtual_range.size, page_size) else virtual_range.size, }; } fn address(self: *PageIter) usize { return get_address(self.dir_index, self.table_index); } fn iter(self: *PageIter) ?*PageIter { if (self.left == 0 or self.dir_index >= tables_per_directory) return null; if (self.initial_call) { self.initial_call = false; self.changed_table = true; } else { self.left -= @minimum(page_size, self.left); self.table_index += 1; self.offset = 0; self.changed_table = self.table_index >= pages_per_table; if (self.changed_table) { self.table_index = 0; self.dir_index += 1; } if (self.left == 0 or self.dir_index >= tables_per_directory) return null; } return self; } fn no_table(self: *PageIter) bool { return !table_is_present(self.page_directory[self.dir_index]); } fn ensure_table(self: *PageIter) AllocError!void { if (self.changed_table and self.no_table()) { try self.mgr.new_page_table(self.page_directory, self.dir_index, self.user); } } fn get_table_access(self: *PageIter) TableAccess { return access_page_table(get_table_address(self.page_directory[self.dir_index])); } fn map_to_i(self: *PageIter, table_entry: *u32, physical_address: usize) void { set_entry(table_entry, physical_address, self.user); if (&self.page_directory[0] == &active_page_directory[0]) { invalidate_page(self.address()); } } fn ensure_page(self: *PageIter) AllocError!void { try self.ensure_table(); const table_access = self.get_table_access(); defer table_access.done(); const table = table_access.get(); if (page_is_guard_page(table[self.table_index])) { @panic("ensure_page: page is guard page!"); } const table_entry = &table[self.table_index]; if (!page_is_present(table_entry.*)) { self.map_to_i(table_entry, try self.mgr.pop_frame()); } } fn map_to(self: *PageIter, physical_address: usize) AllocError!void { try self.ensure_table(); const table_access = self.get_table_access(); defer table_access.done(); const table = table_access.get(); if (page_is_guard_page(table[self.table_index])) { @panic("map_to: page is guard page!"); } if (page_is_present(table[self.table_index])) { @panic("map_to: page already present!"); } self.map_to_i(&table[self.table_index], physical_address); } fn access(self: *PageIter) PageAccess { const table_access = self.get_table_access(); defer table_access.done(); const table = table_access.get(); return access_page(get_page_address(table[self.table_index])); } }; // TODO: Read/Write and Any Other Options pub fn mark_virtual_memory_present(self: *ManagerImpl, page_directory: []u32, range: Range, user: bool) AllocError!void { var page_iter = PageIter.new(self, page_directory, range, true, user); while (page_iter.iter()) |page| { try page.map_to(try self.pop_frame()); } } // TODO fn mark_virtual_memory_absent(self: *ManagerImpl, range: Range) void { _ = self; _ = range; } pub fn map(self: *ManagerImpl, virtual_range: Range, physical_start: usize, user: bool) AllocError!void { var page_iter = PageIter.new(self, active_page_directory[0..], virtual_range, true, user); var physical_address = physical_start; while (page_iter.iter()) |page| { try page.map_to(physical_address); physical_address +%= page_size; } } pub fn page_directory_memory_dump(self: *ManagerImpl, page_directory: []u32, address: usize, len: usize) void { const range = Range{.start = address, .size = len}; var page_iter = PageIter.new(self, page_directory, range, false, true); while (page_iter.iter()) |page| { const access = page.access(); defer access.done(); const page_data = access.get()[page.offset..]; try georgios.get_console_writer().print("{}", .{utils.fmt_dump_hex(page_data)}); } } pub fn page_directory_memory_copy(self: *ManagerImpl, page_directory: []u32, address: usize, data: []const u8) AllocError!void { // print.format("page_directory_memory_copy: {} b to {:a}\n", .{data.len, address}); const range = Range{.start = address, .size = data.len}; var page_iter = PageIter.new(self, page_directory, range, false, true); var data_left = data; while (page_iter.iter()) |page| { try page.ensure_page(); const access = page.access(); defer access.done(); const copy_to = access.get()[page.offset..]; const copied = utils.memory_copy_truncate(copy_to, data_left); data_left = data_left[copied..]; } if (data_left.len > 0) { @panic("page_directory_memory_copy: data_left.len > 0"); } } pub fn page_directory_memory_set(self: *ManagerImpl, page_directory: []u32, address: usize, byte: u8, len: usize) AllocError!void { // print.format("page_directory_memory_set: {} b at {:a}\n", .{len, address}); const range = Range{.start = address, .size = len}; var page_iter = PageIter.new(self, page_directory, range, false, true); while (page_iter.iter()) |page| { try page.ensure_page(); const access = page.access(); defer access.done(); utils.memory_set(access.get()[page.offset..], byte); } } pub fn get_unused_kernel_space(self: *ManagerImpl, requested_size: usize) AllocError!Range { return Range.from_bytes( try self.kernel_space_page_alloc.allocator.alloc_array(u8, requested_size)); } pub fn new_page_table(self: *ManagerImpl, page_directory: []u32, dir_index: usize, user: bool) AllocError!void { // print.format("new_page_table {:x}\n", dir_index); // TODO: Go through memory.Memory const table_address = try self.pop_frame(); // TODO set_entry for page_directory set_entry(&page_directory[dir_index], table_address, user); const access = access_page_table(table_address); const table = access.get(); var i: usize = 0; while (i < pages_per_table) { table[i] = 0; i += 1; } access.done(); } pub fn make_guard_page(self: *ManagerImpl, page_directory: ?[]u32, address: usize, user: bool) AllocError!void { const page_dir = page_directory orelse active_page_directory[0..]; const dir_index = get_directory_index(address); if (!table_is_present(page_dir[dir_index])) { try self.new_page_table(page_dir, dir_index, user); } const access = access_page_table(get_table_address(page_dir[dir_index])); defer access.done(); const table = access.get(); const table_index = get_table_index(address); const free_frame: ?u32 = if (page_is_present(table[table_index])) get_page_address(table[table_index]) else null; table[table_index] = as_guard_page(table[table_index]); if (&page_dir[0] == &active_page_directory[0]) { invalidate_page(get_address(dir_index, table_index)); } if (free_frame) |addr| { self.push_frame(addr); } } fn page_alloc(allocator: *memory.Allocator, size: usize, align_to: usize) AllocError![]u8 { _ = align_to; const self = @fieldParentPtr(ManagerImpl, "page_allocator", allocator); const range = try self.get_unused_kernel_space(size); try self.mark_virtual_memory_present(active_page_directory[0..], range, false); return range.to_slice(u8); } fn page_free(allocator: *memory.Allocator, value: []const u8, aligned_to: usize) FreeError!void { const self = @fieldParentPtr(ManagerImpl, "page_allocator", allocator); // TODO _ = self; _ = value; _ = aligned_to; } pub fn new_page_directory(self: *ManagerImpl) AllocError![]u32 { _ = self; const page_directory = try self.parent.big_alloc.alloc_array(u32, tables_per_directory); _ = utils.memory_set(sliceAsBytes(page_directory[0..]), 0); return page_directory; } };
0
repos/georgios/kernel
repos/georgios/kernel/platform/segments.zig
// Code for managing up the Global Descriptor Table (GDT) and related data // structures. // // We must define the segment selectors required 80286 memory protection scheme // and also the Task State Segment (TSS) required for context switching. // // For Reference See: // Intel® 64 and IA-32 Architectures Software Developer’s Manual // https://wiki.osdev.org/Global_Descriptor_Table // https://wiki.osdev.org/Segmentation const builtin = @import("builtin"); const std = @import("std"); const utils = @import("utils"); const kernel = @import("root").kernel; const print = kernel.print; const platform = @import("platform.zig"); const kernel_to_virtual = platform.kernel_to_virtual; const TaskStateSegment = packed struct { link: u16 = 0, zero1: u16 = 0, esp0: u32 = 0, ss0: u16 = 0, zero2: u16 = 0, esp1: u32 = 0, ss1: u16 = 0, zero3: u16 = 0, esp2: u32 = 0, ss2: u16 = 0, zero4: u16 = 0, cr3: u32 = 0, eip: u32 = 0, eflags: u32 = 0, eax: u32 = 0, ecx: u32 = 0, edx: u32 = 0, ebx: u32 = 0, esp: u32 = 0, ebp: u32 = 0, esi: u32 = 0, edi: u32 = 0, es: u16 = 0, zero5: u16 = 0, cs: u16 = 0, zero6: u16 = 0, ss: u16 = 0, zero7: u16 = 0, ds: u16 = 0, zero8: u16 = 0, fs: u16 = 0, zero9: u16 = 0, gs: u16 = 0, zero10: u16 = 0, ldt_selector: u16 = 0, zero11: u16 = 0, trap: bool = false, zero12: u15 = 0, io_map: u16 = 0, }; var task_state_segment = TaskStateSegment{}; pub fn set_interrupt_handler_stack(esp: u32) void { task_state_segment.esp0 = esp; task_state_segment.ss0 = kernel_data_selector; } const Access = packed struct { accessed: bool = false, /// Readable Flag for Code Selectors, Writable Bit for Data Selectors rw: bool = true, /// Direction/Conforming Flag /// For data selectors sets the direction of segment growth. I don't think /// I care about that. For code selectors true means code in this segment /// can be executed by lower rings. dc: bool = false, /// True for Code Selectors, False for Data Selectors executable: bool = false, /// True for Code and Data Segments no_system_segment: bool = true, /// 0 (User) through 3 (Kernel) ring_level: u2 = 0, valid: bool = true, }; const Flags = packed struct { always_zero: u2 = 0, /// Protected Mode (32 bits) segment if true pm: bool = true, /// Limit is bytes if this is true, else limit is in pages. granularity: bool = true, }; const Entry = packed struct { limit_0_15: u16, base_0_15: u16, base_16_23: u8, access: Access, // TODO: Zig Bug? // Highest 4 bits of limit and flags. Was going to have this be two 4 bit // fields, but that wasn't the same thing as this for some reason... limit_16_19: u8, base_24_31: u8, }; var table: [6]Entry = undefined; pub var names: [table.len][]const u8 = undefined; pub fn get_name(index: u32) []const u8 { return if (index < names.len) names[index] else "Selector index is out of range"; } fn set(name: []const u8, index: u8, base: u32, limit: u32, access: Access, flags: Flags) u16 { names[index] = name; print.debug_format(" - [{}]: \"{}\"", .{index, name}); if (access.valid) { print.debug_format("\n - starts at {:a}, size is {:x} {}, {} Ring {} ", .{ base, limit, if (flags.granularity) @as([]const u8, "b") else @as([]const u8, "pages"), if (flags.pm) @as([]const u8, "32b") else @as([]const u8, "16b"), @intCast(usize, access.ring_level)}); if (access.no_system_segment) { if (access.executable) { print.debug_format( "Code Segment\n" ++ " - Can{} be read by lower rings.\n" ++ " - Can{} be executed by lower rings\n", .{ if (access.rw) @as([]const u8, "") else @as([]const u8, " NOT"), if (access.dc) @as([]const u8, "") else @as([]const u8, " NOT")}); } else { print.debug_format( "Data Segment\n" ++ " - Can{} be written to by lower rings.\n" ++ " - Grows {}.\n", .{ if (access.rw) @as([]const u8, "") else @as([]const u8, " NOT"), if (access.dc) @as([]const u8, "down") else @as([]const u8, "up")}); } } else { print.debug_string("System Segment\n"); } if (access.accessed) { print.debug_string(" - Accessed\n"); } } else { print.debug_char('\n'); } table[index].limit_0_15 = @intCast(u16, limit & 0xffff); table[index].base_0_15 = @intCast(u16, base & 0xffff); table[index].base_16_23 = @intCast(u8, (base >> 16) & 0xff); table[index].access = access; table[index].limit_16_19 = @intCast(u8, (limit >> 16) & 0xf) | (@intCast(u8, @bitCast(u4, flags)) << 4); table[index].base_24_31 = @intCast(u8, (base >> 24) & 0xff); return (index << 3) | access.ring_level; } fn set_null_entry(index: u8) void { _ = set("Null", index, 0, 0, std.mem.zeroes(Access), std.mem.zeroes(Flags)); names[index] = "Null"; } const Pointer = packed struct { limit: u16, base: u32, }; extern fn gdt_load(pointer: *const Pointer) void; comptime { asm ( \\ .section .text \\ .global gdt_load \\ .type gdt_load, @function \\ gdt_load: \\ movl 4(%esp), %eax \\ lgdt (%eax) \\ movw (kernel_data_selector), %ax \\ movw %ax, %ds \\ movw %ax, %es \\ movw %ax, %fs \\ movw %ax, %gs \\ movw %ax, %ss \\ pushl (kernel_code_selector) \\ push $.gdt_complete_load \\ ljmp *(%esp) \\ .gdt_complete_load: \\ movw (tss_selector), %ax \\ ltr %ax \\ add $8, %esp \\ ret ); } pub var kernel_code_selector: u16 = 0; pub var kernel_data_selector: u16 = 0; pub var user_code_selector: u16 = 0; pub var user_data_selector: u16 = 0; export var tss_selector: u16 = 0; pub fn init() void { print.debug_string(" - Filling the Global Descriptor Table (GDT)\n"); set_null_entry(0); const flags = Flags{}; kernel_code_selector = set("Kernel Code", 1, 0, 0xFFFFFFFF, Access{.ring_level = 0, .executable = true}, flags); kernel_data_selector = set("Kernel Data", 2, 0, 0xFFFFFFFF, Access{.ring_level = 0}, flags); user_code_selector = set("User Code", 3, 0, kernel_to_virtual(0) - 1, Access{.ring_level = 3, .executable = true}, flags); user_data_selector = set("User Data", 4, 0, kernel_to_virtual(0) - 1, Access{.ring_level = 3}, flags); tss_selector = set("Task State", 5, @ptrToInt(&task_state_segment), @sizeOf(TaskStateSegment) - 1, // TODO: Make This Explicit @bitCast(Access, @as(u8, 0xe9)), @bitCast(Flags, @as(u4, 0))); const pointer = Pointer { .limit = @intCast(u16, @sizeOf(@TypeOf(table)) - 1), .base = @intCast(u32, @ptrToInt(&table)), }; gdt_load(&pointer); }
0
repos/georgios/kernel
repos/georgios/kernel/platform/ps2.zig
// ============================================================================ // PS/2 Driver for Mouse and Keyboard // Interacts through the Intel 8042 controller. // // For reference: // https://wiki.osdev.org/%228042%22_PS/2_Controller // https://wiki.osdev.org/PS/2_Keyboard // https://isdaman.com/alsos/hardware/mouse/ps2interface.htm // https://wiki.osdev.org/PS/2_Mouse // ============================================================================ const build_options = @import("build_options"); const utils = @import("utils"); const georgios = @import("georgios"); const keyboard = georgios.keyboard; const Key = keyboard.Key; const KeyboardEvent = keyboard.Event; const MouseEvent = georgios.MouseEvent; const kernel = @import("root").kernel; const print = kernel.print; const key_to_char = kernel.keys.key_to_char; const putil = @import("util.zig"); const interrupts = @import("interrupts.zig"); const segments = @import("segments.zig"); const scan_codes = @import("ps2_scan_codes.zig"); const Error = error { Ps2ResetFailed, Ps2DeviceIssue, }; var keyboard_initialized = false; var keyboard_modifiers = keyboard.Modifiers{}; var keyboard_buffer = utils.CircularBuffer(KeyboardEvent, 128, .DiscardNewest){}; var mouse_initialized = false; var mouse_buffer = utils.CircularBuffer(MouseEvent, 256, .DiscardNewest){}; const controller = struct { const data_port: u16 = 0x60; const command_status_port: u16 = 0x64; const ack: u8 = 0xfa; const DeviceKind = enum { Unknown, Keyboard, Mouse, }; var port1_device: ?DeviceKind = null; var port2_device: ?DeviceKind = null; fn port1_is_keyboard() bool { return port1_device == DeviceKind.Keyboard; } fn port2_is_mouse() bool { return port2_device == DeviceKind.Mouse; } const Status = packed struct { const Dest = enum(u1) { Device = 0, Controller = 1, }; has_data: bool, not_ready_for_write: bool, system_flag: bool, write_dest: Dest, unknown: u2, timeout_error: bool, parity_error: bool, }; fn read_status() Status { return @bitCast(Status, putil.in8(command_status_port)); } fn read_data_with_timeout(timeout: u16) ?u8 { var n: usize = 0; while (true) { if (read_status().has_data) { const byte = putil.in8(data_port); // print.format("read_data_with_timeout: {:x}\n", .{byte}); return byte; } if (timeout > 0) { n += 1; if (n >= timeout) break; } } // print.string("read_data_with_timeout: null\n"); return null; } fn read_data() u8 { return read_data_with_timeout(0).?; } fn read_data_as(comptime Type: type, timeout: u16) Error!Type { var status: [@sizeOf(Type)]u8 = undefined; for (status) |*byte| { byte.* = read_data_with_timeout(timeout) orelse { return Error.Ps2DeviceIssue; }; } return @bitCast(Type, status); } fn write(port: u16, value: u8) void { while (read_status().not_ready_for_write) { } return putil.out8(port, value); } fn write_data(value: u8) void { write(data_port, value); } const HasResponse = enum { NoRes, HasRes, }; fn command(cmd: u8, arg: ?u8, has_res: HasResponse) ?u8 { write(command_status_port, cmd); if (arg) |arg_byte| { write_data(arg_byte); } return if (has_res == .HasRes) read_data() else null; } const Config = packed struct { port1_interrupt_enabled: bool, port2_interrupt_enabled: bool, system_flag: bool, zero1: u1 = 0, port1_check: bool, port2_check: bool, port1_translation: bool, zero2: u1 = 0, }; fn read_config() Config { return @bitCast(Config, command(0x20, null, .HasRes).?); } fn write_config(config: Config) void { _ = command(0x60, @bitCast(u8, config), .NoRes); } const Port = enum(u2) { Port1 = 0, Port2 = 1, }; fn enable_port(port: Port, enabled: bool) void { const cmds = [_]u8{0xad, 0xae, 0xa7, 0xa8}; _ = command(cmds[(@enumToInt(port) << 1) | @boolToInt(enabled)], null, .NoRes); } fn device_command(port: Port, cmd: u8) u8 { if (port == .Port1) { write_data(cmd); } else { _ = command(0xd4, cmd, .NoRes); } return read_data(); } const MouseStatus = packed struct { const Scaling = enum(u1) { OneToOne = 0, TwoToOne = 1, }; const Mode = enum(u1) { Stream = 0, Remote = 1, }; rmb_pressed: bool, mmb_pressed: bool, lmb_pressed: bool, zero1: u1 = 0, scaling: Scaling, data_enabled: bool, mode: Mode, zero2: u1 = 0, resolution: u8, sample_rate: u8, }; fn get_mouse_status(port: Port) Error!MouseStatus { const ack_res = device_command(port, 0xe9); if (ack_res != ack) { print.format("WARNING: get_mouse_status: PS/2 device on {} replied {} for ack\n", .{port, ack_res}); return Error.Ps2DeviceIssue; } return read_data_as(MouseStatus, 512); } fn mouse_data_enabled(port: Port, enabled: bool) Error!void { const ack_res = device_command(port, if (enabled) 0xf4 else 0xf5); if (ack_res != ack) { print.format("WARNING: get_mouse_status: PS/2 device on {} replied {} for ack\n", .{port, ack_res}); return Error.Ps2DeviceIssue; } } fn reset_device(port: Port, device: *?DeviceKind) Error!void { device.* = null; // Reset: This returns an ack, a self-test result, and a 0 to 2 byte // byte sequence id. The last part doesn't seem to be properly // documented on the osdev wiki. (TODO?) // TODO: Detect no device const ack_res = device_command(port, 0xff); if (ack_res != ack) { print.format("WARNING: reset_device: PS/2 device on {} replied {} for ack\n", .{port, ack_res}); return; } // Self-test result const self_test_res = read_data(); if (self_test_res != 0xaa) { print.format("WARNING: reset_device: PS/2 device on {} replied {} for self test\n", .{port, self_test_res}); } // Get id byte sequence const timeout: u16 = 2048; if (read_data_with_timeout(timeout)) |id0| { if (read_data_with_timeout(timeout)) |id1| { print.format(" - PS/2 {}: Unknown device {:x}, {:x}\n", .{port, id0, id1}); device.* = DeviceKind.Unknown; } else if (id0 == 0) { print.format(" - PS/2 {}: Mouse\n", .{port}); device.* = DeviceKind.Mouse; } else { print.format(" - PS/2 {}: Unknown device {:x}\n", .{port, id0}); device.* = DeviceKind.Unknown; } } else { print.format(" - PS/2 {}: Keyboard\n", .{port}); device.* = DeviceKind.Keyboard; } // TODO: Zig bug, can't combine this into a single "and" expr, LLVM crashes if (build_options.mouse) { if (device.* == DeviceKind.Mouse) { const mouse_status = try get_mouse_status(port); // print.format("MouseStatus: {}\n", .{mouse_status}); if (!mouse_status.data_enabled) { try mouse_data_enabled(port, true); // const mouse_status2 = try get_mouse_status(port); // print.format("MouseStatus: {}\n", .{mouse_status2}); } } } } fn reset() Error!void { // Disable ports and flush output buffer enable_port(.Port1, false); enable_port(.Port2, false); _ = putil.in8(data_port); var config = read_config(); config.port1_interrupt_enabled = false; config.port2_interrupt_enabled = false; write_config(config); // Controller self-test const controller_status = command(0xaa, null, .HasRes).?; if (controller_status != 0x55) { print.format("ERROR: PS/2 controller self-test status {}\n", .{controller_status}); return Error.Ps2ResetFailed; } // Test ports const port1_status = command(0xab, null, .HasRes).?; if (port1_status != 0x00) { print.format("ERROR: PS/2 port 1 test status {}\n", .{port1_status}); return Error.Ps2ResetFailed; } const port2_status = command(0xa9, null, .HasRes).?; if (port2_status != 0x00) { print.format("ERROR: PS/2 port 2 test status {}\n", .{port2_status}); return Error.Ps2ResetFailed; } // Enable ports enable_port(.Port1, true); enable_port(.Port2, true); // Set controller config config.port1_interrupt_enabled = true; config.port2_interrupt_enabled = true; // Have controller translate to scan code set 1 for us. That's // what's currently in ps2_scan_codes.zig. config.port1_translation = true; write_config(config); // Reset/detect devices on ports reset_device(.Port1, &port1_device) catch |e| { print.format("ERROR: PS/2 port 1 init error: {}\n", .{@errorName(e)}); port1_device = null; }; reset_device(.Port2, &port2_device) catch |e| { print.format("ERROR: PS/2 port 2 init error: {}\n", .{@errorName(e)}); port2_device = null; }; } const MouseData = packed struct { lmb_pressed: bool, rmb_pressed: bool, mmb_pressed: bool, one: u1 = 1, x_sign: u1, y_sign: u1, x_overflow: u1, y_overflow: u1, x: u8, y: u8, fn get_value(sign: u1, value: u8) i9 { return @bitCast(i9, (@intCast(u9, sign) << 8) | value); } fn to_mouse_event(self: *const MouseData) MouseEvent { return .{ .rmb_pressed = self.rmb_pressed, .mmb_pressed = self.mmb_pressed, .lmb_pressed = self.lmb_pressed, .delta = .{ .x = get_value(self.x_sign, self.x), .y = get_value(self.y_sign, self.y), }, }; } }; fn get_mouse_data() Error!MouseData { return read_data_as(MouseData, 128); } }; /// Number of bytes into the current pattern. var byte_count: u8 = 0; const Pattern = enum { TwoBytePrintScreen, PrintScreenPressed, PrintScreenReleased, Pause, }; /// Current multibyte patterns that are possible. var pattern: Pattern = undefined; fn keyboard_event_occurred(interrupt_number: u32, interrupt_stack: *const interrupts.Stack) void { _ = interrupt_number; _ = interrupt_stack; if (!keyboard_initialized) return; var event: ?KeyboardEvent = null; const byte = controller.read_data(); // print.format("[{:x}]", .{byte}); var reset = false; switch (byte_count) { 0 => switch (byte) { // Towards Two Bytes or PrintScreen 0xe0 => pattern = .TwoBytePrintScreen, // Towards Pause 0xe1 => pattern = .Pause, // Reached One Byte else => { const entry = scan_codes.one_byte[byte]; if (entry.key) |key| { event = KeyboardEvent.new( key, entry.shifted_key, entry.kind.?, &keyboard_modifiers); } reset = true; }, }, 1 => switch (pattern) { .TwoBytePrintScreen => switch (byte) { // Towards PrintScreen Pressed 0x2a => pattern = .PrintScreenPressed, // Towards PrintScreen Released 0xb7 => pattern = .PrintScreenReleased, // Reached Two Bytes else => { const entry = scan_codes.two_byte[byte]; if (entry.key) |key| { event = KeyboardEvent.new( key, entry.shifted_key, entry.kind.?, &keyboard_modifiers); } reset = true; }, }, // Towards Pause .Pause => reset = byte != 0x1d, else => reset = true, }, 2 => switch (pattern) { // Towards PrintScreen Pressed and Released .PrintScreenPressed, .PrintScreenReleased => reset = byte != 0xe0, // Towards Pause .Pause => reset = byte != 0x45, else => reset = true, }, 3 => switch (pattern) { .PrintScreenPressed => { if (byte == 0x37) { // Reached PrintScreen Pressed event = KeyboardEvent.new( .Key_PrintScreen, null, .Pressed, &keyboard_modifiers); } reset = true; }, .PrintScreenReleased => { if (byte == 0xaa) { // Reached PrintScreen Released event = KeyboardEvent.new( .Key_PrintScreen, null, .Released, &keyboard_modifiers); } reset = true; }, // Towards Pause .Pause => reset = byte != 0xe1, else => reset = true, }, 4 => switch (pattern) { // Towards Pause .Pause => reset = byte != 0x9d, else => reset = true, }, 5 => switch (pattern) { // Towards Pause .Pause => { if (byte == 0xc5) { // Reached Pause event = KeyboardEvent.new(.Key_Pause, null, .Hit, &keyboard_modifiers); } reset = true; }, else => reset = true, }, else => reset = true, } if (reset) { byte_count = 0; } else { byte_count += 1; } if (event != null) { const e = &event.?; keyboard_modifiers.update(e); // print.format("<{}: {}>", .{@tagName(e.key), @tagName(e.kind)}); if (e.kind == .Pressed) { if (key_to_char(e.key)) |c| { e.char = c; if (keyboard_modifiers.alt_is_pressed() and keyboard_modifiers.control_is_pressed() and c == 'D') { kernel.quick_debug(); return; } } } keyboard_buffer.push(e.*); kernel.threading_mgr.keyboard_event_occurred(); } } pub fn get_key() ?KeyboardEvent { putil.disable_interrupts(); defer putil.enable_interrupts(); return keyboard_buffer.pop(); } fn mouse_event_occurred(interrupt_number: u32, interrupt_stack: *const interrupts.Stack) void { _ = interrupt_number; _ = interrupt_stack; if (!mouse_initialized) return; const data = controller.get_mouse_data() catch return; const event = data.to_mouse_event(); //print.format("mouse: {}\n", .{event}); mouse_buffer.push(event); } pub fn get_mouse_event() ?MouseEvent { putil.disable_interrupts(); defer putil.enable_interrupts(); return mouse_buffer.pop(); } pub fn init() !void { try controller.reset(); // Set up IRQs if (controller.port1_is_keyboard()) { interrupts.IrqInterruptHandler(1, keyboard_event_occurred).set( "IRQ1: PS/2 Keyboard", segments.kernel_code_selector, interrupts.kernel_flags); } if (controller.port2_is_mouse()) { interrupts.IrqInterruptHandler(12, mouse_event_occurred).set( "IRQ12: PS/2 Mouse", segments.kernel_code_selector, interrupts.kernel_flags); } interrupts.load(); if (controller.port1_is_keyboard()) { interrupts.pic.allow_irq(1, true); } if (controller.port2_is_mouse()) { interrupts.pic.allow_irq(12, true); } keyboard_initialized = controller.port1_is_keyboard(); mouse_initialized = controller.port2_is_mouse(); } pub fn anykey() void { if (build_options.wait_for_anykey) { while (true) { if (get_key()) |key| { if (key.kind == .Released) { break; } } } } }
0
repos/georgios/kernel
repos/georgios/kernel/platform/platform.zig
// Platform Initialization and Public Interface const std = @import("std"); const builtin = @import("builtin"); const kernel = @import("root").kernel; const io = kernel.io; const print = kernel.print; pub const serial_log = @import("serial_log.zig"); pub const cga_console = @import("cga_console.zig"); pub const segments = @import("segments.zig"); pub const interrupts = @import("interrupts.zig"); pub const multiboot = @import("multiboot.zig"); pub const pmemory = @import("memory.zig"); pub const util = @import("util.zig"); pub const pci = @import("pci.zig"); pub const ata = @import("ata.zig"); pub const acpi = @import("acpi.zig"); pub const ps2 = @import("ps2.zig"); pub const threading = @import("threading.zig"); pub const vbe = @import("vbe.zig"); pub const timing = @import("timing.zig"); pub const bios_int = @import("bios_int.zig"); pub const frame_size = pmemory.frame_size; pub const page_size = pmemory.page_size; pub const MemoryMgrImpl = pmemory.ManagerImpl; pub const enable_interrupts = util.enable_interrupts; pub const disable_interrupts = util.disable_interrupts; pub const idle = util.idle; pub const halt_forever = util.halt_forever; pub const Time = u64; pub const time = timing.rdtsc; pub const seconds_to_time = timing.seconds_to_ticks; pub const milliseconds_to_time = timing.milliseconds_to_ticks; pub fn panic(msg: []const u8, trace: ?*std.builtin.StackTrace) noreturn { _ = msg; _ = trace; asm volatile ("int $50"); unreachable; } // Kernel Boundaries ========================================================== extern var _REAL_START: u32; pub fn kernel_real_start() usize { return @ptrToInt(&_REAL_START); } extern var _REAL_END: u32; pub fn kernel_real_end() usize { return @ptrToInt(&_REAL_END); } extern var _VIRTUAL_START: u32; pub fn kernel_virtual_start() usize { return @ptrToInt(&_VIRTUAL_START); } extern var _VIRTUAL_END: u32; pub fn kernel_virtual_end() usize { return @ptrToInt(&_VIRTUAL_END); } extern var _KERNEL_SIZE: u32; pub fn kernel_size() usize { return @ptrToInt(&_KERNEL_SIZE); } extern var _VIRTUAL_OFFSET: u32; pub fn kernel_to_real(addr: usize) usize { return addr - @ptrToInt(&_VIRTUAL_OFFSET); } pub fn kernel_to_virtual(addr: usize) usize { return addr + @ptrToInt(&_VIRTUAL_OFFSET); } pub fn kernel_range_real_start_available() usize { return @intCast(usize, multiboot.kernel_range_start_available); } pub fn kernel_range_virtual_start_available() usize { return kernel_to_virtual( @intCast(usize, multiboot.kernel_range_start_available)); } // Console Implementation ===================================================== fn console_write(file: *io.File, from: []const u8) io.FileError!usize { _ = file; for (from) |value| { serial_log.print_char(value); kernel.console.print(value); } return from.len; } fn console_read(file: *io.File, to: []u8) io.FileError!usize { _ = file; _ = to; return 0; } // Boot Stack ================================================================= extern var stack: [util.Ki(16)]u8 align(16) linksection(".bss"); pub fn print_stack_left() void { print.format("stack left: {}\n", asm volatile ("mov %%esp, %[x]" : [x] "=r" (-> usize)) - @ptrToInt(&stack)); } // Platform Initialization ==================================================== pub fn init() !void { // Finish Setup of Console Logging serial_log.init(); cga_console.init(); kernel.console = &cga_console.console; kernel.console_file.write_impl = console_write; kernel.console_file.read_impl = console_read; // Setup Basic CPU Utilities segments.init(); interrupts.init(); timing.estimate_cpu_speed(); // List Multiboot Tags if (print.debug_print) { _ = try multiboot.find_tag(.End); } // Setup Global Memory Management var real_memory_map = kernel.memory.RealMemoryMap{}; const mmap_tag = try multiboot.find_tag(.Mmap); pmemory.process_multiboot2_mmap(&real_memory_map, &mmap_tag); try kernel.memory_mgr.init(&real_memory_map); // Threading try kernel.threading_mgr.init(); // Setup Devices kernel.device_mgr.init(kernel.alloc.std_allocator()); try ps2.init(); pci.find_pci_devices(); bios_int.init(); vbe.init(); try acpi.init(); // Start Ticking timing.set_pit_freq(.Irq0, 100); interrupts.pic.allow_irq(0, true); } pub fn shutdown() void { acpi.power_off(); }
0
repos/georgios/kernel
repos/georgios/kernel/platform/threading.zig
const std = @import("std"); const georgios = @import("georgios"); const utils = @import("utils"); const kernel = @import("root").kernel; const kthreading = kernel.threading; const Thread = kthreading.Thread; const Process = kthreading.Process; const kmemory = kernel.memory; const Range = kmemory.Range; const print = kernel.print; const platform = @import("platform.zig"); const pmemory = @import("memory.zig"); const interrupts = @import("interrupts.zig"); const InterruptStack = interrupts.InterruptStack; const segments = @import("segments.zig"); pub const Error = georgios.threading.Error; const pmem = &kernel.memory_mgr.impl; fn v86(ss: u32, esp: u32, cs: u32, eip: u32) noreturn { asm volatile ("push %[ss]" :: [ss] "{ax}" (ss)); asm volatile ("push %[esp]" :: [esp] "{ax}" (esp)); asm volatile ( \\pushf \\orl $0x20000, (%%esp) ); asm volatile ("push %[cs]" :: [cs] "{ax}" (cs)); asm volatile ("push %[eip]" :: [eip] "{ax}" (eip)); asm volatile ("iret"); unreachable; // asm volatile ( // \\push // :: // [old_context_ptr] "{ax}" (@ptrToInt(&last.impl.context)), // [new_context] "{bx}" (self.context)); // ); } fn usermode(ip: u32, sp: u32, v8086: bool) noreturn { asm volatile ( \\// Load User Data Selector into Data Segment Registers \\movw %[user_data_selector], %%ds \\movw %[user_data_selector], %%es \\movw %[user_data_selector], %%fs \\movw %[user_data_selector], %%gs \\ \\// Push arguments for iret \\pushl %[user_data_selector] // ss \\pushl %[sp] // sp \\// Push Flags with Interrupts Enabled \\pushf \\movl (%%esp), %%edx \\orl $0x0200, %%edx \\cmpl $0, %[v8086] \\jz no_v8086 \\orl $0x20000, %%edx \\no_v8086: \\movl %%edx, (%%esp) \\pushl %[user_code_selector] \\pushl %[ip] // ip \\ \\.global usermode_iret // Breakpoint for Debugging \\usermode_iret: \\iret // jump to ip as ring 3 : : [user_code_selector] "{cx}" (@as(u32, segments.user_code_selector)), [user_data_selector] "{dx}" (@as(u32, segments.user_data_selector)), [sp] "{bx}" (sp), [ip] "{ax}" (ip), [v8086] "{si}" (@as(u32, @boolToInt(v8086))), ); unreachable; } pub const ThreadImpl = struct { thread: *Thread, context: usize, context_is_setup: bool, usermode_stack: Range, usermode_stack_ptr: usize, kernelmode_stack: Range, v8086: bool, pub fn init(self: *ThreadImpl, thread: *Thread, boot_thread: bool) Error!void { self.thread = thread; self.context_is_setup = boot_thread; if (!boot_thread) { const stack_size = utils.Ki(8); const guard_size = utils.Ki(4); self.kernelmode_stack = try kernel.memory_mgr.big_alloc.alloc_range(guard_size + stack_size); try kernel.memory_mgr.impl.make_guard_page(null, self.kernelmode_stack.start, true); self.kernelmode_stack.start += guard_size; self.kernelmode_stack.size -= guard_size; // print.format("3/4 point on stack: .{:a}\n", // .{self.kernelmode_stack.start + stack_size / 4}); } self.v8086 = if (thread.process) |process| process.impl.v8086 else false; } fn push_to_context(self: *ThreadImpl, value: anytype) void { const Type = @TypeOf(value); const size = @sizeOf(Type); self.context -= size; _ = utils.memory_copy_truncate( @intToPtr([*]u8, self.context)[0..size], std.mem.asBytes(&value)); } fn pop_from_context(self: *ThreadImpl, comptime Type: type) Type { const size = @sizeOf(Type); var value: Type = undefined; _ = utils.memory_copy_truncate( std.mem.asBytes(&value), @intToPtr([*]const u8, self.context)[0..size]); self.context += size; return value; } /// Initial Kernel Mode Stack/Context in switch_to() for New Threads const SwitchToFrame = packed struct { // pusha edi: u32, esi: u32, ebp: u32, esp: u32, ebx: u32, edx: u32, ecx: u32, eax: u32, // pushf eflags: u32, // switch_to() Base Frame func_eax: u32, func_ebx: u32, func_ebp: u32, func_return: u32, // run() Frame run_return: u32, run_arg: u32, }; /// Setup Initial Kernel Mode Stack/Context in switch_to() for New Threads fn setup_context(self: *ThreadImpl) void { // Setup Usermode Stack if (!self.thread.kernel_mode) { if (self.thread.process) |process| { process.impl.setup(self); } } // Setup Initial Kernel Mode Stack/Context const sp = self.kernelmode_stack.end() - 1; self.context = sp; var frame = std.mem.zeroes(SwitchToFrame); frame.esp = sp; // TODO: Zig Bug? @ptrToInt(&run) results in weird address frame.func_return = @ptrToInt(run); frame.func_ebp = sp; frame.run_arg = @ptrToInt(self); self.push_to_context(frame); } pub fn before_switch(self: *ThreadImpl) void { if (!self.context_is_setup) { self.setup_context(); self.context_is_setup = true; } if (self.thread.process) |process| { process.impl.switch_to() catch @panic("before_switch: ProcessImpl.switch_to"); } if (!self.thread.kernel_mode) { platform.segments.set_interrupt_handler_stack(self.kernelmode_stack.end() - 1); } kernel.threading_mgr.current_process = self.thread.process; kernel.threading_mgr.current_thread = self.thread; } pub fn switch_to(self: *ThreadImpl) callconv(.C) void { // WARNING: A FRAME FOR THIS FUNCTION NEEDS TO BE SETUP IN setup_context! const last = kernel.threading_mgr.current_thread.?; self.before_switch(); asm volatile ( \\pushf \\pusha \\movl %%esp, (%[old_context_ptr]) \\movl %[new_context], %%esp \\popa \\popf : : [old_context_ptr] "{ax}" (@ptrToInt(&last.impl.context)), [new_context] "{bx}" (self.context)); after_switch(); } pub fn after_switch() void { if (interrupts.in_tick) { if (kthreading.debug) print.char('#'); interrupts.pic.end_of_interrupt(0, false); interrupts.in_tick = false; platform.enable_interrupts(); } } pub fn run_impl(self: *ThreadImpl) void { self.before_switch(); if (self.thread.kernel_mode) { platform.enable_interrupts(); asm volatile ("call *%[entry]" : : [entry] "{ax}" (self.thread.entry)); kernel.threading_mgr.remove_current_thread(); } else { usermode(self.thread.entry, self.usermode_stack_ptr, self.v8086); } } // WARNING: THIS FUNCTION'S ARGUMENTS NEED TO BE SETUP IN setup_context! pub fn run(self: *ThreadImpl) callconv(.C) void { if (kthreading.debug) print.format("Thread {} has Started\n", .{self.thread.id}); self.run_impl(); } }; pub const ProcessImpl = struct { // TODO: Growable stack pub const usermode_stack_size = platform.frame_size * 10; const main_bios_memory = Range{.start = 0x00080000, .size = 0x00080000}; process: *Process = undefined, page_directory: []u32 = undefined, v8086: bool = false, pub fn init(self: *ProcessImpl, process: *Process) Error!void { self.process = process; self.page_directory = try pmem.new_page_directory(); } // TODO: Cleanup fn copy_string_to_user_stack(self: *ProcessImpl, thread: *ThreadImpl, s: []const u8) []const u8 { thread.usermode_stack_ptr -= s.len; const usermode_slice = @intToPtr([*]const u8, thread.usermode_stack_ptr)[0..s.len]; pmem.page_directory_memory_copy( self.page_directory, thread.usermode_stack_ptr, s) catch unreachable; return usermode_slice; } pub fn setup(self: *ProcessImpl, thread: *ThreadImpl) void { const main_thread = &self.process.main_thread == thread.thread; if (!main_thread) { // TODO: This code won't work if we want to call multiple threads per process. // We need to allocate a different stack for each thread. @panic("TODO: Support multiple threads per process"); } const stack_bottom: usize = if (self.v8086) main_bios_memory.start else platform.kernel_to_virtual(0); thread.usermode_stack = .{ .start = stack_bottom - usermode_stack_size, .size = usermode_stack_size}; pmem.mark_virtual_memory_present( self.page_directory, thread.usermode_stack, true) catch @panic("setup_context: mark_virtual_memory_present"); thread.usermode_stack_ptr = thread.usermode_stack.end(); if (self.v8086) { // Map Real-Mode Interrupt Vector Table (IVT) and BIOS Data Area (BDA) pmem.map(.{.start = 0, .size = platform.frame_size}, 0, true) catch @panic("ProcessImpl.setup: v8086 map IVT and BDA"); // Map the Main BIOS Region of Memory pmem.map(main_bios_memory, main_bios_memory.start, true) catch @panic("ProcessImpl.setup: v8086 map main bios memory"); } else if (main_thread) { thread.usermode_stack_ptr -= @sizeOf(u32); const stack_end: u32 = 0xc000dead; pmem.page_directory_memory_copy( self.page_directory, thread.usermode_stack_ptr, utils.to_const_bytes(&stack_end)) catch unreachable; var info = self.process.info.?; // ProcessInfo path and name const name = if (info.name.len > 0) info.name else info.path; info.path = self.copy_string_to_user_stack(thread, info.path); info.name = self.copy_string_to_user_stack(thread, name); // ProcessInfo.args thread.usermode_stack_ptr = utils.align_down(thread.usermode_stack_ptr - @sizeOf([]const u8) * info.args.len, @alignOf([]const u8)); const args_array = thread.usermode_stack_ptr; var arg_slice_ptr = args_array; for (info.args) |arg| { const arg_slice = self.copy_string_to_user_stack(thread, arg); pmem.page_directory_memory_copy( self.page_directory, arg_slice_ptr, utils.to_const_bytes(&arg_slice)) catch unreachable; arg_slice_ptr += @sizeOf([]const u8); } info.args = @intToPtr([*]const []const u8, args_array)[0..info.args.len]; // ProcessInfo thread.usermode_stack_ptr -= utils.align_up( @sizeOf(georgios.ProcessInfo), @alignOf(georgios.ProcessInfo)); thread.usermode_stack_ptr = utils.align_down(thread.usermode_stack_ptr, @alignOf(usize)); pmem.page_directory_memory_copy( self.page_directory, thread.usermode_stack_ptr, utils.to_const_bytes(&info)) catch unreachable; } } pub fn switch_to(self: *ProcessImpl) Error!void { var current_page_directory: ?[]u32 = null; if (kernel.threading_mgr.current_process) |current| { if (current == self.process) { return; } else { current_page_directory = current.impl.page_directory; } } try pmemory.load_page_directory(self.page_directory, current_page_directory); // TODO: Try to undo the effects if there is an error. } pub fn start(self: *ProcessImpl) Error!void { self.process.main_thread.impl.switch_to(); } pub fn address_space_copy(self: *ProcessImpl, address: usize, data: []const u8) kmemory.AllocError!void { try pmem.page_directory_memory_copy( self.page_directory, address, data); } pub fn address_space_set(self: *ProcessImpl, address: usize, byte: u8, len: usize) kmemory.AllocError!void { try pmem.page_directory_memory_set( self.page_directory, address, byte, len); } }; pub fn new_v8086_process() !*Process { const p = try kernel.threading_mgr.new_process_i(); p.info = null; p.impl.v8086 = true; p.entry = platform.frame_size; try p.init(null); return p; } // const process = try platform.impl.threading.new_v8086_process(); // try process.address_space_copy(process.entry, // @intToPtr([*]const u8, @ptrToInt(exc))[0..@ptrToInt(&exc_end) - @ptrToInt(exc)]); // try threading_mgr.start_process(process); // threading_mgr.wait_for_process(process.id);
0
repos/georgios/kernel
repos/georgios/kernel/platform/multiboot.zig
const builtin = @import("builtin"); const utils = @import("utils"); const platform = @import("platform.zig"); const vbe = @import("vbe.zig"); const kernel = @import("root").kernel; const print = kernel.print; const Range = kernel.memory.Range; export var multiboot_info: []u32 = undefined; const Error = error { NullMultibootInfoPointer, TagNotFound, }; const TagKind = enum (u32) { End = 0, CmdLine = 1, BootLoaderName = 2, Module = 3, BasicMemInfo = 4, BootDev = 5, Mmap = 6, Vbe = 7, Framebuffer = 8, ElfSections = 9, Apm = 10, Efi32 = 11, Efi64 = 12, Smbios = 13, AcpiOld = 14, AcpiNew = 15, Network = 16, EfiMmap = 17, EfiBs = 18, Efi32Ih = 19, Efi64Ih = 20, LoadBaseAddr = 21, pub fn from_u32(value: u32) ?TagKind { return utils.int_to_enum(TagKind, value); } pub fn to_string(self: TagKind) []const u8 { return switch (self) { .End => "End", .CmdLine => "Boot Command", .BootLoaderName => "Boot Loader Name", .Module => "Modules", .BasicMemInfo => "Basic Memory Info", .BootDev => "BIOS Boot Device", .Mmap => "Memory Map", .Vbe => "VBE Info", .Framebuffer => "Framebuffer Info", .ElfSections => "ELF Symbols", .Apm => "APM Table", .Efi32 => "EFI 32-bit Table Pointer", .Efi64 => "EFI 64-bit Table Pointer", .Smbios => "SMBIOS Tables", .AcpiOld => "ACPI v1 RSDP", .AcpiNew => "ACPI v2 RSDP", .Network => "Networking Info", .EfiMmap => "EFI Memory Map", .EfiBs => "EFI Boot Services Not Terminated", .Efi32Ih => "EFI 32-bit Image Handle Pointer", .Efi64Ih => "EFI 64-bit Image Handle Pointer", .LoadBaseAddr => "Image Load Base Physical Address", }; } }; /// Process part of the Multiboot information given by `find`. If `find` wasn't /// found, returns `Error.TagNotFound`. If `find` is `End`, then just list /// what's in the Multiboot header. pub fn find_tag(find: TagKind) Error!Range { var i = @intCast(usize, @ptrToInt(multiboot_info.ptr)); if (i == 0) { return Error.NullMultibootInfoPointer; } const list = find == .End; if (list) { print.debug_string(" - Multiboot Tags Available:\n"); } var running = true; var tag_count: usize = 0; if (list) { const size = @intToPtr(*u32, i).*; print.debug_format( \\ - Total Size: {} B ({} KiB) \\ - Tags: \\ , .{size, size >> 10}); } i += 8; // Move to first tag while (running) { const kind_raw = @intToPtr(*u32, i).*; const size = @intToPtr(*u32, i + 4).*; const kind_maybe = TagKind.from_u32(kind_raw); if (list) { print.debug_format(" - {}\n", .{ if (kind_maybe) |kind| kind.to_string() else "Unkown"}); } if (kind_maybe) |kind| { if (kind == .End) { running = false; } if (find == kind) { return Range{.start = i, .size = size}; } } // Move to next tag i += utils.align_up(size, 8); tag_count += 1; } if (list) { print.debug_format(" - That was {} tags\n", .{tag_count}); return Range{.start = i, .size = 0}; } return Error.TagNotFound; } const VbeInfo = packed struct { kind: TagKind, size: u32, mode: u16, interface_seg: u16, interface_off: u16, interface_len: u16, control_info: [512]u8, mode_info: [256]u8, }; pub fn get_vbe_info() ?*VbeInfo { const range = find_tag(TagKind.Vbe) catch { return null; }; return range.to_ptr(*VbeInfo); }
0
repos/georgios/kernel
repos/georgios/kernel/platform/acpi.zig
// Advanced Configuration and Power Interface (ACPI) // - https://en.wikipedia.org/wiki/Advanced_Configuration_and_Power_Interface // - https://wiki.osdev.org/ACPI // // ACPI Component Architecture (ACPICA) // - https://www.acpica.org/ // - https://github.com/acpica/acpica // - https://wiki.osdev.org/ACPICA const utils = @import("utils"); const kernel = @import("root").kernel; const print = kernel.print; const pmemory = @import("memory.zig"); const util = @import("util.zig"); const interrupts = @import("interrupts.zig"); const segments = @import("segments.zig"); const timing = @import("timing.zig"); const pci = @import("pci.zig"); const acpica = @cImport({ @cInclude("georgios_acpica_wrapper.h"); }); var page_directory: [1024]u32 = undefined; var prev_page_directory: [1024]u32 = undefined; fn check_status(comptime what: []const u8, status: acpica.Status) void { if (status != acpica.Ok) { print.format(what ++ " returned {:x}\n", .{status}); @panic(what ++ " failed"); } } pub const TableHeader = packed struct { signature: [4]u8, size: u32, revision: u8, checksum: u8, // TODO: Zig Bug, stage1 panics on [6]u8 // oem_id: [6]u8, oem_id1: [4]u8, oem_id2: [2]u8, oem_table_id: [8]u8, oem_revision: u32, creator_id: [4]u8, creator_revision: u32, }; pub const Address = packed struct { pub const Kind = enum(u8) { Memory = 0, Io = 1, _, }; kind: Kind, register_width: u8, register_offset: u8, reserved: u8, address: u64, }; fn device_callback(obj: acpica.ACPI_HANDLE, level: acpica.Uint32, context: ?*anyopaque, return_value: [*c]?*anyopaque) callconv(.C) acpica.Status { _ = level; _ = context; _ = return_value; var devinfo: [*c]acpica.ACPI_DEVICE_INFO = undefined; check_status("acpi.device_callback: AcpiGetObjectInfo", acpica.AcpiGetObjectInfo(obj, &devinfo)); const name = @ptrCast(*[4]u8, &devinfo.*.Name); print.format(" - {}\n", .{name}); if (utils.memory_compare(name, "HPET")) { print.string(" - HPET Found\n"); } acpica.AcpiOsFree(devinfo); return acpica.Ok; } pub fn init() !void { print.string(" - Initializing ACPI Subsystem\n"); _ = utils.memory_set(utils.to_bytes(page_directory[0..]), 0); try pmemory.load_page_directory(&page_directory, &prev_page_directory); check_status("acpi.init: AcpiInitializeSubsystem", acpica.AcpiInitializeSubsystem()); check_status("acpi.init: AcpiInitializeTables", acpica.AcpiInitializeTables(null, 16, 0)); check_status("acpi.init: AcpiLoadTables", acpica.AcpiLoadTables()); // check_status("acpi.init: AcpiEnableSubsystem", // acpica.AcpiEnableSubsystem(acpica.ACPI_FULL_INITIALIZATION)); // check_status("acpi.init: AcpiInitializeObjects", // acpica.AcpiInitializeObjects(acpica.ACPI_FULL_INITIALIZATION)); // var devcb_rv: ?*anyopaque = null; // check_status("acpi.init: AcpiGetDevices", acpica.AcpiGetDevices( // null, device_callback, null, &devcb_rv)); var table: [*c]acpica.ACPI_TABLE_HEADER = undefined; var hpet: [4]u8 = "HPET".*; check_status("acpi.init: AcpiGetTable", acpica.AcpiGetTable(@ptrCast([*c]u8, &hpet), 1, @ptrCast([*c][*c]acpica.ACPI_TABLE_HEADER, &table))); print.format("{}\n", .{@ptrCast(*timing.HpetTable, table).*}); try pmemory.load_page_directory(&prev_page_directory, &page_directory); } pub fn power_off() void { const power_off_state: u8 = 5; print.string("Powering Off Now\n"); // interrupts.pic.allow_irq(0, false); util.disable_interrupts(); pmemory.load_page_directory(&page_directory, null) catch @panic("acpi.power_off: load_page_directory failed"); check_status("acpi.power_off: AcpiEnterSleepStatePrep", acpica.AcpiEnterSleepStatePrep(power_off_state)); check_status("acpi.power_off: AcpiEnterSleepState", acpica.AcpiEnterSleepState(power_off_state)); @panic("acpi.power_off: reached end"); } // OS Abstraction Layer ====================================================== export fn AcpiOsInitialize() acpica.Status { return acpica.Ok; } export fn AcpiOsTerminate() acpica.Status { return acpica.Ok; } export fn AcpiOsGetRootPointer() acpica.PhysicalAddress { var p: acpica.PhysicalAddress = 0; _ = acpica.AcpiFindRootPointer(@ptrCast([*c]acpica.PhysicalAddress, &p)); return p; } export fn AcpiOsAllocate(size: acpica.Size) ?*anyopaque { const a = kernel.alloc.alloc_array(u8, size) catch return null; return @ptrCast(*anyopaque, a.ptr); } export fn AcpiOsFree(ptr: ?*anyopaque) void { if (ptr) |p| { kernel.alloc.free_array(utils.empty_slice(u8, p)) catch {}; } } const Sem = kernel.sync.Semaphore(acpica.Uint32); export fn AcpiOsCreateSemaphore( max_units: acpica.Uint32, initial_units: acpica.Uint32, semaphore: **Sem) acpica.Status { _ = max_units; const sem = kernel.alloc.alloc(Sem) catch return acpica.NoMemory; sem.* = .{.value = initial_units}; sem.init(); semaphore.* = sem; return acpica.Ok; } export fn AcpiOsWaitSemaphore( semaphore: *Sem, units: acpica.Uint32, timeout: acpica.Uint16) acpica.Status { // TODO: Timeout in milliseconds _ = timeout; var got: acpica.Uint32 = 0; while (got < units) { semaphore.wait() catch continue; got += 1; } return acpica.Ok; } export fn AcpiOsSignalSemaphore(semaphore: *Sem, units: acpica.Uint32) acpica.Status { var left: acpica.Uint32 = units; while (left > 0) { semaphore.signal() catch continue; left -= 1; } return acpica.Ok; } export fn AcpiOsDeleteSemaphore(semaphore: *Sem) acpica.Status { kernel.alloc.free(semaphore) catch return acpica.BadParameter; return acpica.Ok; } const Lock = kernel.sync.Lock; export fn AcpiOsCreateLock(lock: **Lock) acpica.Status { const l = kernel.alloc.alloc(Lock) catch return acpica.NoMemory; l.* = .{}; lock.* = l; return acpica.Ok; } export fn AcpiOsAcquireLock(lock: *Lock) acpica.ACPI_CPU_FLAGS { lock.spin_lock(); return 0; } export fn AcpiOsReleaseLock(lock: *Lock, flags: acpica.ACPI_CPU_FLAGS) void { _ = flags; lock.unlock(); } export fn AcpiOsDeleteLock(lock: *Lock) acpica.Status { kernel.alloc.free(lock) catch return acpica.BadParameter; return acpica.Ok; } export fn AcpiOsGetThreadId() acpica.Uint64 { const t = kernel.threading_mgr.current_thread orelse &kernel.threading_mgr.boot_thread; return t.id; } export fn AcpiOsPredefinedOverride(predefined_object: *const acpica.ACPI_PREDEFINED_NAMES, new_value: **allowzero anyopaque) acpica.Status { _ = predefined_object; new_value.* = @intToPtr(*allowzero anyopaque, 0); return acpica.Ok; } export fn AcpiOsTableOverride(existing: [*c]acpica.ACPI_TABLE_HEADER, new: [*c][*c]acpica.ACPI_TABLE_HEADER) acpica.Status { _ = existing; new.* = null; return acpica.Ok; } export fn AcpiOsPhysicalTableOverride(existing: [*c]acpica.ACPI_TABLE_HEADER, new_addr: [*c]acpica.ACPI_PHYSICAL_ADDRESS, new_len: [*c]acpica.Uint32) acpica.Status { _ = existing; _ = new_len; new_addr.* = 0; return acpica.Ok; } export fn AcpiOsMapMemory( address: acpica.PhysicalAddress, size: acpica.Size) *allowzero anyopaque { const page = pmemory.page_size; const pmem = &kernel.memory_mgr.impl; const addr = @intCast(usize, address); const start_page = utils.align_down(addr, page); const offset = addr % page; const range = pmem.get_unused_kernel_space(size + offset) catch { print.string("AcpiOsMapMemory: get_unused_kernel_space failed\n"); return @intToPtr(*allowzero anyopaque, 0); }; pmem.map(range, start_page, false) catch { print.string("AcpiOsMapMemory: map failed\n"); return @intToPtr(*allowzero anyopaque, 0); }; return @intToPtr(*allowzero anyopaque, range.start + offset); } export fn AcpiOsUnmapMemory(address: *allowzero anyopaque, size: acpica.Size) void { // TODO _ = address; _ = size; } export fn AcpiOsReadPort(address: acpica.ACPI_IO_ADDRESS, value: [*c]acpica.Uint32, width: acpica.UINT32) acpica.Status { const port = @truncate(u16, address); value.* = switch (width) { 8 => util.in8(port), 16 => util.in16(port), 32 => util.in32(port), else => { print.format("AcpiOsReadPort: width is {}\n", .{width}); return acpica.AE_ERROR; }, }; return acpica.Ok; } export fn AcpiOsWritePort(address: acpica.ACPI_IO_ADDRESS, value: acpica.Uint32, width: acpica.Uint32) acpica.Status { const port = @truncate(u16, address); switch (width) { 8 => util.out8(port, @truncate(u8, value)), 16 => util.out16(port, @truncate(u16, value)), 32 => util.out32(port, value), else => { print.format("AcpiOsWritePort: width is {}\n", .{width}); return acpica.AE_ERROR; }, } return acpica.Ok; } fn convert_pci_loc(pci_loc: [*c]acpica.ACPI_PCI_ID) pci.Location { // TODO ACPI_PCI_ID has a UINT16 Segment field. This might be for PCIe? return .{ .bus = @intCast(pci.Bus, pci_loc.*.Bus), .device = @intCast(pci.Device, pci_loc.*.Device), .function = @intCast(pci.Function, pci_loc.*.Function), }; } export fn AcpiOsReadPciConfiguration(pci_loc: [*c]acpica.ACPI_PCI_ID, offset: acpica.Uint32, value: [*c]acpica.Uint64, width: acpica.Uint32) acpica.Status { // print.format("AcpiOsReadPciConfiguration: {}\n", .{pci_loc}); const off = @intCast(pci.Offset, offset); const loc = convert_pci_loc(pci_loc); value.* = switch (width) { 8 => pci.read_config(u8, loc, off), 16 => pci.read_config(u16, loc, off), 32 => pci.read_config(u32, loc, off), else => { print.format("AcpiOsReadPciConfiguration: width is {}\n", .{width}); return acpica.AE_ERROR; }, }; return acpica.Ok; } export fn AcpiOsWritePciConfiguration(pci_loc: [*c]acpica.ACPI_PCI_ID, offset: acpica.Uint32, value: acpica.Uint64, width: acpica.Uint32) acpica.Status { // print.format("AcpiOsWritePciConfiguration: {}\n", .{pci_loc}); const off = @intCast(pci.Offset, offset); const loc = convert_pci_loc(pci_loc); switch (width) { 8 => pci.write_config(u8, loc, off, @truncate(u8, value)), 16 => pci.write_config(u16, loc, off, @truncate(u16, value)), 32 => pci.write_config(u32, loc, off, @truncate(u32, value)), else => { print.format("AcpiOsWritePciConfiguration: width is {}\n", .{width}); return acpica.AE_ERROR; }, } return acpica.Ok; } var interrupt_handler: acpica.ACPI_OSD_HANDLER = null; var interrupt_context: ?*anyopaque = null; pub fn interrupt(interrupt_number: u32, interrupt_stack: *const interrupts.Stack) void { _ = interrupt_number; _ = interrupt_stack; if (interrupt_handler) |handler| { _ = handler(interrupt_context); } } export fn AcpiOsInstallInterruptHandler(number: acpica.Uint32, handler: acpica.ACPI_OSD_HANDLER, context: ?*anyopaque) acpica.Status { const fixed: u32 = 9; if (number != fixed) { print.format("AcpiOsInstallInterruptHandler: unexpected IRQ {}\n", .{number}); return acpica.AE_BAD_PARAMETER; } if (interrupt_handler != null) { print.string("AcpiOsInstallInterruptHandler: already installed one\n"); return acpica.AE_ALREADY_EXISTS; } interrupt_handler = handler; interrupt_context = context; interrupts.IrqInterruptHandler(fixed, interrupt).set( "ACPI", segments.kernel_code_selector, interrupts.kernel_flags); interrupts.load(); return acpica.Ok; } export fn AcpiOsRemoveInterruptHandler(number: acpica.Uint32, routine: acpica.ACPI_OSD_HANDLER) acpica.Status { // TODO print.format("AcpiOsRemoveInterruptHandler: TODO {}\n", .{number}); _ = number; _ = routine; return acpica.Ok; } export fn AcpiOsEnterSleep( sleep_state: acpica.Uint8, reg_a: acpica.Uint32, reg_b: acpica.Uint32) acpica.Status { // TODO? _ = sleep_state; _ = reg_a; _ = reg_b; return acpica.Ok; } export fn AcpiOsGetTimer() acpica.Uint64 { return 0; // @panic("AcpiOsGetTimer called"); } export fn AcpiOsSignal(function: acpica.Uint32, info: *anyopaque) acpica.Status { _ = function; _ = info; @panic("AcpiOsSignal called"); } export fn AcpiOsExecute() acpica.Status { @panic("AcpiOsExecute called"); } export fn AcpiOsWaitEventsComplete() acpica.Status { @panic("AcpiOsWaitEventsComplete called"); } export fn AcpiOsStall() acpica.Status { @panic("AcpiOsStall called"); } export fn AcpiOsSleep() acpica.Status { @panic("AcpiOsSleep called"); } export fn AcpiOsReadMemory() acpica.Status { @panic("AcpiOsReadMemory called"); } export fn AcpiOsWriteMemory() acpica.Status { @panic("AcpiOsWriteMemory called"); } export fn AcpiOsPrintf() acpica.Status { @panic("AcpiOsPrintf called"); }
0
repos/georgios/kernel
repos/georgios/kernel/platform/serial_log.zig
const utils = @import("utils"); const util = @import("util.zig"); const out8 = util.out8; const in8 = util.in8; const com1_port: u16 = 0x3f8; pub fn init() void { out8(com1_port + 1, 0x00); // Disable all interrupts out8(com1_port + 3, 0x80); // Enable DLAB (set baud rate divisor) out8(com1_port + 0, 0x03); // Set divisor to 3 (lo byte) 38400 baud out8(com1_port + 1, 0x00); // (hi byte) out8(com1_port + 3, 0x03); // 8 bits, no parity, one stop bit out8(com1_port + 2, 0xC7); // Enable FIFO, clear them, with 14-byte threshold out8(com1_port + 4, 0x0B); // IRQs enabled, RTS/DSR set } pub fn output_char(c: u8) void { while ((in8(com1_port + 5) & 0x20) == 0) {} out8(com1_port, c); } var ansi_esc_processor = utils.AnsiEscProcessor{ .print_char = output_char, }; pub fn print_char(c: u8) void { // ansi_esc_processor.feed_char(c); output_char(c); }
0
repos/georgios/kernel/platform
repos/georgios/kernel/platform/bios_int/bios_int.c
/* * Most of the code in this file is written completely from scratch, but some * of it is based on code in https://forum.osdev.org/viewtopic.php?f=1&t=31388 * which helped me transition from using XFree86/X.org's libx86emu to using * Steffen Winterfeldt's libx86emu. */ #include <x86emu.h> #include <time.h> #include <stdlib.h> #include <sys/io.h> #include <stdio.h> #include <from_zig.h> #include <georgios_bios_int.h> #include <stdbool.h> // We could implement this roughly for x86emu using our rdtsc-based timer, but // this can be a nop because we don't ask x86emu to have a timeout. time_t time(time_t * arg) { if (arg) { *arg = 0; } return 0; } int vsnprintf( char * restrict buffer, size_t bufsz, const char * restrict format, va_list vlist) { if (bufsz == 0) return 0; size_t buffer_i = 0; int state = 0; for (size_t fmt_i = 0; format[fmt_i]; fmt_i++) { if (buffer_i == bufsz - 1) { break; } const char ch = format[fmt_i]; bool print_ch = false; switch (state) { case 0: if (ch == '%') { state = 1; } else { print_ch = true; } break; default: if (ch >= '0' && ch <= '9' || ch == '.') { // skip } else { void* value_ptr = 0; unsigned value; switch (ch) { case 'x': value = va_arg(vlist, unsigned); value_ptr = &value; break; case 's': value_ptr = va_arg(vlist, char *); break; } if (value_ptr) { size_t got; georgios_bios_int_to_string( &buffer[buffer_i], bufsz - buffer_i + 1, &got, ch, value_ptr); buffer_i += got; } state = 0; } } if (print_ch) { buffer[buffer_i] = ch; buffer_i++; } } buffer[buffer_i] = '\0'; return buffer_i; } extern void georgios_bios_int_fush_log_impl(char * buf, unsigned size); void georgios_bios_int_fush_log(x86emu_t * emu, char * buf, unsigned size) { georgios_bios_int_fush_log_impl(buf, size); } unsigned georgios_bios_int_memio(x86emu_t * emu, uint32_t addr, uint32_t * val, unsigned type) { unsigned value = 0xffffffff; uint32_t size = type & 0xff; type &= ~0xff; if (type == X86EMU_MEMIO_R || type == X86EMU_MEMIO_X) { if (size & X86EMU_MEMIO_16) { value = georgios_bios_int_rdw(addr); } else if (size & X86EMU_MEMIO_32) { value = georgios_bios_int_rdl(addr); } else { value = georgios_bios_int_rdb(addr); } *val = value; } else if (type & X86EMU_MEMIO_W) { if (size & X86EMU_MEMIO_16) { georgios_bios_int_wrw(addr, *val); } else if (size & X86EMU_MEMIO_32) { georgios_bios_int_wrl(addr, *val); } else { georgios_bios_int_wrb(addr, *val); } } else if (type & X86EMU_MEMIO_I) { if (size & X86EMU_MEMIO_16) { value = inw(addr); } else if (size & X86EMU_MEMIO_32) { value = inl(addr); } else { value = inb(addr); } *val = value; } else if (type & X86EMU_MEMIO_O) { if (size & X86EMU_MEMIO_16) { outw(addr, *val); } else if (size & X86EMU_MEMIO_32) { outl(addr, *val); } else { outb(addr, *val); } } else { georgios_bios_int_print_string("georgios_bios_int_memio invalid type is "); georgios_bios_int_print_value(type); georgios_bios_int_print_string("\n"); return 1; } return 0; } int georgios_bios_int_code_check(x86emu_t * emu) { // TODO: This shouldn't be needed, but it looks like switching the VESA // mode doesn't work properly if we run the interrupt without either this // or tracing. georgios_bios_int_wait(); return 0; } static x86emu_t * emu; static bool georgios_bios_int_trace; void georgios_bios_int_init(bool trace) { georgios_bios_int_trace = trace; const unsigned allow_all = X86EMU_PERM_R | X86EMU_PERM_W | X86EMU_PERM_X; emu = x86emu_new(allow_all, allow_all); x86emu_set_memio_handler(emu, georgios_bios_int_memio); emu->io.iopl_ok = 1; x86emu_set_log(emu, 1024, georgios_bios_int_fush_log); if (trace) { emu->log.trace = X86EMU_TRACE_DEFAULT; } } bool georgios_bios_int_run(GeorgiosBiosInt * params) { emu->x86.R_CS_BASE = emu->x86.R_DS_BASE = emu->x86.R_ES_BASE = emu->x86.R_FS_BASE = emu->x86.R_GS_BASE = emu->x86.R_SS_BASE = ~0; emu->x86.R_CS_LIMIT = emu->x86.R_DS_LIMIT = emu->x86.R_ES_LIMIT = emu->x86.R_FS_LIMIT = emu->x86.R_GS_LIMIT = emu->x86.R_SS_LIMIT = ~0; x86emu_set_seg_register(emu, emu->x86.R_CS_SEL, 0); x86emu_set_seg_register(emu, emu->x86.R_DS_SEL, 0); x86emu_set_seg_register(emu, emu->x86.R_ES_SEL, 0); x86emu_set_seg_register(emu, emu->x86.R_FS_SEL, 0); x86emu_set_seg_register(emu, emu->x86.R_GS_SEL, 0); x86emu_set_seg_register(emu, emu->x86.R_SS_SEL, 0); emu->x86.R_EAX = params->eax; emu->x86.R_EBX = params->ebx; emu->x86.R_ECX = params->ecx; emu->x86.R_EDX = params->edx; emu->x86.R_EDI = params->edi; const uint16_t ip = 0x7c00; emu->x86.R_EIP = ip; *(uint8_t*)(ip + 0) = 0xcd; // int ... *(uint8_t*)(ip + 1) = params->interrupt; // Interrupt Number *(uint8_t*)(ip + 2) = 0xf4; // hlt emu->x86.R_SP = 0xffff; /* x86emu_dump(emu, ~0); */ /* x86emu_clear_log(emu, 1); */ bool slow = params->slow && !georgios_bios_int_trace; if (slow) { x86emu_set_code_handler(emu, georgios_bios_int_code_check); } const unsigned result = x86emu_run(emu, X86EMU_RUN_LOOP); if (slow) { x86emu_set_code_handler(emu, NULL); params->slow = false; } params->eax = emu->x86.R_EAX; params->ebx = emu->x86.R_EBX; params->ecx = emu->x86.R_ECX; params->edx = emu->x86.R_EDX; if (result) { georgios_bios_int_print_string("georgios_bios_int_run: result is "); georgios_bios_int_print_value(result); georgios_bios_int_print_string("\n"); return true; } return false; } void georgios_bios_int_done() { x86emu_done(emu); }
0
repos/georgios/kernel/platform/bios_int
repos/georgios/kernel/platform/bios_int/private_include/time.h
#ifndef GEORGIOS_BIOS_INT_TIME_H #define GEORGIOS_BIOS_INT_TIME_H typedef unsigned time_t; #define time georgios_bios_int_time extern time_t time(time_t * arg); #endif
0
repos/georgios/kernel/platform/bios_int
repos/georgios/kernel/platform/bios_int/private_include/string.h
#ifndef GEORGIOS_BIOS_INT_STRING_H #define GEORGIOS_BIOS_INT_STRING_H #define strcat georgios_bios_int_strcat extern char * strcat(char * dest, const char * src); #endif
0
repos/georgios/kernel/platform/bios_int
repos/georgios/kernel/platform/bios_int/private_include/from_zig.h
#ifndef GEORGIOS_BIOS_INT_FROM_ZIG_H #define GEORGIOS_BIOS_INT_FROM_ZIG_H #include <stdint.h> #include <stddef.h> #include <stdbool.h> extern void georgios_bios_int_print_string(const char * str); extern void georgios_bios_int_print_value(uint32_t value); extern void georgios_bios_int_wait(); extern bool georgios_bios_int_to_string(char * buffer, size_t buffer_size, size_t * got, char kind, void * arg); extern uint8_t georgios_bios_int_rdb(uint32_t addr); extern uint16_t georgios_bios_int_rdw(uint32_t addr); extern uint32_t georgios_bios_int_rdl(uint32_t addr); extern void georgios_bios_int_wrb(uint32_t addr, uint8_t value); extern void georgios_bios_int_wrw(uint32_t addr, uint16_t value); extern void georgios_bios_int_wrl(uint32_t addr, uint32_t value); // Port I/O is in sys/io.h #endif
0
repos/georgios/kernel/platform/bios_int
repos/georgios/kernel/platform/bios_int/private_include/stdlib.h
#ifndef GEORGIOS_BIOS_INT_STDLIB_H #define GEORGIOS_BIOS_INT_STDLIB_H #include <stddef.h> #define malloc georgios_bios_int_malloc void * malloc(size_t size); #define calloc georgios_bios_int_calloc void * calloc(size_t num, size_t size); #define free georgios_bios_int_free void free(void * ptr); #endif
0
repos/georgios/kernel/platform/bios_int
repos/georgios/kernel/platform/bios_int/private_include/stdio.h
#ifndef GEORGIOS_BIOS_INT_STDIO_H #define GEORGIOS_BIOS_INT_STDIO_H #include "stdlib.h" #include <stdarg.h> #define vsnprintf georgios_bios_int_vsnprintf extern int vsnprintf( char * restrict buffer, size_t bufsz, const char * restrict format, va_list vlist); #endif
0
repos/georgios/kernel/platform/bios_int/private_include
repos/georgios/kernel/platform/bios_int/private_include/sys/io.h
#ifndef GEROGIOS_BIOS_INT_SYS_IO_H #define GEROGIOS_BIOS_INT_SYS_IO_H #include <stdint.h> #define inb georgios_bios_int_inb extern uint8_t inb(uint16_t port); #define inw georgios_bios_int_inw extern uint16_t inw(uint16_t port); #define inl georgios_bios_int_inl extern uint32_t inl(uint16_t port); #define outb georgios_bios_int_outb extern uint8_t outb(uint16_t port, uint8_t value); #define outw georgios_bios_int_outw extern uint16_t outw(uint16_t port, uint16_t value); #define outl georgios_bios_int_outl extern uint32_t outl(uint16_t port, uint16_t value); #endif
0
repos/georgios/kernel/platform/bios_int
repos/georgios/kernel/platform/bios_int/public_include/georgios_bios_int.h
#ifndef GEORGIOS_BIOS_INT_H #define GEORGIOS_BIOS_INT_H #include <stdbool.h> #include <stdint.h> typedef struct { uint8_t interrupt; uint32_t eax; uint32_t ebx; uint32_t ecx; uint32_t edx; uint32_t edi; bool slow; } GeorgiosBiosInt; extern void georgios_bios_int_init(bool trace); extern bool georgios_bios_int_run(GeorgiosBiosInt * params); extern void georgios_bios_int_done(); #endif
0
repos/georgios/kernel/platform
repos/georgios/kernel/platform/acpica/prepare_source.py
#!/usr/bin/env python3 import sys from pathlib import Path def log(*args, prefix_message=None, **kwargs): f = kwargs[file] if 'file' in kwargs else sys.stdout prefix = lambda what: print(what, ": ", sep='', end='', file=f) prefix(sys.argv[0]) if prefix_message is not None: prefix(prefix_message) print(*args, **kwargs) def error(*args, **kwargs): log(*args, prefix_message='ERROR', **kwargs) sys.exit(1) if len(sys.argv) != 2: error("Invalid argument count, pass the base path") prefix_path = Path(sys.argv[1]) suffix_path = Path('include') / 'platform' / 'acenv.h' src = prefix_path / 'acpica' / 'source' / suffix_path dst = prefix_path / suffix_path to_replace = '#error Unknown target environment' to_insert = '#include "acgeorgios.h"' if dst.is_file(): log(str(dst), "already exists") sys.exit(0) lines = src.read_text().split('\n') indexes = [] for i, line in enumerate(lines): if line == to_replace: indexes.append(i) log('Found', repr(to_replace), 'on line(s):', ','.join([str(i + 1) for i in indexes])) if len(indexes) != 1: error("Was expecting just one line!") lines[indexes[0]] = to_insert dst.write_text('\n'.join(lines))
0
repos/georgios/kernel/platform/acpica
repos/georgios/kernel/platform/acpica/include/acpiosxf.h
#include "platform/acenv.h" #include_next <acpiosxf.h>
0
repos/georgios/kernel/platform/acpica
repos/georgios/kernel/platform/acpica/include/georgios_acpica_wrapper.h
#ifndef GEORGIOS_ACPICA_WRAPPER_HEADER #define GEORGIOS_ACPICA_WRAPPER_HEADER #include <acpi.h> typedef UINT8 Uint8; typedef UINT16 Uint16; typedef UINT32 Uint32; typedef UINT64 Uint64; typedef ACPI_STATUS Status; const Status Ok = AE_OK; const Status Error = AE_ERROR; const Status NoMemory = AE_NO_MEMORY; const Status BadParameter = AE_BAD_PARAMETER; typedef ACPI_SIZE Size; typedef ACPI_PHYSICAL_ADDRESS PhysicalAddress; #endif
0
repos/georgios/kernel/platform/acpica
repos/georgios/kernel/platform/acpica/include/acpi.h
#include "platform/acenv.h" #include_next <acpi.h>
0
repos/georgios/kernel/platform/acpica/include
repos/georgios/kernel/platform/acpica/include/platform/acgeorgios.h
#ifndef GEORGIOS_ACPICA_CONFIG_HEADER #define GEORGIOS_ACPICA_CONFIG_HEADER #define ACPI_MACHINE_WIDTH 32 #define ACPI_DIV_64_BY_32(n_hi, n_lo, d32, q32, r32) \ asm("divl %2;" : "=a"(q32), "=d"(r32) : "r"(d32), "0"(n_lo), "1"(n_hi)) #define ACPI_SHIFT_RIGHT_64(n_hi, n_lo) \ asm("shrl $1, %2; rcrl $1, %3;" : "=r"(n_hi), "=r"(n_lo) : "0"(n_hi), "1"(n_lo)) #define ACPI_NO_ERROR_MESSAGES #define ACPI_CACHE_T ACPI_MEMORY_LIST #define ACPI_USE_LOCAL_CACHE 1 #endif
0
repos/georgios
repos/georgios/misc/clang-sanitize-blacklist.txt
[undefined] src:*
0
repos/georgios/misc
repos/georgios/misc/ext2-test-disk/make.sh
set -e mke2fs -L '' -N 0 -O none -d root -r 1 -t ext2 ext2-test-disk.img 256k
0
repos/georgios
repos/georgios/scripts/watch_log.sh
set -e file="tmp/serial.log" rm -f $file tail --retry --follow $file
0
repos/georgios
repos/georgios/scripts/zig.py
#!/usr/bin/env python3 """\ Script for managing Zig versions in use. The script uses and updates the version listed in the README.md file. current-path can be used to add zig to PATH. """ import sys import json from argparse import ArgumentParser from pathlib import Path import urllib.request import urllib import re import functools import enum import tarfile # Utils ======================================================================= def download(url, msg=''): msg += '...' print('Downloading', url + msg) try: return urllib.request.urlopen(url) except urllib.error.URLError as e: sys.exit('Failed to download {}: {}'.format(url, str(e))) def download_file(url, dest=None): if dest.is_dir(): dest = dest / url.split('/')[-1] with dest.open('wb') as f: f.write(download(url, ', saving to' + str(dest)).read()) return dest def extract_archive(archive, dest): print('Extracting', archive, 'to', dest) with tarfile.open(archive) as tf: tf.extractall(dest) archive.unlink() # Main Logic ================================================================== georgios_root = Path(__file__).resolve().parent.parent readme_path = georgios_root / 'README.md' default_zigs_path = georgios_root / '../zigs' if not default_zigs_path.is_dir(): default_zigs_path = georgios_root / 'tmp/zigs' os = 'linux' cpu = 'x86_64' zig_version_url = 'https://ziglang.org/download/index.json' field = r'0|[1-9]\d*' version_regex = r'({f})\.({f})\.({f})(?:-dev\.(\d+))?'.format(f=field) version_re = re.compile(version_regex) current_re = re.compile( r'(.*\[Zig\]\(https:\/\/ziglang.org\/\) )(?P<ver>{}.*)$'.format(version_regex)) zig_name_re = re.compile('zig-([\w-]+)-(?P<ver>{}.*)$'.format(version_regex)) @functools.total_ordering class Zig: def __init__(self, zigs_path, name): self.name = name m = zig_name_re.match(name) if not m: raise ValueError('Invalid zig name: ' + name) self.version = m.group('ver') self.path = zigs_path / name def exists(self): return (self.path / 'zig').is_file() @classmethod def from_version(cls, zigs_path, version): return cls(zigs_path, 'zig-{}-{}-{}'.format(os, cpu, version)) @classmethod def from_info(cls, zigs_path, info): return cls.from_version(zigs_path, info['version']) def is_release(self): return self.version_parts()[3] is None def guess_url(self): return "https://ziglang.org/{}/{}.tar.xz".format( "download/" + self.version if self.is_release() else "builds", self.name) def version_parts(self): return version_re.match(self.version).groups() def __eq__(self, other): return self.version == other.version def __lt__(self, other): ours = self.version_parts() theirs = other.version_parts() def lt(i): if i == 3: if theirs[3] is None: return ours[3] is not None elif ours[3] is None: return False elif ours[i] == theirs[i]: return lt(i + 1) return ours[i] < theirs[i] return lt(0) def __str__(self): return self.version def __repr__(self): return '<Zig: {}>'.format(self.name) def get_current_version(): with readme_path.open() as f: for line in f: m = current_re.match(line) if m: return m.group('ver') raise ValueError('Could not get current from README.md') def set_current_version(version): lines = readme_path.read_text().split('\n') for i, line in enumerate(lines): m = current_re.search(line) if m: lines[i] = m.group(1) + version readme_path.write_text('\n'.join(lines)) def get_current(zigs_path): return Zig.from_version(zigs_path, get_current_version()) def get_downloaded(zigs_path): l = [] for zig_path in zigs_path.glob('*'): try: zig = Zig(zigs_path, zig_path.name) if zig.exists(): l.append(zig) except: pass return sorted(l) def use(zigs_path, version=None, zig=None): if version is not None: zig = Zig.from_version(zigs_path, version) elif zig is None: raise ValueError print('Using', zig.version) if not zig.exists(): raise ValueError('Trying to use a Zig that does not exist: ' + str(zig.path)) set_current_version(zig.version) print('Refresh PATH if needed') def get_latest_info(): return json.load(download(zig_version_url))["master"] class CheckStatus(enum.Enum): UsingLatest = enum.auto(), LatestNotCurrent = enum.auto(), NeedToDownloadLatest = enum.auto(), def check(zigs_path, for_update=False): current = get_current(zigs_path) print('Current is', current) if not for_update and not current.exists(): print(' It needs to be downloaded!') latest_info = get_latest_info() latest = Zig.from_info(args.zigs_path, latest_info) print('Latest is', latest) using_latest = latest == current if using_latest: print(' Same as current') if latest.exists(): if using_latest: status = CheckStatus.UsingLatest else: print(' Latest was downloaded, but isn\'t current') status = CheckStatus.LatestNotCurrent else: if for_update: print(' Will download the latest') else: print(' Would need to be downloaded') status = CheckStatus.NeedToDownloadLatest return status, latest, latest_info def download_zig(zigs_path, zig, url): extract_archive(download_file(url, zigs_path), zigs_path) def update(zigs_path): status, latest, latest_info = check(args.zigs_path, for_update=True) if status == CheckStatus.UsingLatest: return if status == CheckStatus.NeedToDownloadLatest: download_zig(zigs_path, latest, latest_info['{}-{}'.format(cpu, os)]['tarball']) status = CheckStatus.LatestNotCurrent if status == CheckStatus.LatestNotCurrent: use(zigs_path, zig=latest) # Subcommands ================================================================= def current_path_subcmd(args): zig = get_current(args.zigs_path) if not zig.exists(): raise ValueError('Zig in README.md does not exist: ' + str(zig.path)) print(zig.path.resolve()) def current_version_subcmd(args): print(get_current_version()) def check_subcmd(args): check(args.zigs_path) def list_subcmd(args): for zig in reversed(get_downloaded(args.zigs_path)): print(zig.version) def use_subcmd(args): use(args.zigs_path, version=args.version) def update_subcmd(args): update(args.zigs_path) def download_subcmd(args): zig = get_current(args.zigs_path) if zig.exists(): print('Already downloaded', zig.version) return download_zig(args.zigs_path, zig, zig.guess_url()) # Main ======================================================================== if __name__ == '__main__': arg_parser = ArgumentParser(description=__doc__) arg_parser.add_argument('--zigs-path', type=Path, default=default_zigs_path, help='Where to store all the versions of Zig' ) subcmds = arg_parser.add_subparsers() cp = subcmds.add_parser('current-path', help='Print the path of the current Zig', ) cp.set_defaults(func=current_path_subcmd) cv = subcmds.add_parser('current-version', help='Print the the current version of Zig', ) cv.set_defaults(func=current_version_subcmd) c = subcmds.add_parser('check', help='See if there is a new latest', ) c.set_defaults(func=check_subcmd) l = subcmds.add_parser('list', help='List all downloaded versions', ) l.set_defaults(func=list_subcmd) us = subcmds.add_parser('use', help='Use a specified downloaded version', ) us.set_defaults(func=use_subcmd) us.add_argument('version', metavar='VERSION') up = subcmds.add_parser('update', help='Use the latest version, downloading if needed', ) up.set_defaults(func=update_subcmd) dl = subcmds.add_parser('download', help='Downloading the current version if missing', ) dl.set_defaults(func=download_subcmd) args = arg_parser.parse_args() if not hasattr(args, 'func'): arg_parser.error('Must provide a subcommand') if args.zigs_path == default_zigs_path: args.zigs_path.resolve().mkdir(parents=True, exist_ok=True) args.zigs_path = args.zigs_path.resolve() args.func(args)
0
repos/georgios
repos/georgios/scripts/bits.py
#!/usr/bin/env python3 import sys def bits(value): m = value.bit_length() for i in range(0, m): if value & (1<<i): print("Bit", i, "enabled") def usage(rv): print("Supply ") sys.exit(rv) if len(sys.argv) != 2: usage(1) bits(int(sys.argv[1], 16))
0
repos/georgios
repos/georgios/scripts/read_paging.py
import sys # dump data in gdb using something like # dump binary memory FILE ((unsigned*)&WHAT) (((unsigned*)&WHAT)+1024) # This dumps the current one: # dump binary memory FILE ((unsigned*)($cr3+0xc0000000)) (((unsigned*)($cr3+0xc0000000))+1024) # And read using: # read_paging.py directory FILE # read_paging.py table FILE # read_paging.py raw FILE path = sys.argv[2] data = {} word_count = 0 with open(path, 'br') as f: role = [] role_start = None word = [] for byte in f.read(): word.append(byte) if len(word) == 4: # 44 33 22 11 -> 0x11223344 real_word = word[0] + (word[1] << 8) + (word[2] << 16) + (word[3] << 24) if real_word: if not role: role_start = word_count role.append(real_word) elif role: data[role_start] = role role = [] word_count += 1 word = [] if role: data[role_start] = role if word: sys.exit("Uneven ammount of bytes!") def common_flags(value): what = [] if value & (1 << 1): what.append("Writable") if value & (1 << 2): what.append("User") else: what.append("Non-user") if value & (1 << 3): what.append("Write-through") else: what.append("Write-back") if value & (1 << 4): what.append("Non-Cached") else: what.append("Cached") if value & (1 << 5): what.append("Accessed") return what if sys.argv[1] == 'directory': for role_start, role in data.items(): for index, value in enumerate(role): if value & 1: what = [] what.extend(common_flags(value)) if value & (1 << 6): what.append("4MiB Pages") else: what.append("4KiB Pages") print("+{:08X} -:- Page Table at {:08X}: {}".format( (role_start + index) * 0x400000, value & 0xfffff000, ", ".join(what))) elif sys.argv[1] == 'table': for role_start, role in data.items(): for index, value in enumerate(role): if value & 1: what = [] what.extend(common_flags(value)) if value & (1 << 6): what.append("Dirty") else: what.append("Clean") if value & (1 << 7): what.append("PAT") if value & (1 << 7): what.append("Global") print("+{:08X} -:- Page at {:08X}: {}".format( (role_start + index) * 0x400000, value & 0xfffff000, ", ".join(what))) elif sys.argv[1] == 'raw': for role_start, role in data.items(): print("+{:08X} ================================================".format(role_start*4)) for index, value in enumerate(role): print("+{:08X} -:- {:08X}".format((role_start + index) * 4, value)) else: sys.exit(1)
0
repos/georgios
repos/georgios/scripts/install_to_disk.sh
# Replace disk.img with another one that can be booted from. # # TODO: Figure out how to do this without root and a bunch of utilities. It's # possible to write the disk image myself if I'm already writing GPT and Ext2 # code for the OS itself. If I can do this I'm not far from having the OS being # able to install itself. The only major roadblock would be getting GRUB into # the image. grub-install needs the disk to be a block device that is mounted. set -e echo Check for Existing Loop Device =========================================== if [ ! -z "$(losetup -j disk.img)" ] then for dev in $(losetup -j disk.img | cut -d ':' -f 1) do echo "Disk image is already a device at $dev, removing..." for part_dev in $(mount | grep -s "$dev" | cut -d ' ' -f 1) do echo "$dev is mounted as $part_dev, unmounting..." sudo umount $part_dev done sudo losetup --detach $dev done fi echo Create Blank Image ======================================================= rm -f disk.img dd if=/dev/zero of=disk.img iflag=fullblock bs=1M count=20 sync echo Create Loop Device ======================================================= sudo losetup --partscan --find --offset 0 disk.img dev=$(losetup -j disk.img | cut -d ':' -f 1) read -p "$dev is the device, type Y if this is correct. " -n 1 -r echo if [[ $REPLY =~ ^[Yy]$ ]] then echo "OK" else echo "Not Y, aborting..." exit 1 fi echo Create Partitions ======================================================== sudo sfdisk $dev < misc/disk.sfdisk echo Format Ext2 Partition ==================================================== root_dev="${dev}p2" if [ ! -b $root_dev ] then echo "$root_dev is an invalid block device" exit 1 fi sudo mke2fs -L '' -N 0 -O none -d tmp/root -r 1 -t ext2 $root_dev echo Mount Ext2 Partition ===================================================== mkdir -p tmp/mount_point sudo mount $root_dev tmp/mount_point echo Copy Extra Files ========================================================= sudo cp misc/grub_hd.cfg tmp/mount_point/boot/grub/grub.cfg echo Install GRUB ============================================================= sudo grub-install --target=i386-pc \ --root-directory=tmp/mount_point --boot-directory=tmp/mount_point/boot $dev echo Unmount Ext2 Partition =================================================== sync sudo umount tmp/mount_point echo Remove Loop Device ======================================================= sudo losetup -d $dev
0
repos/georgios
repos/georgios/scripts/gpf_error_code.py
#!/usr/bin/env python3 import sys if len(sys.argv) != 2: print("Pass Error Code from a General Protection Fault") sys.exit(1) print("Error Caused By:") value = int(sys.argv[1]) if value & 1: print("External To The CPU") table = ["GDT", "IDT", "LDT", "IDT"][(value >> 1) & 3] print("In the", table) index = (value >> 3) & 8191 print("At Selector Index", index) if (table == "IDT"): print("This is", ("Intel Interrupt " + str(index)) if index < 32 else ("IRQ " + str(index - 32)))
0
repos/georgios
repos/georgios/scripts/lint.py
import sys from pathlib import Path import subprocess import re import traceback def git(*args): result = subprocess.run(["git"] + list(args), check=True, stdout=subprocess.PIPE) return result.stdout.decode('utf-8').split('\n') def get_files(): # Get Tracked Files files = set([Path(p) for p in git("ls-files") if p]) if not files: sys.exit("Error: No Tracked Files") # Get Untracked Files files |= set([Path(p[3:]) for p in git("status", "--porcelain=v1") if p.startswith('??')]) return sorted(list(files)) status = 0 # Find Files ================================================================== trailing_whitespace = re.compile(r'\s$') zig_test_re = re.compile(r'^test "(.*)" {$') zig_test_roots = set() zig_files_with_tests = set() for path in get_files(): if not path.is_file() or path.suffix in ('.img', '.png', '.gif', '.bmp'): continue try: with path.open() as f: lines = [line[:-1] for line in f.readlines()] zig_file = path.suffix == ".zig" lineno = 1 for line in lines: if trailing_whitespace.match(line): print('Trailing space on {}:{}'.format(str(path), lineno)) status = 1 if zig_file: m = zig_test_re.match(line) if m: if m.group(1).endswith("test root"): zig_test_roots |= {path} else: zig_files_with_tests |= {path} lineno += 1 except Exception: print('ERROR: Exception thrown while reading {}:', repr(str(path)), file=sys.stderr) traceback.print_exc(file=sys.stderr) status = 1 # Make sure all tests are being tested ======================================== # Make sure all test roots are in build.zig zig_add_tests_re = re.compile(r'add_tests\("([\w/]+.zig)"\);') zig_add_tests = set() with open('build.zig') as f: for line in f.readlines(): m = zig_add_tests_re.search(line) if m: zig_add_tests |= {Path(m.group(1))} missing_from_build_zig = zig_test_roots - zig_add_tests if missing_from_build_zig: print('Missing from build.zig:', ', '.join([str(p) for p in missing_from_build_zig])) status = 1 missing_zig_test_roots = zig_add_tests - zig_test_roots if missing_zig_test_roots: print('add_tests in build.zig that are not test roots:', ', '.join([str(p) for p in missing_zig_test_roots])) status = 1 # Make sure all zig files with tests are in a test root imported_in_test_roots = set() test_import_re = re.compile(r'_ = @import\("([\w/]+.zig)"\);') for zig_test_root in zig_test_roots: with open(zig_test_root) as f: for line in f.readlines(): m = test_import_re.search(line) if m: imported_in_test_roots |= {zig_test_root.parent / m.group(1)} missing_from_test_roots = zig_files_with_tests - imported_in_test_roots if missing_from_test_roots: print('Missing from a test root:', ', '.join([str(p) for p in missing_from_test_roots])) status = 1 missing_zig_tests = imported_in_test_roots - zig_files_with_tests if missing_zig_tests: print('Imports in test roots without tests:', ', '.join([str(p) for p in missing_zig_tests])) status = 1 sys.exit(status)
0
repos/georgios
repos/georgios/scripts/flags.py
#!/usr/bin/env python3 import sys if len(sys.argv) != 2: print("Pass x86 Flags Register Value as Hex") sys.exit(1) value = int(sys.argv[1], 16) if value & 0x0001: print("Carry") if value & 0x0004: print("Parity") if value & 0x0010: print("Adjust") if value & 0x0040: print("Zero") if value & 0x0080: print("Sign") if value & 0x0100: print("Trap") if value & 0x0200: print("Interrupts Enabled") if value & 0x0400: print("Direction") if value & 0x0800: print("Overflow") # I/O Privilege Level (Ignore for now) if value & 0x4000: print("Nested Task") if value & 0x00010000: print("Resume") if value & 0x00020000: print("Virutal 8086 Mode") if value & 0x00040000: print("Virtual Interrupt") if value & 0x00100000: print("Virtual Interrupt Pending") if value & 0x00200000: print("Able to use CPUID")
0
repos/georgios
repos/georgios/scripts/sanity_check.sh
set -e function pop { git stash pop } function do_or_pop { echo $@ $@ || (echo "$@ failed" && pop && exit 1) } git clean --force -dX git stash --keep-index --include-untracked do_or_pop make test do_or_pop make pop
0
repos/georgios
repos/georgios/scripts/gen-test-file.py
#!/usr/bin/env python3 int_size = 4 total_size = 1048576 int_count = total_size // int_size with open('tmp/root/files/test-file', 'bw') as f: for i in range(0, int_count): f.write(i.to_bytes(int_size, 'little'))
0
repos/georgios/scripts
repos/georgios/scripts/codegen/genif.py
#!/usr/bin/env python3 '''\ Georgios Interface Code Generator ''' from argparse import ArgumentParser from pathlib import Path from bridle.type_files import add_type_file_argument_parsing, type_files_to_trees import bridle.tree as ast from bridle.tree import InterfaceNode from bridle.tree import PrimitiveKind indent = ' ' zig_primitives = { PrimitiveKind.boolean: 'bool', PrimitiveKind.byte: 'u8', PrimitiveKind.u8: 'u8', PrimitiveKind.i8: 'i8', PrimitiveKind.u16: 'u16', PrimitiveKind.i16: 'i16', PrimitiveKind.u32: 'u32', PrimitiveKind.i32: 'i32', PrimitiveKind.u64: 'u64', PrimitiveKind.i64: 'i64', PrimitiveKind.u128: 'u128', PrimitiveKind.i128: 'i128', PrimitiveKind.f32: 'f32', PrimitiveKind.f64: 'f64', PrimitiveKind.f128: 'f128', PrimitiveKind.c8: 'u8', PrimitiveKind.c16: 'u16', PrimitiveKind.s8: '[]const u8', PrimitiveKind.s16: '[]const u32', } def to_zig_type(type_node): if isinstance(type_node, ast.PrimitiveNode): return zig_primitives[type_node.kind] elif str(type_node) == 'void': # TODO: Should be a better way to do this return 'void' elif isinstance(type_node, ast.ScopedName): return '.'.join(type_node.parts) else: raise TypeError('Unsupported: ' + repr(type(type_node)) + ': ' + repr(type_node)) def arg_list(args): return ', '.join(args) def zig_signature(return_type, args, preargs={}, postargs={}): all_args = {} for args in [preargs, args, postargs]: for name, type in args.items(): all_args[name] = type return ('({}) georgios.DispatchError!{}'.format(arg_list( ['{}: {}'.format(name, type) for name, type in all_args.items()]), return_type), all_args) def op_to_zig_signature(op, preargs={}, postargs={}): return zig_signature(to_zig_type(op.return_type), {name: to_zig_type(type.type) for name, type in op}, preargs=preargs, postargs=postargs, ) class ZigFile: def __init__(self, source): self.path = source.parent / (source.stem + '.zig') self.file = self.path.open('w') self.indent_level = 0 self.last_indent_change = 0 self.print('// Generated from {} by ifgen.py\n', source) self.print('const georgios = @import("georgios.zig");', source) def print_i(self, what, *args, **kwargs): i = indent * self.indent_level formatted = what.format(*args, **kwargs) print(i + formatted.replace('\n', '\n' + i), file=self.file, flush=True) def print(self, what, *args, indent_change=0, **kwargs): # Insert a newline if a member is added or a new scope/block is being # opened after closing a nested scope/block or a new scope/block is # being opened after a member. if (indent_change >= 0 and self.last_indent_change < 0) or \ (indent_change > 0 and self.last_indent_change == 0): print('', file=self.file, flush=True) # Decrease indent before closing scope/block if indent_change < 0: self.indent_level += indent_change self.print_i(what, *args, **kwargs) # Increate indent after opening scope/block if indent_change > 0: self.indent_level += indent_change self.last_indent_change = indent_change def open_scope(self, name, what, public=True): self.print('{}const {} = {} {{', 'pub ' if public else '', name, what, indent_change=1) def open_struct(self, name, public=True): self.open_scope(name, 'struct', public=public) def open_union(self, name, public=True): self.open_scope(name, 'union (enum)', public=public) def member(self, name, type, default = None): self.print('{}: {}{},', name, type, (' = ' + default) if default else '') def close_scope(self): self.print('}};', indent_change=-1) def open_block(self, what, *args, **kwargs): self.print(what + ' {{', *args, **kwargs, indent_change=1) def open_function_i(self, name, signature): self.open_block('pub fn {}{}', name, signature) def open_function(self, name, return_type, args, preargs={}, postargs={}): sig, all_args = zig_signature(return_type, args, preargs=preargs, postargs=postargs) return self.open_function_i(name, sig) def open_op_function(self, op, preargs={}, postargs={}, prefix='', postfix=''): sig, all_args = op_to_zig_signature(op, preargs=preargs, postargs=postargs) self.open_function_i(prefix + op.name + postfix, sig) return all_args def open_if(self, condition=None): self.open_block('if ({})', condition) def else_block(self, condition=None): self.indent_level -= 1 self.print_i('}} else{} {{', '' if condition is None else (' if (' + condition + ')')) self.indent_level += 1 self.last_indent_change = 1 def close_block(self): self.print('}}', indent_change=-1) def has_annotation(node, name): # TODO: Work on better way to get this info from the node in bridle for annotation in node.annotations: if annotation.name == name: return True return False def gen_syscall(zig_file, node): for name, op in node: zig_file.open_op_function(op) zig_file.close_block() def gen_dispatch(zig_file, node): self = {'self': '*' + node.name} # TODO: Zig Error Translation # Virtual Functions for name, op in node: all_args = zig_file.open_op_function(op, preargs=self) zig_file.print('return self._{}_impl({});', name, arg_list(all_args)) zig_file.close_block() # Dispatch Argument Message Data zig_file.open_union('_ArgVals') for op_name, op in node: count = len(op) if count == 0: args_type = 'void' elif count == 1: args_type = to_zig_type(op.children[0].type) else: args_type = 'struct {\n' for arg_name, arg in op: args_type += '{}{}: {},\n'.format(indent, arg_name, to_zig_type(arg.type)) args_type += '}' zig_file.member('_' + op_name, args_type) zig_file.close_scope() # Dispatch Return Message Data zig_file.open_union('_RetVals') for name, op in node: zig_file.member('_' + name, to_zig_type(op.return_type)) zig_file.close_scope() # Dispatch Call/Send Implementations zig_file.open_struct('_dispatch_impls') for op_name, op in node: zig_file.open_op_function(op, preargs=self, prefix='_', postfix = '_impl') if len(op) == 1: for name in op.child_names(): args = name break else: args = '.{' + arg_list(['.{0} = {0}'.format(name) for name in op.child_names()]) + '}' zig_file.print('return georgios.send_value(&_ArgVals{{.{} = {}}}, self._port_id, .{{}});', '_' + op_name, args) zig_file.close_block() zig_file.close_scope() # Dispatch Server Recv Implementation zig_file.open_function('_recv_value', 'void', {'dispatch': 'georgios.Dispatch'}, self) zig_file.open_block('return switch ((try georgios.msg_cast(_ArgVals, dispatch)).*)') for op_name, op in node: count = len(op) args = ['self'] capture = ' |val|' if count == 0: capture = '' elif count == 1: args.append('val') else: args.extend(['val.' + arg for arg in op.child_names()]) zig_file.print('._{} =>{} self._{}_impl({}),', op_name, capture, op_name, arg_list(args)) zig_file.close_scope() zig_file.close_block() # TODO # Unsupported Implementations # zig_file.open_struct('_unsupported_impls') # for name, op in node: # all_args = zig_file.open_op_function(op, preargs=self, prefix='_') # for name in all_args.keys(): # zig_file.print('_ = {};', name) # zig_file.print('@panic("TODO");') # TODO # zig_file.close_block() # zig_file.close_scope() # TODO: Nop Implementation? # Implementation Functions Members zig_file.member('_port_id', 'georgios.PortId') for name, op in node: func_name = '_' + name + '_impl' zig_file.member(func_name, 'fn' + op_to_zig_signature(op, preargs=self)[0], default='_dispatch_impls.' + func_name) def main(): argparser = ArgumentParser(description=__doc__) add_type_file_argument_parsing(argparser) args = argparser.parse_args() trees = type_files_to_trees(args) for tree in trees: zig_file = ZigFile(tree.loc.source) for node in tree.children: if isinstance(node, InterfaceNode): zig_file.open_struct(node.name) if has_annotation(node, 'syscalls'): gen_syscall(zig_file, node) elif has_annotation(node, 'virtual_dispatch'): gen_dispatch(zig_file, node) else: print(node.name, 'does not have an expected annotation') zig_file.close_scope() if __name__ == "__main__": main()
0
repos/georgios/scripts
repos/georgios/scripts/codegen/code_page_437.py
# Generate conversion code from Unicode Code Point to Code Page 437, the IBM PC # CGA builtin character set. import sys zig_file = 'kernel/platform/code_point_437.zig' # Utilities ================================================================== class KeyValue: def __init__(self, key, value): self.key = key self.value = value def __lt__(self, other): return self.key < other.key def __repr__(self): return '<0x{:04x}: 0x{:02x}>'.format(self.key, self.value) def offset(self): return self.key - self.value class Range: def __init__(self, kv=None): self.kvs = [kv] if kv is not None else [] def goes_next(self, keyvalue): if keyvalue is None or (self.kvs and keyvalue.key != self.kvs[-1].key + 1): return False self.kvs.append(keyvalue) return True def same_offset(self): if self.kvs: first_offset = self.kvs[0].offset() for kv in self.kvs[1:]: if kv.offset() != first_offset: return None return first_offset return None def __len__(self): return len(self.kvs) def __bool_(self): return len(self.kvs) > 0 def __repr__(self): if self.kvs: return '<{} -> {} ({})>'.format( repr(self.kvs[0]), repr(self.kvs[-1]), len(self.kvs)) else: return '<(0)>' def get_ranges(l): ranges = [Range(l[0])] for kv in l[1:]: if not ranges[-1].goes_next(kv): ranges.append(Range(kv)) return ranges # Code Page 437 Unicode Data ================================================= # Based on the table in https://en.wikipedia.org/wiki/Code_page_437 keys = [ # 0/NUL is left to an unknown, because it would be the same as a space in # 437, but I don't think it should. None, 0x263a, # "☺" WHITE SMILING FACE 0x263b, # "☻" BLACK SMILING FACE 0x2665, # "♥" BLACK HEART SUIT 0x2666, # "♦" BLACK DIAMOND SUIT 0x2663, # "♣" BLACK CLUB SUIT 0x2660, # "♠" BLACK SPADE SUIT 0x2022, # "•" BULLET 0x25d8, # "◘" INVERSE BULLET 0x25cb, # "○" WHITE CIRCLE 0x25d9, # "◙" INVERSE WHITE CIRCLE 0x2642, # "♂" MALE SIGN 0x2640, # "♀" FEMALE SIGN 0x266a, # "♪" EIGHTH NOTE 0x266b, # "♫" BEAMED EIGHTH NOTES 0x263c, # "☼" WHITE SUN WITH RAYS 0x25ba, # "►" BLACK RIGHT-POINTING POINTER 0x25c4, # "◄" BLACK LEFT-POINTING POINTER 0x2195, # "↕" UP DOWN ARROW 0x203c, # "‼" DOUBLE EXCLAMATION MARK 0x00b6, # "¶" PILCROW SIGN 0x00a7, # "§" SECTION SIGN 0x25ac, # "▬" BLACK RECTANGLE 0x21a8, # "↨" UP DOWN ARROW WITH BASE 0x2191, # "↑" UPWARDS ARROW 0x2193, # "↓" DOWNWARDS ARROW 0x2192, # "→" RIGHTWARDS ARROW 0x2190, # "←" LEFTWARDS ARROW 0x221f, # "∟" RIGHT ANGLE 0x2194, # "↔" LEFT RIGHT ARROW 0x25b2, # "▲" BLACK UP-POINTING TRIANGLE 0x25bc, # "▼" BLACK DOWN-POINTING TRIANGLE 0x0020, # " " SPACE 0x0021, # "!" EXCLAMATION MARK 0x0022, # """ QUOTATION MARK 0x0023, # "#" NUMBER SIGN 0x0024, # "$" DOLLAR SIGN 0x0025, # "%" PERCENT SIGN 0x0026, # "&" AMPERSAND 0x0027, # "'" APOSTROPHE 0x0028, # "(" LEFT PARENTHESIS 0x0029, # ")" RIGHT PARENTHESIS 0x002a, # "*" ASTERISK 0x002b, # "+" PLUS SIGN 0x002c, # "," COMMA 0x002d, # "-" HYPHEN-MINUS 0x002e, # "." FULL STOP 0x002f, # "/" SOLIDUS 0x0030, # "0" DIGIT ZERO 0x0031, # "1" DIGIT ONE 0x0032, # "2" DIGIT TWO 0x0033, # "3" DIGIT THREE 0x0034, # "4" DIGIT FOUR 0x0035, # "5" DIGIT FIVE 0x0036, # "6" DIGIT SIX 0x0037, # "7" DIGIT SEVEN 0x0038, # "8" DIGIT EIGHT 0x0039, # "9" DIGIT NINE 0x003a, # ":" COLON 0x003b, # ";" SEMICOLON 0x003c, # "<" LESS-THAN SIGN 0x003d, # "=" EQUALS SIGN 0x003e, # ">" GREATER-THAN SIGN 0x003f, # "?" QUESTION MARK 0x0040, # "@" COMMERCIAL AT 0x0041, # "A" LATIN CAPITAL LETTER A 0x0042, # "B" LATIN CAPITAL LETTER B 0x0043, # "C" LATIN CAPITAL LETTER C 0x0044, # "D" LATIN CAPITAL LETTER D 0x0045, # "E" LATIN CAPITAL LETTER E 0x0046, # "F" LATIN CAPITAL LETTER F 0x0047, # "G" LATIN CAPITAL LETTER G 0x0048, # "H" LATIN CAPITAL LETTER H 0x0049, # "I" LATIN CAPITAL LETTER I 0x004a, # "J" LATIN CAPITAL LETTER J 0x004b, # "K" LATIN CAPITAL LETTER K 0x004c, # "L" LATIN CAPITAL LETTER L 0x004d, # "M" LATIN CAPITAL LETTER M 0x004e, # "N" LATIN CAPITAL LETTER N 0x004f, # "O" LATIN CAPITAL LETTER O 0x0050, # "P" LATIN CAPITAL LETTER P 0x0051, # "Q" LATIN CAPITAL LETTER Q 0x0052, # "R" LATIN CAPITAL LETTER R 0x0053, # "S" LATIN CAPITAL LETTER S 0x0054, # "T" LATIN CAPITAL LETTER T 0x0055, # "U" LATIN CAPITAL LETTER U 0x0056, # "V" LATIN CAPITAL LETTER V 0x0057, # "W" LATIN CAPITAL LETTER W 0x0058, # "X" LATIN CAPITAL LETTER X 0x0059, # "Y" LATIN CAPITAL LETTER Y 0x005a, # "Z" LATIN CAPITAL LETTER Z 0x005b, # "[" LEFT SQUARE BRACKET 0x005c, # "\" REVERSE SOLIDUS 0x005d, # "]" RIGHT SQUARE BRACKET 0x005e, # "^" CIRCUMFLEX ACCENT 0x005f, # "_" LOW LINE 0x0060, # "`" GRAVE ACCENT 0x0061, # "a" LATIN SMALL LETTER A 0x0062, # "b" LATIN SMALL LETTER B 0x0063, # "c" LATIN SMALL LETTER C 0x0064, # "d" LATIN SMALL LETTER D 0x0065, # "e" LATIN SMALL LETTER E 0x0066, # "f" LATIN SMALL LETTER F 0x0067, # "g" LATIN SMALL LETTER G 0x0068, # "h" LATIN SMALL LETTER H 0x0069, # "i" LATIN SMALL LETTER I 0x006a, # "j" LATIN SMALL LETTER J 0x006b, # "k" LATIN SMALL LETTER K 0x006c, # "l" LATIN SMALL LETTER L 0x006d, # "m" LATIN SMALL LETTER M 0x006e, # "n" LATIN SMALL LETTER N 0x006f, # "o" LATIN SMALL LETTER O 0x0070, # "p" LATIN SMALL LETTER P 0x0071, # "q" LATIN SMALL LETTER Q 0x0072, # "r" LATIN SMALL LETTER R 0x0073, # "s" LATIN SMALL LETTER S 0x0074, # "t" LATIN SMALL LETTER T 0x0075, # "u" LATIN SMALL LETTER U 0x0076, # "v" LATIN SMALL LETTER V 0x0077, # "w" LATIN SMALL LETTER W 0x0078, # "x" LATIN SMALL LETTER X 0x0079, # "y" LATIN SMALL LETTER Y 0x007a, # "z" LATIN SMALL LETTER Z 0x007b, # "{" LEFT CURLY BRACKET 0x007c, # "|" VERTICAL LINE 0x007d, # "}" RIGHT CURLY BRACKET 0x007e, # "~" TILDE 0x2302, # "⌂" HOUSE 0x00c7, # "Ç" LATIN CAPITAL LETTER C WITH CEDILLA 0x00fc, # "ü" LATIN SMALL LETTER U WITH DIAERESIS 0x00e9, # "é" LATIN SMALL LETTER E WITH ACUTE 0x00e2, # "â" LATIN SMALL LETTER A WITH CIRCUMFLEX 0x00e4, # "ä" LATIN SMALL LETTER A WITH DIAERESIS 0x00e0, # "à" LATIN SMALL LETTER A WITH GRAVE 0x00e5, # "å" LATIN SMALL LETTER A WITH RING ABOVE 0x00e7, # "ç" LATIN SMALL LETTER C WITH CEDILLA 0x00ea, # "ê" LATIN SMALL LETTER E WITH CIRCUMFLEX 0x00eb, # "ë" LATIN SMALL LETTER E WITH DIAERESIS 0x00e8, # "è" LATIN SMALL LETTER E WITH GRAVE 0x00ef, # "ï" LATIN SMALL LETTER I WITH DIAERESIS 0x00ee, # "î" LATIN SMALL LETTER I WITH CIRCUMFLEX 0x00ec, # "ì" LATIN SMALL LETTER I WITH GRAVE 0x00c4, # "Ä" LATIN CAPITAL LETTER A WITH DIAERESIS 0x00c5, # "Å" LATIN CAPITAL LETTER A WITH RING ABOVE 0x00c9, # "É" LATIN CAPITAL LETTER E WITH ACUTE 0x00e6, # "æ" LATIN SMALL LETTER AE 0x00c6, # "Æ" LATIN CAPITAL LETTER AE 0x00f4, # "ô" LATIN SMALL LETTER O WITH CIRCUMFLEX 0x00f6, # "ö" LATIN SMALL LETTER O WITH DIAERESIS 0x00f2, # "ò" LATIN SMALL LETTER O WITH GRAVE 0x00fb, # "û" LATIN SMALL LETTER U WITH CIRCUMFLEX 0x00f9, # "ù" LATIN SMALL LETTER U WITH GRAVE 0x00ff, # "ÿ" LATIN SMALL LETTER Y WITH DIAERESIS 0x00d6, # "Ö" LATIN CAPITAL LETTER O WITH DIAERESIS 0x00dc, # "Ü" LATIN CAPITAL LETTER U WITH DIAERESIS 0x00a2, # "¢" CENT SIGN 0x00a3, # "£" POUND SIGN 0x00a5, # "¥" YEN SIGN 0x20a7, # "₧" PESETA SIGN 0x0192, # "ƒ" LATIN SMALL LETTER F WITH HOOK 0x00e1, # "á" LATIN SMALL LETTER A WITH ACUTE 0x00ed, # "í" LATIN SMALL LETTER I WITH ACUTE 0x00f3, # "ó" LATIN SMALL LETTER O WITH ACUTE 0x00fa, # "ú" LATIN SMALL LETTER U WITH ACUTE 0x00f1, # "ñ" LATIN SMALL LETTER N WITH TILDE 0x00d1, # "Ñ" LATIN CAPITAL LETTER N WITH TILDE 0x00aa, # "ª" FEMININE ORDINAL INDICATOR 0x00ba, # "º" MASCULINE ORDINAL INDICATOR 0x00bf, # "¿" INVERTED QUESTION MARK 0x2310, # "⌐" REVERSED NOT SIGN 0x00ac, # "¬" NOT SIGN 0x00bd, # "½" VULGAR FRACTION ONE HALF 0x00bc, # "¼" VULGAR FRACTION ONE QUARTER 0x00a1, # "¡" INVERTED EXCLAMATION MARK 0x00ab, # "«" LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00bb, # "»" RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x2591, # "░" LIGHT SHADE 0x2592, # "▒" MEDIUM SHADE 0x2593, # "▓" DARK SHADE 0x2502, # "│" BOX DRAWINGS LIGHT VERTICAL 0x2524, # "┤" BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x2561, # "╡" BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE 0x2562, # "╢" BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE 0x2556, # "╖" BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE 0x2555, # "╕" BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE 0x2563, # "╣" BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x2551, # "║" BOX DRAWINGS DOUBLE VERTICAL 0x2557, # "╗" BOX DRAWINGS DOUBLE DOWN AND LEFT 0x255d, # "╝" BOX DRAWINGS DOUBLE UP AND LEFT 0x255c, # "╜" BOX DRAWINGS UP DOUBLE AND LEFT SINGLE 0x255b, # "╛" BOX DRAWINGS UP SINGLE AND LEFT DOUBLE 0x2510, # "┐" BOX DRAWINGS LIGHT DOWN AND LEFT 0x2514, # "└" BOX DRAWINGS LIGHT UP AND RIGHT 0x2534, # "┴" BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x252c, # "┬" BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x251c, # "├" BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x2500, # "─" BOX DRAWINGS LIGHT HORIZONTAL 0x253c, # "┼" BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x255e, # "╞" BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE 0x255f, # "╟" BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE 0x255a, # "╚" BOX DRAWINGS DOUBLE UP AND RIGHT 0x2554, # "╔" BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x2569, # "╩" BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x2566, # "╦" BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x2560, # "╠" BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x2550, # "═" BOX DRAWINGS DOUBLE HORIZONTAL 0x256c, # "╬" BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x2567, # "╧" BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE 0x2568, # "╨" BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE 0x2564, # "╤" BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE 0x2565, # "╥" BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE 0x2559, # "╙" BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE 0x2558, # "╘" BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE 0x2552, # "╒" BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE 0x2553, # "╓" BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE 0x256b, # "╫" BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE 0x256a, # "╪" BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE 0x2518, # "┘" BOX DRAWINGS LIGHT UP AND LEFT 0x250c, # "┌" BOX DRAWINGS LIGHT DOWN AND RIGHT 0x2588, # "█" FULL BLOCK 0x2584, # "▄" LOWER HALF BLOCK 0x258c, # "▌" LEFT HALF BLOCK 0x2590, # "▐" RIGHT HALF BLOCK 0x2580, # "▀" UPPER HALF BLOCK 0x03b1, # "α" GREEK SMALL LETTER ALPHA 0x00df, # "ß" LATIN SMALL LETTER SHARP S 0x0393, # "Γ" GREEK CAPITAL LETTER GAMMA 0x03c0, # "π" GREEK SMALL LETTER PI 0x03a3, # "Σ" GREEK CAPITAL LETTER SIGMA 0x03c3, # "σ" GREEK SMALL LETTER SIGMA 0x00b5, # "µ" MICRO SIGN 0x03c4, # "τ" GREEK SMALL LETTER TAU 0x03a6, # "Φ" GREEK CAPITAL LETTER PHI 0x0398, # "Θ" GREEK CAPITAL LETTER THETA 0x03a9, # "Ω" GREEK CAPITAL LETTER OMEGA 0x03b4, # "δ" GREEK SMALL LETTER DELTA 0x221e, # "∞" INFINITY 0x03c6, # "φ" GREEK SMALL LETTER PHI 0x03b5, # "ε" GREEK SMALL LETTER EPSILON 0x2229, # "∩" INTERSECTION 0x2261, # "≡" IDENTICAL TO 0x00b1, # "±" PLUS-MINUS SIGN 0x2265, # "≥" GREATER-THAN OR EQUAL TO 0x2264, # "≤" LESS-THAN OR EQUAL TO 0x2320, # "⌠" TOP HALF INTEGRAL 0x2321, # "⌡" BOTTOM HALF INTEGRAL 0x00f7, # "÷" DIVISION SIGN 0x2248, # "≈" ALMOST EQUAL TO 0x00b0, # "°" DEGREE SIGN 0x2219, # "∙" BULLET OPERATOR 0x00b7, # "·" MIDDLE DOT 0x221a, # "√" SQUARE ROOT 0x207f, # "ⁿ" SUPERSCRIPT LATIN SMALL LETTER N 0x00b2, # "²" SUPERSCRIPT TWO 0x25a0, # "■" BLACK SQUARE 0x00a0, # " " NO-BREAK SPACE ] # Print Out Code Page 437 (mostly for fun) for i in range(0, 8): print(''.join([(chr(k) if k is not None else ' ') for k in keys[i * 32:i * 32 + 32]])) # Sort Out Out the Unicode Data ============================================== # Make Key Value Pairs kvs = [KeyValue(k, v) for v, k in enumerate(keys) if k is not None] kvs.sort() # Sort Into Ranges ranges = get_ranges(kvs) ranges.sort(key=lambda r: r.kvs[0].key) ranges.sort(key=lambda r: len(r), reverse=True) print('All Ranges ====================================================================') for r in ranges: print(r) # Separate Out the Contiguous Ranges from Ranges to Add to the Hash Table contiguous_ranges = [] bucket_count = 0 ranges_to_hash = [] for r in ranges: offset = r.same_offset() if offset is not None and len(r) > 1: contiguous_ranges.append(r) else: # Hash it bucket_count += len(r) ranges_to_hash.append(r) max_bucket_length = 0 buckets = {} for r in ranges_to_hash: for kv in r.kvs: m = kv.key % bucket_count # Hash is Simple Mod With Bucket Count if m not in buckets: buckets[m] = [] buckets[m].append(kv) l = len(buckets[m]) max_bucket_length = max(len(buckets[m]), max_bucket_length) print('Contiguous Ranges =============================================================') for r in contiguous_ranges: print(r) print('Hashed Ranges =================================================================') print('bucket_count:', bucket_count) print('max_bucket_length: ', max_bucket_length) if (max_bucket_length > 255): sys.exit('max_bucket_length is too large') print('size: ', max_bucket_length * bucket_count) max_hash_used = 0 for this_hash in range(0, bucket_count): if this_hash in buckets: print('0x{:08x}'.format(this_hash), buckets[this_hash]) max_hash_used = this_hash print('max_hash_used:', hex(max_hash_used)) # Code Generation ============================================================ with open(zig_file, "w") as f: def fprint(*args, **kwargs): print(*args, **kwargs, file=f) fprint('''// Generated by scripts/codegen/code_page_437.py // This is data just used by cga_console.zig ''') fprint('pub const bucket_count: u16 = {};\n'.format(bucket_count)); fprint('pub const max_bucket_length: u16 = {};\n'.format(max_bucket_length)); fprint('pub const max_hash_used: u16 = {};\n'.format(max_hash_used)); fprint('pub const hash_table = [_]u32 {') for this_hash in range(0, max_hash_used + 1): fprint(' ', end='') bucket = buckets[this_hash] if this_hash in buckets else [] for kv in bucket: fprint(' 0x{:08x},'.format( 0x01000000 | (kv.value << 16) | kv.key), end = '') for i in range(0, max_bucket_length - len(bucket)): fprint(' 0x00000000,', end = '') fprint('') fprint('''}; pub fn contiguous_ranges(c: u16) ?u8 {''') for r in contiguous_ranges: offset = r.same_offset() return_string = 'return @intCast(u8, c{})'.format( ' - 0x{:04x}'.format(offset) if offset else '') base = r.kvs[0].key fprint(' if (c >= 0x{:04x} and c <= 0x{:04x}) {};'.format( base, base + len(r) - 1, return_string)) fprint(''' return null; }''')
0
repos/georgios/scripts
repos/georgios/scripts/codegen/scan_codes.py
# ============================================================================= # Script for generating kernel/platform/ps2_scan_codes.zig # ============================================================================= codes = [ ([0x01], 'Escape', None, 'Pressed'), ([0x02], '1', 'Exclamation', 'Pressed'), ([0x03], '2', 'At', 'Pressed'), ([0x04], '3', 'Pound', 'Pressed'), ([0x05], '4', 'Dollar', 'Pressed'), ([0x06], '5', 'Percent', 'Pressed'), ([0x07], '6', 'Caret', 'Pressed'), ([0x08], '7', 'Ampersand', 'Pressed'), ([0x09], '8', 'Asterisk', 'Pressed'), ([0x0a], '9', 'LeftParentheses', 'Pressed'), ([0x0b], '0', 'RightParentheses', 'Pressed'), ([0x0c], 'Minus', 'Underscore', 'Pressed'), ([0x0d], 'Equals', 'Plus', 'Pressed'), ([0x0e], 'Backspace', None, 'Pressed'), ([0x0f], 'Tab', None, 'Pressed'), ([0x10], 'q', 'Q', 'Pressed'), ([0x11], 'w', 'W', 'Pressed'), ([0x12], 'e', 'E', 'Pressed'), ([0x13], 'r', 'R', 'Pressed'), ([0x14], 't', 'T', 'Pressed'), ([0x15], 'y', 'Y', 'Pressed'), ([0x16], 'u', 'U', 'Pressed'), ([0x17], 'i', 'I', 'Pressed'), ([0x18], 'o', 'O', 'Pressed'), ([0x19], 'p', 'P', 'Pressed'), ([0x1a], 'LeftSquareBracket', 'LeftBrace', 'Pressed'), ([0x1b], 'RightSquareBracket', 'RightBrace', 'Pressed'), ([0x1c], 'Enter', None, 'Pressed'), ([0x1d], 'LeftControl', None, 'Pressed'), ([0x1e], 'a', 'A', 'Pressed'), ([0x1f], 's', 'S', 'Pressed'), ([0x20], 'd', 'D', 'Pressed'), ([0x21], 'f', 'F', 'Pressed'), ([0x22], 'g', 'G', 'Pressed'), ([0x23], 'h', 'H', 'Pressed'), ([0x24], 'j', 'J', 'Pressed'), ([0x25], 'k', 'K', 'Pressed'), ([0x26], 'l', 'L', 'Pressed'), ([0x27], 'SemiColon', 'Colon', 'Pressed'), ([0x28], 'SingleQuote', 'DoubleQuote', 'Pressed'), ([0x29], 'BackTick', 'Tilde', 'Pressed'), ([0x2a], 'LeftShift', None, 'Pressed'), ([0x2b], 'Backslash', 'Pipe', 'Pressed'), ([0x2c], 'z', 'Z', 'Pressed'), ([0x2d], 'x', 'X', 'Pressed'), ([0x2e], 'c', 'C', 'Pressed'), ([0x2f], 'v', 'V', 'Pressed'), ([0x30], 'b', 'B', 'Pressed'), ([0x31], 'n', 'N', 'Pressed'), ([0x32], 'm', 'M', 'Pressed'), ([0x33], 'Comma', 'LessThan', 'Pressed'), ([0x34], 'Period', 'GreaterThan', 'Pressed'), ([0x35], 'Slash', 'Question', 'Pressed'), ([0x36], 'RightShift', None, 'Pressed'), ([0x37], 'KeypadAsterisk', None, 'Pressed'), ([0x38], 'LeftAlt', None, 'Pressed'), ([0x39], 'Space', None, 'Pressed'), ([0x3a], 'CapsLock', None, 'Pressed'), ([0x3b], 'F1', None, 'Pressed'), ([0x3c], 'F2', None, 'Pressed'), ([0x3d], 'F3', None, 'Pressed'), ([0x3e], 'F4', None, 'Pressed'), ([0x3f], 'F5', None, 'Pressed'), ([0x40], 'F6', None, 'Pressed'), ([0x41], 'F7', None, 'Pressed'), ([0x42], 'F8', None, 'Pressed'), ([0x43], 'F9', None, 'Pressed'), ([0x44], 'F10', None, 'Pressed'), ([0x45], 'NumberLock', None, 'Pressed'), ([0x46], 'ScrollLock', None, 'Pressed'), ([0x47], 'Keypad7', None, 'Pressed'), ([0x48], 'Keypad8', None, 'Pressed'), ([0x49], 'Keypad9', None, 'Pressed'), ([0x4a], 'KeypadMinus', None, 'Pressed'), ([0x4b], 'Keypad4', None, 'Pressed'), ([0x4c], 'Keypad5', None, 'Pressed'), ([0x4d], 'Keypad6', None, 'Pressed'), ([0x4e], 'KeypadPlus', None, 'Pressed'), ([0x4f], 'Keypad1', None, 'Pressed'), ([0x50], 'Keypad2', None, 'Pressed'), ([0x51], 'Keypad3', None, 'Pressed'), ([0x52], 'Keypad0', None, 'Pressed'), ([0x53], 'KeypadPeriod', None, 'Pressed'), ([0x57], 'F11', None, 'Pressed'), ([0x58], 'F12', None, 'Pressed'), ([0x81], 'Escape', None, 'Released'), ([0x82], '1', 'Exclamation', 'Released'), ([0x83], '2', 'At', 'Released'), ([0x84], '3', 'Pound', 'Released'), ([0x85], '4', 'Dollar', 'Released'), ([0x86], '5', 'Percent', 'Released'), ([0x87], '6', 'Caret', 'Released'), ([0x88], '7', 'Ampersand', 'Released'), ([0x89], '8', 'Asterisk', 'Released'), ([0x8a], '9', 'LeftParentheses', 'Released'), ([0x8b], '0', 'RightParentheses', 'Released'), ([0x8c], 'Minus', 'Underscore', 'Released'), ([0x8d], 'Equals', 'Plus', 'Released'), ([0x8e], 'Backspace', None, 'Released'), ([0x8f], 'Tab', None, 'Released'), ([0x90], 'q', 'Q', 'Released'), ([0x91], 'w', 'W', 'Released'), ([0x92], 'e', 'E', 'Released'), ([0x93], 'r', 'R', 'Released'), ([0x94], 't', 'T', 'Released'), ([0x95], 'y', 'Y', 'Released'), ([0x96], 'u', 'U', 'Released'), ([0x97], 'i', 'I', 'Released'), ([0x98], 'o', 'O', 'Released'), ([0x99], 'p', 'P', 'Released'), ([0x9a], 'LeftSquareBracket', 'LeftBrace', 'Released'), ([0x9b], 'RightSquareBracket', 'RightBrace', 'Released'), ([0x9c], 'Enter', None, 'Released'), ([0x9d], 'LeftControl', None, 'Released'), ([0x9e], 'a', 'A', 'Released'), ([0x9f], 's', 'S', 'Released'), ([0xa0], 'd', 'D', 'Released'), ([0xa1], 'f', 'F', 'Released'), ([0xa2], 'g', 'G', 'Released'), ([0xa3], 'h', 'H', 'Released'), ([0xa4], 'j', 'J', 'Released'), ([0xa5], 'k', 'K', 'Released'), ([0xa6], 'l', 'L', 'Released'), ([0xa7], 'SemiColon', 'Colon', 'Released'), ([0xa8], 'SingleQuote', 'DoubleQuote', 'Released'), ([0xa9], 'BackTick', 'Tilde', 'Released'), ([0xaa], 'LeftShift', None, 'Released'), ([0xab], 'Backslash', 'Pipe', 'Released'), ([0xac], 'z', 'Z', 'Released'), ([0xad], 'x', 'X', 'Released'), ([0xae], 'c', 'C', 'Released'), ([0xaf], 'v', 'V', 'Released'), ([0xb0], 'b', 'B', 'Released'), ([0xb1], 'n', 'N', 'Released'), ([0xb2], 'm', 'M', 'Released'), ([0xb3], 'Comma', 'LessThan', 'Released'), ([0xb4], 'Period', 'GreaterThan', 'Released'), ([0xb5], 'Slash', 'Question', 'Released'), ([0xb6], 'RightShift', None, 'Released'), ([0xb7], 'KeypadAsterisk', None, 'Released'), ([0xb8], 'LeftAlt', None, 'Released'), ([0xb9], 'Space', None, 'Released'), ([0xba], 'CapsLock', None, 'Released'), ([0xbb], 'F1', None, 'Released'), ([0xbc], 'F2', None, 'Released'), ([0xbd], 'F3', None, 'Released'), ([0xbe], 'F4', None, 'Released'), ([0xbf], 'F5', None, 'Released'), ([0xc0], 'F6', None, 'Released'), ([0xc1], 'F7', None, 'Released'), ([0xc2], 'F8', None, 'Released'), ([0xc3], 'F9', None, 'Released'), ([0xc4], 'F10', None, 'Released'), ([0xc5], 'NumberLock', None, 'Released'), ([0xc6], 'ScrollLock', None, 'Released'), ([0xc7], 'Keypad7', None, 'Released'), ([0xc8], 'Keypad8', None, 'Released'), ([0xc9], 'Keypad9', None, 'Released'), ([0xca], 'KeypadMinus', None, 'Released'), ([0xcb], 'Keypad4', None, 'Released'), ([0xcc], 'Keypad5', None, 'Released'), ([0xcd], 'Keypad6', None, 'Released'), ([0xce], 'KeypadPlus', None, 'Released'), ([0xcf], 'Keypad1', None, 'Released'), ([0xd0], 'Keypad2', None, 'Released'), ([0xd1], 'Keypad3', None, 'Released'), ([0xd2], 'Keypad0', None, 'Released'), ([0xd3], 'KeypadPeriod', None, 'Released'), ([0xd7], 'F11', None, 'Released'), ([0xd8], 'F12', None, 'Released'), ([0xe0, 0x1c], 'KeypadEnter', None, 'Pressed'), ([0xe0, 0x1d], 'RightControl', None, 'Pressed'), ([0xe0, 0x35], 'KeypadSlash', None, 'Pressed'), ([0xe0, 0x38], 'RightAlt', None, 'Pressed'), ([0xe0, 0x47], 'Home', None, 'Pressed'), ([0xe0, 0x48], 'CursorUp', None, 'Pressed'), ([0xe0, 0x49], 'PageUp', None, 'Pressed'), ([0xe0, 0x4b], 'CursorLeft', None, 'Pressed'), ([0xe0, 0x4d], 'CursorRight', None, 'Pressed'), ([0xe0, 0x4f], 'End', None, 'Pressed'), ([0xe0, 0x50], 'CursorDown', None, 'Pressed'), ([0xe0, 0x51], 'PageDown', None, 'Pressed'), ([0xe0, 0x52], 'Insert', None, 'Pressed'), ([0xe0, 0x53], 'Delete', None, 'Pressed'), ([0xe0, 0x5e], 'AcpiPower', None, 'Pressed'), ([0xe0, 0x5f], 'AcpiSleep', None, 'Pressed'), ([0xe0, 0x63], 'AcpiWake', None, 'Pressed'), ([0xe0, 0x9c], 'KeypadEnter', None, 'Released'), ([0xe0, 0x9d], 'RightControl', None, 'Released'), ([0xe0, 0xb5], 'KeypadSlash', None, 'Released'), ([0xe0, 0xb8], 'RightAlt', None, 'Released'), ([0xe0, 0xc7], 'Home', None, 'Released'), ([0xe0, 0xc8], 'CursorUp', None, 'Released'), ([0xe0, 0xc9], 'PageUp', None, 'Released'), ([0xe0, 0xcb], 'CursorLeft', None, 'Released'), ([0xe0, 0xcd], 'CursorRight', None, 'Released'), ([0xe0, 0xcf], 'End', None, 'Released'), ([0xe0, 0xd0], 'CursorDown', None, 'Released'), ([0xe0, 0xd1], 'PageDown', None, 'Released'), ([0xe0, 0xd2], 'Insert', None, 'Released'), ([0xe0, 0xd3], 'Delete', None, 'Released'), ([0xe0, 0xde], 'AcpiPower', None, 'Released'), ([0xe0, 0xdf], 'AcpiSleep', None, 'Released'), ([0xe0, 0xe3], 'AcpiWake', None, 'Released'), ] one_byte_codes = [] two_byte_codes = [] for code in codes: l = len(code[0]) if l == 1: one_byte_codes.append(code) elif l == 2: two_byte_codes.append(code) else: raise ValueError('Code must have one or two bytes') def key(value): if value is None: return 'null' return '.Key_' + value def kind(value): if value is None: return 'null' return '.' + value with open('kernel/platform/ps2_scan_codes.zig', 'w') as f: print('''\ // Generated by scripts/codegen/scan_codes.py const georgios = @import("georgios"); const kb = georgios.keyboard; pub const Entry = struct { key: ?kb.Key, shifted_key: ?kb.Key, kind: ?kb.Kind, };''', file=f) def make_table(codes, index, name): table = [(None, None, None)] * 256 print('\npub const', name, '= [256]Entry {', file=f) for code in codes: table[code[0][index]] = code[1:] for row in table: print(' Entry{{.key = {}, .shifted_key = {}, .kind = {}}},'.format( key(row[0]), key(row[1]), kind(row[2])), file=f) print('};', file=f) make_table(one_byte_codes, 0, 'one_byte') make_table(two_byte_codes, 1, 'two_byte')
0
repos/georgios/scripts
repos/georgios/scripts/codegen/generate_system_calls.py
#!/usr/bin/env python3 # Generates system call interface functions that can be called by programs # based on the implementation file. import sys from pathlib import Path import re from subprocess import check_output, PIPE debug = False impl_file = Path('kernel/platform/system_calls.zig') interface_file = Path('libs/georgios/system_calls.zig') this_file = Path(__file__) syscall_error_values_file = Path('tmp/syscall_error_values.zig') int_num = None syscall = None syscalls = {} syscall_regs = {} imports = {'utils': 'utils'} def log(*args, prefix_message=None, **kwargs): f = kwargs[file] if 'file' in kwargs else sys.stdout prefix = lambda what: print(what, ": ", sep='', end='', file=f) prefix(sys.argv[0]) if prefix_message is not None: prefix(prefix_message) print(*args, **kwargs) def error(*args, **kwargs): log(*args, prefix_message='ERROR', **kwargs) sys.exit(1) decompose_sig_re = re.compile(r'^(\w+)\((.*)\) (?:([^ :]+): )?((?:([^ !]+)!)?([\? \[\]\w\.]+))$') error_re = re.compile(r'^(.*)!') def decompose_sig(sig): m = decompose_sig_re.match(sig) if not m: error("Could not decompose signature of ", repr(sig)) name, args, return_name, return_type, error_return, value_return = m.groups() if return_name is None: return_name = 'rv' return name, args, return_name, return_type, error_return, value_return # See if we can skip generating the file need_to_generate = False if not interface_file.exists(): log('Missing', str(interface_file), ' so need to generate') need_to_generate = True else: interface_modified = interface_file.stat().st_mtime if this_file.stat().st_mtime >= interface_modified: log('Script changed so need to generate') need_to_generate = True elif impl_file.stat().st_mtime >= interface_modified: log(str(interface_file), 'was updated so need to generate') need_to_generate = True if not need_to_generate: log('No need to generate', str(interface_file), 'so exiting') sys.exit(0); # Parse the System Call Implementations ======================================= int_num_re = re.compile(r'pub const interrupt_number: u8 = (\d+);') indent = ' ' * 4 syscall_arg_re = re.compile(indent + r'const arg(\d+) = interrupt_stack.(\w+);.*') indent += ' ' * 4 syscall_sig_re = re.compile(indent + r'// SYSCALL: (.*)') import_re = re.compile(indent + r'// IMPORT: ([^ ]+) "([^" ]+)"') syscall_num_re = re.compile(indent + r'(\d+) => .*') with impl_file.open() as f: for i, line in enumerate(f): line = line.rstrip() lineno = i + 1 # System Call Interrupt Number m = int_num_re.fullmatch(line) if m: if syscall: error("Interrupt Number in syscall on line", lineno) if int_num is not None: error(("Found duplicate interrupt number {} on line {}, " + "already found {}").format(m.group(1), lineno, int_num)) int_num = m.group(1) continue # Registers Available for Return and Arguments m = syscall_arg_re.fullmatch(line) if m: if syscall: error("Syscall register in syscall on line", lineno) syscall_regs[int(m.group(1))] = m.group(2) continue # System Call Pseudo-Signature (see implementation file for details) m = syscall_sig_re.fullmatch(line) if m: if syscall: error("Syscall signature", repr(syscall), "without a syscall number before line ", lineno) syscall = m.group(1) continue # Import Needed for the System Call m = import_re.fullmatch(line) if m: if syscall is None: error("Import without a syscall signature on line", lineno) imports[m.group(1)] = m.group(2) continue # System Call Number, Concludes System Call Info m = syscall_num_re.fullmatch(line) if m: if syscall is None: error("Syscall number without a syscall signature on line", lineno) syscalls[int(m.group(1))] = syscall syscall = None continue # Error Translation =========================================================== # Get Existing Error Codes # Do this to make sure error value are the same between runs. error_code_re = re.compile(r' (\w+) = (\d+),') in_error_code = False all_error_codes = {} max_error_code = 0 with interface_file.open('r') as f: for i, line in enumerate(f): lineno = i + 1 if in_error_code: m = error_code_re.search(line) if m: ec = int(m.group(2)) all_error_codes[m.group(1)] = ec max_error_code = max(max_error_code, ec) elif line == '};\n': break elif line == 'const ErrorCode = enum(u32) {\n': in_error_code = True # Get Errors Used by System Calls error_types = {} for call in syscalls.values(): error_type = decompose_sig(call)[4] if error_type: error_types[error_type] = [] # Get all the error values/codes of the error types used by the system calls. syscall_error_values_file.parent.mkdir(parents=True, exist_ok=True) for error_type in error_types: with syscall_error_values_file.open('w') as f: print('''\ const std = @import("std"); const georgios = @import("georgios"); pub fn main() !void { const stdout = std.io.getStdOut().writer(); for (@typeInfo(''' + error_type + ''').ErrorSet.?) |field| { try stdout.print("{s}\\n", .{field.name}); } } ''', file=f) error_codes = [s for s in check_output([ 'zig', 'run', '--pkg-begin', 'georgios', 'libs/georgios/georgios.zig', '--pkg-begin', 'utils', 'libs/utils/utils.zig', str(syscall_error_values_file), '--pkg-end', '--pkg-end']).decode('utf-8').split('\n') if s] error_types[error_type] = error_codes for error_code in error_codes: if error_code not in all_error_codes: max_error_code += 1 all_error_codes[error_code] = max_error_code # Print Debug Info ============================================================ if int_num is None: error("Didn't find interrupt number") if debug: log('System Call Interrupt Number:', int_num) if len(syscall_regs) == 0: error("No registers found!") if debug: for num, reg in syscall_regs.items(): log('Arg {} is reg %{}'.format(num, reg)) if len(syscalls) == 0: error("No system calls found!") if debug: for pair in imports.items(): log('Import', *pair) # Write Interface File ======================================================== with interface_file.open('w') as f: print('''\ // Generated by scripts/codegen/generate_system_calls.py from // kernel/platform/system_calls.zig. See system_calls.zig for more info. ''', file=f) for pair in imports.items(): print('const {} = @import("{}");'.format(*pair), file=f) print('const ErrorCode = enum(u32) {', file=f) for name, value in all_error_codes.items(): print(' {} = {},'.format(name, value), file=f) print('''\ _, }; pub fn ValueOrError(comptime ValueType: type, comptime ErrorType: type) type { return union (enum) { const Self = @This(); value: ValueType, error_code: ErrorCode, pub fn set_value(self: *Self, value: ValueType) void { self.* = Self{.value = value}; } pub fn set_error(self: *Self, err: ErrorType) void { self.* = Self{.error_code = switch (ErrorType) {''', file=f) for error_type, error_values in error_types.items(): print(' {} => switch (err) {{'.format(error_type), file=f) for error_value in error_values: print(' {0}.{1} => ErrorCode.{1},'.format( error_type, error_value), file=f) print(' },', file=f) print('''\ else => @compileError( "Invalid ErrorType for " ++ @typeName(Self) ++ ".set_error: " ++ @typeName(ErrorType)), }}; } pub fn get(self: *const Self) ErrorType!ValueType { return switch (self.*) { Self.value => |value| return value, Self.error_code => |error_code| switch (ErrorType) {''', file=f) for error_type, error_values in error_types.items(): print(' {} => switch (error_code) {{'.format(error_type), file=f) for error_value in error_values: print(' .{0} => {1}.{0},'.format( error_value, error_type), file=f) print(' {} => georgios.BasicError.Unknown,'.format( '_' if len(error_values) == len(all_error_codes) else 'else'), file=f) print(' },', file=f) print('''\ else => @compileError( "Invalid ErrorType for " ++ @typeName(Self) ++ ".get: " ++ @typeName(ErrorType)), }, }; } }; } ''', file=f) for num, sig in syscalls.items(): name, args, return_name, return_type, error_return, value_return = decompose_sig(sig) args = args.split(', ') if len(args) == 1 and args[0] == '': args = [] if debug: log(num, '=>', repr(name), 'args', args, 'return', repr(return_name), ': ', repr(return_type)) noreturn = return_type == 'noreturn' has_return = not (return_type == 'void' or noreturn) return_expr = return_name if error_return: internal_return_type = 'ValueOrError({}, {})'.format(value_return, error_return) return_expr += '.get()' else: internal_return_type = return_type required_regs = len(args) + 1 if has_return else 0 avail_regs = len(syscall_regs) if required_regs > avail_regs: error('System call {} requires {} registers, but the max is {}'.format( repr(sig), required_regs, avail_regs)) print('\npub fn {}({}) callconv(.Inline) {} {{'.format( name, ', '.join([a[1:] if a.startswith('&') else a for a in args]), return_type), file=f) return_value = '' if has_return: print(' var {}: {} = undefined;'.format( return_name, internal_return_type), file=f) print(( ' asm volatile ("int ${}" ::\n' + ' [syscall_number] "{{eax}}" (@as(u32, {})),' ).format(int_num, num), file=f) arg_num = 1 def add_arg(arg_num , what): if ':' in what: what = what.split(':')[0] if what.startswith('&'): what = '@ptrToInt(' + what + ')' if arg_num >= len(syscall_regs): error('System call {} has too many arguments'.format(repr(sig))) print(' [arg{}] "{{{}}}" ({}),'.format( arg_num, syscall_regs[arg_num], what), file=f) return arg_num + 1 for arg in args: arg_num = add_arg(arg_num, arg) if has_return: arg_num = add_arg(arg_num, '&' + return_name) print( ' );', file=f) if has_return: print(' return {};'.format(return_expr), file=f) elif noreturn: print(' unreachable;', file=f) print('}', file=f)
0
repos/georgios/scripts
repos/georgios/scripts/codegen/constant_guids.py
# Generate Guid constants, right now just for gpt.zig. def bytearr(guid): s = guid.replace('-', '') return ', '.join(['0x' + s[i] + s[i + 1] for i in range(0, len(s), 2)]) def make_guid(name, guid, f): print("pub const {} = Guid{{.data= // {}\n [_]u8{{{}}}}};".format( name, guid, bytearr(guid)), file=f) guids = [ ("nil", "00000000-0000-0000-0000-000000000000"), ("linux_partition_type", "0fc63daf-8483-4772-8e79-3d69d8477de4"), ] with open('kernel/constant_guids.zig', 'w') as f: print('// Generated by scripts/codegen/constant_guids.py\n', file=f) print('const Guid = @import("utils").Guid;', file=f) for (guid, name) in guids: make_guid(guid, name, f)
0
repos/georgios/scripts
repos/georgios/scripts/codegen/keys.py
# ============================================================================= # Script for generating kernel/keys.zig and libs/georgios/keys.zig # ============================================================================= import string def k(name, char): return ('Key_' + name, 'null' if char is None else '\'' + char + '\'') keys = [] # Letters and Numbers keys.extend([k(c, c) for c in string.ascii_lowercase]) keys.extend([k(c, c) for c in string.ascii_uppercase]) keys.extend([k(c, c) for c in string.digits]) keys.extend([k('Keypad' + c, c) for c in string.digits]) # Keys with Printable Symbols keys.extend([k(*pair) for pair in [ ('Enter', '\\n'), ('KeypadEnter', '\\n'), ('Tab', '\\t'), ('Backspace', '\\x08'), ('Space', ' '), ('Slash', '/'), ('KeypadSlash', '/'), ('Backslash', '\\\\'), ('Period', '.'), ('KeypadPeriod', '.'), ('Question', '?'), ('Exclamation', '!'), ('Comma', ','), ('Colon', ':'), ('SemiColon', ';'), ('BackTick', '`'), ('SingleQuote', '\\\''), ('DoubleQuote', '"'), ('Asterisk', '*'), ('KeypadAsterisk', '*'), ('At', '@'), ('Ampersand', '&'), ('Percent', '%'), ('Caret', '^'), ('Pipe', '|'), ('Tilde', '~'), ('Underscore', '_'), ('Pound', '#'), ('Dollar', '$'), ('Plus', '+'), ('KeypadPlus', '+'), ('Minus', '-'), ('KeypadMinus', '-'), ('Equals', '='), ('GreaterThan', '>'), ('LessThan', '<'), ('LeftBrace', '{'), ('RightBrace', '}'), ('LeftSquareBracket', '['), ('RightSquareBracket', ']'), ('LeftParentheses', '('), ('RightParentheses', ')'), ]]) # Keys with no Printable Symbols keys.extend([k(name, None) for name in [ 'Escape', 'LeftShift', 'RightShift', 'LeftAlt', 'RightAlt', 'LeftControl', 'RightControl', 'CapsLock', 'NumberLock', 'ScrollLock', 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12', 'CursorLeft', 'CursorRight', 'CursorUp', 'CursorDown', 'PageUp', 'PageDown', 'AcpiPower', 'AcpiSleep', 'AcpiWake', 'Home', 'End', 'Insert', 'Delete', 'PrintScreen', 'Pause', ]]) # Generate Key Definitions with open('libs/georgios/keys.zig', 'w') as f: print('''\ // Generated by scripts/codegen/keys.py pub const Key = enum {''', file=f) for pair in keys: print(' ' + pair[0] + ',', file=f) print('};', file=f) # Generate Key to Character Function with open('kernel/keys.zig', 'w') as f: print('''\ // Generated by scripts/codegen/keys.py const Key = @import("georgios").keyboard.Key; pub fn key_to_char(key: Key) ?u8 { return chars_table[@enumToInt(key)]; } const chars_table = [_]?u8 {''', file=f) for pair in keys: print(' ' + pair[1] + ',', file=f) print('};', file=f)
0
repos/georgios/scripts
repos/georgios/scripts/prototypes/buddy.py
# Based on http://bitsquid.blogspot.com/2015/08/allocation-adventures-3-buddy-allocator.html import math from enum import Enum def align_down(value, by): return value & (~by + 1) def align_up(value, by): return align_down(value + by - 1, by) # Get next power of two if the value is not one. def pot(value): if value >= (1 << 32): raise ValueError value -= 1 value |= value >> 1 value |= value >> 2 value |= value >> 4 value |= value >> 8 value |= value >> 16 value += 1 return value class Memory: def __init__(self, size, start = 0): self.size = size self.start = start self.end = start + size self.contents = [None] * size def get(self, address): if address >= self.end: raise ValueError("Tried to get invalid address " + str(address)) value = self.contents[address - self.start] if value is None: raise ValueError("Tried to get uninitialized address " + str(address)) return value def set(self, address, value): if address >= self.end: raise ValueError("Tried to set invalid address " + str(address)) self.contents[address - self.start] = value def __repr__(self): rv = [] for value in self.contents: if value is None: rv.append('.') elif value is nil: rv.append('N') else: rv.append(str(value)) return ' '.join(rv) nil=(None,) class BlockStatus(Enum): invalid = 0 split = 1 free = 2 used = 3 def __repr__(self): if self == self.invalid: return 'I' if self == self.split: return 'S' if self == self.free: return 'F' if self == self.used: return 'U' return super().__repr__() # Example # # size = 32 # min_size = 4 # # Index by Level # # 0 | 0 | # 1 | 0 | 1 | # 2 | 0 | 1 | 2 | 3 | # 3 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | # |...|...|...|...|...|...|...|...| # 0 4 8 12 16 20 24 28 32 # # max_level_block_count = 32 / 4 = 8 # level_count = 4 # # Unique Id # # 0 | 0 | # 1 | 1 | 2 | # 2 | 3 | 4 | 5 | 6 | # 3 | 7 | 8 | 9 | 10| 11| 12| 13| 14| # |...|...|...|...|...|...|...|...| # 0 4 8 12 16 20 24 28 32 # # unique_block_count = 15 class OutOfMemory(Exception): pass class WrongBlockStatus(Exception): pass class InvalidPointer(Exception): pass class Buddy: def __init__(self, start, size): self.start = start self.size = size self.min_size = 4 self.max_level_block_count = self.size // self.min_size self.level_count = int(math.log2(self.max_level_block_count)) + 1 self.unique_block_count = (1 << self.level_count) - 1 # Simulated Memory Range to Control self.memory = Memory(size, start) # Intitialze Free List self.free_lists = Memory(self.level_count + 1) self.free_lists.set(0, start) for i in range(1, self.free_lists.size): self.free_lists.set(i, nil) self.set_prev_pointer(start, nil) self.set_next_pointer(start, nil) # Intitialze Block Statuses self.block_statuses = [BlockStatus.invalid] * self.unique_block_count self.block_statuses[0] = BlockStatus.free def get_free_list_pointer(self, address): if self.memory.get(address): return self.memory.get(address + 1) else: return nil def set_free_list_pointer(self, address, value): if value is nil: optional_value = 0 else: optional_value = 1 self.memory.set(address + 1, value) self.memory.set(address, optional_value) prev_offset = 0 def get_prev_pointer(self, address): return self.get_free_list_pointer(address + self.prev_offset) def set_prev_pointer(self, address, value): return self.set_free_list_pointer(address + self.prev_offset, value) next_offset = 2 def get_next_pointer(self, address): return self.get_free_list_pointer(address + self.next_offset) def set_next_pointer(self, address, value): return self.set_free_list_pointer(address + self.next_offset, value) def level_to_block_size(self, level): return self.size // (1 << level) def block_size_to_level(self, size): return self.level_count + 1 - int(math.log2(size)) @staticmethod def unique_id(level, index): return (1 << level) + index - 1 def get_unique_id(self, level, index, expected_status): unique_id = self.unique_id(level, index) status = self.block_statuses[unique_id] if status != expected_status: raise WrongBlockStatus( "unique id {} (level {}, index {}) was expected to be {}, not {}".format( unique_id, level, index, expected_status, status)) return unique_id def get_index(self, level, address): return (address - self.start) // self.level_to_block_size(level) def get_pointer(self, level, index): return index * self.level_to_block_size(level) + self.start @staticmethod def get_buddy_index(index): return index - 1 if index % 2 else index + 1 # Remove block from double linked list def remove_block(self, level, ptr): old_prev = self.get_prev_pointer(ptr) old_next = self.get_next_pointer(ptr) if old_prev is nil: self.free_lists.set(level, old_next) else: self.set_next_pointer(old_prev, old_next) if old_next is not nil: self.set_prev_pointer(old_next, old_prev) def split(self, level, index): print(' - split', level, index) this_unique_id = self.get_unique_id(level, index, BlockStatus.free) this_ptr = self.get_pointer(level, index) new_level = level + 1 new_index = index * 2 buddy_index = new_index + 1 buddy_ptr = self.get_pointer(new_level, buddy_index) self.remove_block(level, this_ptr) # Update New Pointer to This buddy_next = self.free_lists.get(new_level) self.free_lists.set(new_level, this_ptr) # Set Our Pointers self.set_prev_pointer(this_ptr, nil) self.set_next_pointer(this_ptr, buddy_ptr) self.set_prev_pointer(buddy_ptr, this_ptr) self.set_next_pointer(buddy_ptr, buddy_next) # Update Pointers to Buddy if buddy_next is not nil: self.set_prev_pointer(buddy_next, buddy_ptr) # Update Statuses self.block_statuses[this_unique_id] = BlockStatus.split self.block_statuses[self.unique_id(new_level, new_index)] = BlockStatus.free self.block_statuses[self.unique_id(new_level, buddy_index)] = BlockStatus.free def alloc(self, size): if size < self.min_size: raise ValueError( "Asked for size smaller than what the alloctor supports: " + size) if size > self.size: raise ValueError( "Asked for size greater than what the alloctor supports: " + size) target_size = pot(size) target_level = self.block_size_to_level(target_size) print(' - alloc(', size, '), Target Size:', target_size, 'Target Level:', target_level) # Figure out how many (if any) levels we need to split a block in to # get a free block in our target level. address = nil level = target_level while True: address = self.free_lists.get(level) print(' - split_loop: free list level', level, ':', address) if address is nil: if level == 0: print(' - split_loop: reached level 0, no room!') raise OutOfMemory() level -= 1 else: break # If we need to split blocks, do that if level != target_level: for i in range(level, target_level): self.split(i, self.get_index(i, address)) address = self.free_lists.get(i + 1) if address is nil: raise ValueError('nil in split loop!') # Reserve it self.remove_block(target_level, address) index = self.get_index(target_level, address) unique_id = self.unique_id(target_level, index) self.block_statuses[unique_id] = BlockStatus.used print(" - Got", address) print(repr(self)) return address def merge(self, level, index): if level == 0: raise ValueError('merge() was pased level 0') print(' - merge', level, index) buddy_index = self.get_buddy_index(index) new_level = level - 1 new_index = index // 2 # Assert existing blocks are free and new/parrent block is split this_unique_id = self.get_unique_id(level, index, BlockStatus.free) buddy_unique_id = self.get_unique_id(level, buddy_index, BlockStatus.free) new_unique_id = self.get_unique_id(new_level, new_index, BlockStatus.split) # Remove pointers to the old blocks this_ptr = self.get_pointer(level, index) buddy_ptr = self.get_pointer(level, buddy_index) self.remove_block(level, this_ptr) self.remove_block(level, buddy_ptr) # Set new pointers to and from the new block new_this_ptr = self.get_pointer(new_level, new_index) self.set_next_pointer(new_this_ptr, self.free_lists.get(new_level)) self.free_lists.set(new_level, new_this_ptr) self.set_prev_pointer(new_this_ptr, nil) # Set New Statuses self.block_statuses[this_unique_id] = BlockStatus.invalid self.block_statuses[buddy_unique_id] = BlockStatus.invalid self.block_statuses[new_unique_id] = BlockStatus.free def free(self, address): found = False print(" - free(", address, ')') for level in range(self.level_count - 1, -1, -1): index = self.get_index(level, address) try: unique_id = self.get_unique_id(level, index, BlockStatus.used) found = True break except WrongBlockStatus: continue if not found: raise InvalidPointer() print(" - level:", level, "index:", index, "unique id:", unique_id) # Insert Block into List and Mark as Free next_ptr = self.free_lists.get(level) if next_ptr is not nil: self.set_prev_pointer(next_ptr, address) self.free_lists.set(level, address) self.set_prev_pointer(address, nil) self.set_next_pointer(address, next_ptr) self.block_statuses[unique_id] = BlockStatus.free # Merge Until Buddy isn't Free or Level Is 0 for level in range(level, 0, -1): buddy_index = self.get_buddy_index(index) buddy_unique_id = self.unique_id(level, buddy_index) buddy_status = self.block_statuses[buddy_unique_id] print(" - merge level", level, "index", index, "uid", buddy_unique_id, "status", buddy_status) if buddy_status == BlockStatus.free: self.merge(level, index) index >>= 1; else: break print(repr(self)) def __repr__(self): return 'free_lists: {}\nmemory: {}\nstatuses: {}'.format( repr(self.free_lists), repr(self.memory), repr(self.block_statuses)) def buddy_test(start): try: b = Buddy(start, 32) print(repr(b)) b.alloc(4) b.alloc(4) b.alloc(4) b.alloc(4) b.alloc(4) b.alloc(4) b.alloc(4) b.alloc(4) try: b.alloc(4) assert(False) except OutOfMemory: pass except: print('State At Error:', repr(b)) raise try: b = Buddy(start, 32) print(repr(b)) p = b.alloc(4) b.free(p) except: print('State At Error:', repr(b)) raise try: b = Buddy(start, 32) print(repr(b)) p1 = b.alloc(8) p2 = b.alloc(4) p3 = b.alloc(16) b.free(p2) p4 = b.alloc(8) b.free(p3) b.free(p4) b.free(p1) except: print('State At Error:', repr(b)) raise try: b = Buddy(start, 32) print(repr(b)) p = b.alloc(16) b.free(p) try: b.free(p) assert(False) except InvalidPointer: print('Caught Expected InvalidPointer') except: print('State At Error:', repr(b)) raise buddy_test(0) buddy_test(1) buddy_test(7) buddy_test(8) buddy_test(127) try: b = Buddy(0, 128) print(repr(b)) b.alloc(64) except: print('State At Error:', repr(b)) raise
0
repos/georgios/scripts
repos/georgios/scripts/prototypes/bmp.py
# This is to figure out the "bottom-up" bitmap buffered reading for bmp files class Bmp: def __init__(self): self.pos = 0 self.width = 4 self.height = 3 self.bmp_data = [ 8, 9, 10, 11, 4, 5, 6, 7, 0, 1, 2, 3, ] self.len = len(self.bmp_data) self.read_pos = 0 def read(self, buffer, start, end): count = min(end - start, self.len - self.read_pos) for i, byte in enumerate(self.bmp_data[self.read_pos:self.read_pos + count]): buffer[start + i] = byte self.read_pos += count return count def seek(self, pos): self.read_pos = pos def read_bitmap(self, buffer): got = 0 while got < len(buffer) and self.pos < self.len: row = self.pos // self.width col = self.pos % self.width seek_to = self.len - self.width * (row + 1) + col count = min(self.width - col, len(buffer) - got) print('pos =', self.pos, 'row =', row, 'col =', col, 'seek_to =', seek_to, 'count =', count) self.seek(seek_to) assert count == self.read(buffer, got, got + count) got += count self.pos += count return got bmp = Bmp() print(bmp.bmp_data) buffer = [0xaa] * 5 print(buffer[0:bmp.read_bitmap(buffer)]) print(buffer[0:bmp.read_bitmap(buffer)]) print(buffer[0:bmp.read_bitmap(buffer)])
0
repos/georgios
repos/georgios/programs/linking.ld
ENTRY(_start) _PAGE_SIZE = 4K; SECTIONS { /* space for a null and friends to trigger protection */ . = ALIGN(1M); .text : ALIGN(_PAGE_SIZE) { *(.text) } .data : ALIGN(_PAGE_SIZE) { *(.data) } .bss : ALIGN(_PAGE_SIZE) { *(.bss) *(COMMON) } _end = ALIGN(_PAGE_SIZE); }
0
repos/georgios/programs
repos/georgios/programs/ed/ed.zig
const std = @import("std"); const georgios = @import("georgios"); comptime {_ = georgios;} const syscalls = georgios.system_calls; const utils = georgios.utils; const streq = utils.memory_compare; const console = georgios.get_console_writer(); const no_max = std.math.maxInt(usize); pub fn panic(msg: []const u8, trace: ?*std.builtin.StackTrace) noreturn { georgios.panic(msg, trace); } var alloc: std.mem.Allocator = undefined; var input_buffer: [256]u8 = undefined; var running = true; var current_line: usize = 1; var path: ?[]u8 = null; var buffer: utils.List([]u8) = undefined; fn get_line(num: usize) ?[]u8 { if (num == 0) return null; var it = buffer.iterator(); var current: usize = 1; while (it.next()) |line| { if (num == current) return line; current += 1; } return null; } fn write_file() !void { if (path == null) { try console.print("No path set\n", .{}); } var file = try georgios.fs.open(path.?, .{.Write = .{.truncate = true}}); defer file.close() catch unreachable; _ = try file.seek(0, .FromStart); var it = buffer.iterator(); while (it.next()) |line| { _ = try file.write_or_error(line); _ = try file.write_or_error("\n"); } } fn read_file() !void { if (path == null) { try console.print("No path set\n", .{}); } var file = try georgios.fs.open(path.?, .{.ReadOnly = .{}}); defer file.close() catch unreachable; var reader = file.reader(); current_line = 0; while (try reader.readUntilDelimiterOrEofAlloc(alloc, '\n', no_max)) |line| { try buffer.push_back(line); current_line += 1; } if (current_line == 0) { current_line = 1; } } fn get_input(prompt: bool) ?[]const u8 { if (prompt) { try console.print(":", .{}); } var got: usize = 0; while (true) { const key_event = syscalls.get_key(.Blocking).?; if (key_event.char) |c| { if (key_event.modifiers.control_is_pressed()) { switch (c) { 'd' => return null, else => {}, } } var print = true; if (c == '\n') { try console.print("\n", .{}); break; } else if (c == '\x08') { if (got > 0) { got -= 1; } else { print = false; } } else if ((got + 1) == input_buffer.len) { print = false; } else { input_buffer[got] = c; got += 1; } if (print) { try console.print("{c}", .{c}); } } } return input_buffer[0..got]; } pub fn main() !u8 { if (georgios.proc_info.args.len != 1) { return 1; } var arena = std.heap.ArenaAllocator.init(georgios.page_allocator); alloc = arena.allocator(); defer arena.deinit(); path = try alloc.dupe(u8, georgios.proc_info.args[0]); buffer = .{.alloc = alloc}; read_file() catch |e| { try console.print("Could not open {s}: {s}\n", .{path, @errorName(e)}); }; var append = false; while (get_input(!append)) |input| { if (append) { try buffer.push_back(try alloc.dupe(u8, input)); append = false; } else { if (streq(input, "a")) { append = true; continue; } else if (streq(input, "q")) { break; } else if (streq(input, "w")) { try write_file(); continue; } else if (streq(input, ",")) { if (get_line(current_line)) |line| { try console.print("{s}\n", .{line}); } else { current_line = 1; } continue; } else if (streq(input, ",p")) { var it = buffer.iterator(); while (it.next()) |line| { try console.print("{s}\n", .{line}); } continue; } const line_no = std.fmt.parseUnsigned(usize, input, 10) catch { try console.print("Invalid command: {s}\n", .{input}); continue; }; if (get_line(line_no)) |line| { current_line = line_no; try console.print("{s}\n", .{line}); } else { try console.print("Invalid line: {s}\n", .{input}); } } } return 0; }
0
repos/georgios/programs
repos/georgios/programs/test-prog/test-prog.zig
const std = @import("std"); const georgios = @import("georgios"); comptime {_ = georgios;} const streq = georgios.utils.memory_compare; const system_calls = georgios.system_calls; const console = georgios.get_console_writer(); extern var _end: u32; pub fn main() !u8 { var exit_with = false; for (georgios.proc_info.args) |arg| { if (exit_with) { var status: u8 = 1; if (std.fmt.parseUnsigned(u8, arg, 10)) |int| { status = int; } else |err| { try console.print("Invalid exit-with value \"{s}\": {s}\n", .{arg, @errorName(err)}); } return status; } else if (streq(arg, "exit-with")) { exit_with = true; } else if (streq(arg, "panic")) { @panic("Panic was requested"); } else if (streq(arg, "kpanic")) { // Try to invoke an interrupt that's only for the kernel. asm volatile ("int $50"); } else if (streq(arg, "kcode")) { // Try to run code in kernel space asm volatile ( \\pushl $0xc013bef0 \\ret ); } else if (streq(arg, "koverflow")) { system_calls.overflow_kernel_stack(); } else if (streq(arg, "mem")) { try console.print("_end = {x}\n", .{@ptrToInt(&_end)}); _ = try system_calls.add_dynamic_memory(4); _end = 10; } else if (streq(arg, "mem-segfault")) { try console.print("_end = {x}\n", .{@ptrToInt(&_end)}); _end = 10; } else if (streq(arg, "mem-fail")) { _ = try system_calls.add_dynamic_memory(std.math.maxInt(usize)); } else if (streq(arg, "mem-fill")) { // TODO: Figure out why this fails with missing page after a while. try console.print("_end = {x}\n", .{@ptrToInt(&_end)}); while (true) { const area = try system_calls.add_dynamic_memory(4096); const end = @ptrToInt(area.ptr) + area.len; try console.print("{x}\n", .{end}); @intToPtr(*u8, end - 1).* = 0xff; } } else { try console.print("Invalid argument: {s}\n", .{arg}); return 1; } } return 0; }
0
repos/georgios/programs
repos/georgios/programs/hello/hello.zig
const georgios = @import("georgios"); comptime {_ = georgios;} const system_calls = georgios.system_calls; const print_string = system_calls.print_string; const print_uint = system_calls.print_uint; pub fn main() void { print_string("program path is "); print_string(georgios.proc_info.path); print_string("\nprogram name is "); print_string(georgios.proc_info.name); print_string("\n"); print_uint(georgios.proc_info.args.len, 10); print_string(" args\n"); for (georgios.proc_info.args) |arg| { print_string("arg: \""); print_string(arg); print_string("\"\n"); } print_string("Hello, World!\n"); }
0
repos/georgios/programs
repos/georgios/programs/cksum/cksum.zig
// Implementation of POSIX cksum. See Cksum module for details. const georgios = @import("georgios"); comptime {_ = georgios;} const Cksum = georgios.utils.Cksum; const system_calls = georgios.system_calls; const print_string = system_calls.print_string; var buffer: [2048]u8 = undefined; fn print_result(filename: []const u8, cksum: *Cksum) !void { var ts = georgios.utils.ToString{.buffer = buffer[0..]}; try ts.uint(cksum.get_result()); try ts.char(' '); try ts.uint(cksum.total_size); try ts.char(' '); try ts.string(filename); try ts.char('\n'); print_string(ts.get()); } pub fn main() u8 { for (georgios.proc_info.args) |arg| { var cksum = georgios.utils.Cksum{}; var file = georgios.fs.open(arg, .{.ReadOnly = .{}}) catch |e| { print_string("cksum: open error: "); print_string(@errorName(e)); print_string("\n"); return 1; }; var got: usize = 1; while (got > 0) { if (file.read(buffer[0..])) |g| { got = g; } else |e| { print_string("cksum: file.read error: "); print_string(@errorName(e)); print_string("\n"); return 1; } if (got > 0) { cksum.sum_bytes(buffer[0..got]); } } print_result(arg, &cksum) catch |e| { print_string("cksum: failed to print result: "); print_string(@errorName(e)); print_string("\n"); return 1; }; file.close() catch |e| { print_string("cksum: file.close error: "); print_string(@errorName(e)); print_string("\n"); return 1; }; } return 0; }
0
repos/georgios/programs
repos/georgios/programs/unlink/unlink.zig
const georgios = @import("georgios"); comptime {_ = georgios;} const console = georgios.get_console_writer(); pub fn main() u8 { for (georgios.proc_info.args) |path| { var dir = georgios.Directory{._port_id = georgios.MetaPort}; dir.unlink(path) catch |e| { try console.print("unlink: error: {s}\n", .{@errorName(e)}); return 1; }; } return 0; }
0
repos/georgios/programs
repos/georgios/programs/check-test-file/check-test-file.zig
const std = @import("std"); const georgios = @import("georgios"); comptime {_ = georgios;} const system_calls = georgios.system_calls; const print_string = system_calls.print_string; const IntType = u32; const total_size: usize = 1048576; const total_int_count = total_size / @sizeOf(IntType); var status: u8 = 0; var msg_buffer: [128]u8 = undefined; var streak_start: usize = 0; var streak_size: usize = 0; var total_invalid: usize = 0; fn streak() !void { if (streak_size > 0) { var ts = georgios.utils.ToString{.buffer = msg_buffer[0..]}; try ts.string("At "); try ts.uint(streak_start); try ts.string(" got "); try ts.uint(streak_size); try ts.string(" invalid bytes\n"); print_string(ts.get()); total_invalid += streak_size; streak_size = 0; streak_start = 0; status = 1; } } pub fn main() u8 { var file = georgios.fs.open("files/test-file", .{.ReadOnly = .{}}) catch |e| { print_string("open error: "); print_string(@errorName(e)); print_string("\nNOTE: test-file has to be generated using scripts/gen-test-file.py\n"); print_string("After that remove disk.img and rebuild\n"); return 1; }; var pos: usize = 0; var got: usize = 1; const buffer_size: usize = 1024; var buffer: [buffer_size]u8 = undefined; var expected_int: IntType = 0; var last_unexpected_int: IntType = 0; while (got > 0) { if (file.read(buffer[0..])) |g| { got = g; if (got == 0) break; if (got % @sizeOf(IntType) != 0) { var ts = georgios.utils.ToString{.buffer = msg_buffer[0..]}; ts.string("At ") catch unreachable; ts.uint(pos) catch unreachable; ts.string(" got invalid number of bytes: ") catch unreachable; ts.uint(got) catch unreachable; ts.char('\n') catch unreachable; print_string(ts.get()); status = 1; break; } const ints = std.mem.bytesAsSlice(u32, buffer[0..got]); for (ints) |int| { if (expected_int != int) { if (int != (last_unexpected_int + 1)) { var ts = georgios.utils.ToString{.buffer = msg_buffer[0..]}; ts.string("At ") catch unreachable; ts.uint(pos) catch unreachable; ts.string(" got ") catch unreachable; ts.uint(int) catch unreachable; ts.string(" expected ") catch unreachable; ts.uint(expected_int) catch unreachable; ts.char('\n') catch unreachable; print_string(ts.get()); status = 1; } else { print_string("."); } last_unexpected_int = int; if (streak_size == 0) { streak_start = pos; } streak_size += @sizeOf(IntType); } else if (streak_size > 0) { streak() catch |e| { print_string("streak error: "); print_string(@errorName(e)); print_string("\n"); return 1; }; } pos += @sizeOf(IntType); expected_int += 1; } } else |e| { print_string("file.read error: "); print_string(@errorName(e)); print_string("\n"); got = 0; return 1; } } streak() catch |e| { print_string("streak error: "); print_string(@errorName(e)); print_string("\n"); return 1; }; { var ts = georgios.utils.ToString{.buffer = msg_buffer[0..]}; ts.uint(total_invalid) catch unreachable; ts.string(" out of ") catch unreachable; ts.uint(total_size) catch unreachable; ts.string(" bytes were invalid\n") catch unreachable; print_string(ts.get()); status = 1; } if (pos != total_size) { var ts = georgios.utils.ToString{.buffer = msg_buffer[0..]}; ts.string("Expected ") catch unreachable; ts.uint(total_size) catch unreachable; ts.string(" bytes, but got ") catch unreachable; ts.uint(pos) catch unreachable; ts.string(" bytes\n") catch unreachable; print_string(ts.get()); status = 1; } file.close() catch |e| { print_string("file.close error: "); print_string(@errorName(e)); print_string("\n"); status = 1; }; return status; }
0
repos/georgios/programs
repos/georgios/programs/mkdir/mkdir.zig
const georgios = @import("georgios"); comptime {_ = georgios;} const console = georgios.get_console_writer(); pub fn main() u8 { for (georgios.proc_info.args) |path| { var dir = georgios.Directory{._port_id = georgios.MetaPort}; dir.create(path, .{.directory = true}) catch |e| { try console.print("mkdir: error: {s}\n", .{@errorName(e)}); return 1; }; } return 0; }
0
repos/georgios/programs
repos/georgios/programs/ls/ls.zig
const georgios = @import("georgios"); comptime {_ = georgios;} const console = georgios.get_console_writer(); pub fn main() u8 { var path: []const u8 = "."; if (georgios.proc_info.args.len > 0) { path = georgios.proc_info.args[0]; } var dir_file = georgios.fs.open(path, .{.ReadOnly = .{.dir = true}}) catch |e| { try console.print("ls: open error: {s}\n", .{@errorName(e)}); return 1; }; defer dir_file.close() catch unreachable; var entry_buffer: [256]u8 = undefined; while (true) { const read = dir_file.read(entry_buffer[0..]) catch |e| { try console.print("ls: read error: {s}\n", .{@errorName(e)}); return 1; }; if (read == 0) break; try console.print("{s}\n", .{entry_buffer[0..read]}); } return 0; }
0
repos/georgios/programs
repos/georgios/programs/shell/shell.zig
const std = @import("std"); const georgios = @import("georgios"); comptime {_ = georgios;} const system_calls = georgios.system_calls; const utils = georgios.utils; const streq = utils.memory_compare; const TinyishLisp = @import("TinyishLisp"); const Expr = TinyishLisp.Expr; const print_string = system_calls.print_string; const print_uint = system_calls.print_uint; pub fn panic(msg: []const u8, trace: ?*std.builtin.StackTrace) noreturn { georgios.panic(msg, trace); } const segment_start = "░▒▓"; const segment_end = "▓▒░"; const esc = "\x1b"; const reset_console = esc ++ "c"; const ansi_esc = esc ++ "["; const invert_colors = ansi_esc ++ "7m"; const reset_colors = ansi_esc ++ "39;49m"; const no_max = std.math.maxInt(usize); var alloc: std.mem.Allocator = undefined; var tl: TinyishLisp = undefined; var custom_commands: std.StringHashMap(*Expr) = undefined; var console = georgios.get_console_writer(); var generic_console_impl = utils.GenericWriterImpl(georgios.ConsoleWriter.Writer){}; var generic_console: utils.GenericWriter.Writer = undefined; fn check_bin_path(path: []const u8, name: []const u8, buffer: []u8) ?[]const u8 { var dir_file = georgios.fs.open(path, .{.ReadOnly = .{.dir = true}}) catch |e| { try console.print("shell: check_bin_path open error: {s}\n", .{@errorName(e)}); return null; }; defer dir_file.close() catch unreachable; var pos = utils.memory_copy_truncate(buffer[0..], name); pos = pos + utils.memory_copy_truncate(buffer[pos..], ".elf"); var entry_buffer: [256]u8 = undefined; while (true) { const read = dir_file.read(entry_buffer[0..]) catch |e| { try console.print("shell: check_bin_path read error: {s}\n", .{@errorName(e)}); return null; }; if (read == 0) break; const entry = entry_buffer[0..read]; if (streq(entry, buffer[0..pos])) { pos = 0; pos = utils.memory_copy_truncate(buffer, path); pos = pos + utils.memory_copy_truncate(buffer[pos..], "/"); pos = pos + utils.memory_copy_truncate(buffer[pos..], entry); return buffer[0..pos]; } } return null; } var cwd_buffer: [128]u8 = undefined; var command_parts: [32][]const u8 = undefined; const max_command_len = 128; var command_buffer: [max_command_len]u8 = undefined; var processed_command_buffer: [max_command_len]u8 = undefined; fn run_command(command: []const u8) bool { // Turn command into command_parts var it = georgios.utils.WordIterator{ .quote = '\'', .input = command, .buffer = processed_command_buffer[0..], }; var processed_command_buffer_offset: usize = 0; var command_part_count: usize = 0; while (it.next() catch @panic("command iter failure")) |part| { command_parts[command_part_count] = part; command_part_count += 1; processed_command_buffer_offset += part.len; it.buffer = processed_command_buffer[processed_command_buffer_offset..]; } if (command_part_count == 0) { return false; } // Process command_parts if (streq(command_parts[0], "exit")) { return true; } else if (streq(command_parts[0], "reset")) { _ = try console.write(reset_console); } else if (streq(command_parts[0], "pwd")) { if (system_calls.get_cwd(cwd_buffer[0..])) |dir| { try console.print("{s}\n", .{dir}); } else |e| { try console.print("Couldn't get current working directory: {s}\n", .{@errorName(e)}); } } else if (streq(command_parts[0], "cd")) { if (command_part_count != 2) { _ = try console.write("cd requires exactly one argument\n"); } else { system_calls.set_cwd(command_parts[1]) catch |e| { try console.print("Couldn't change current working directory to \"{s}\": {s}\n", .{command_parts[1], @errorName(e)}); }; } } else if (streq(command_parts[0], "sleep")) { if (command_part_count != 2) { _ = try console.write("sleep requires exactly one argument\n"); } else { if (std.fmt.parseUnsigned(usize, command_parts[1], 10)) |n| { system_calls.sleep_seconds(n); } else |e| { try console.print("invalid argument: {s}\n", .{@errorName(e)}); } } } else if (custom_commands.get(command_parts[0])) |command_expr| { const args = tl.make_string_list(command_parts[1..], .Copy) catch |e| { try console.print("issue with converting args for custom command: {s}\n", .{@errorName(e)}); return false; }; const lisp_command = tl.cons(command_expr, args) catch |e| { try console.print("issue with making lisp command: {s}\n", .{@errorName(e)}); return false; }; print_lisp_result(tl.eval(lisp_command, tl.global_env) catch |e| { try console.print("issue with running lisp command: {s}\n", .{@errorName(e)}); return false; }); } else { var command_path = command_parts[0]; var path_buffer: [128]u8 = undefined; if (check_bin_path("/bin", command_parts[0], path_buffer[0..])) |path| { command_path = path[0..]; } const exit_info = system_calls.exec(&georgios.ProcessInfo{ .path = command_path, .name = command_parts[0], .args = command_parts[1..command_part_count], }) catch |e| { try console.print("Command \"{s}\" failed: {s}\n", .{command, @errorName(e)}); return false; }; if (exit_info.failed()) { // Start print_string( ansi_esc ++ "31m" ++ // Red FG segment_start ++ reset_colors); // Status print_string(ansi_esc ++ "30;41m"); // Black FG, Red BG if (exit_info.crashed) { print_string("crashed"); } else { print_uint(exit_info.status, 10); } // End print_string( reset_colors ++ ansi_esc ++ "31m" ++ // Red FG segment_end ++ reset_colors ++ "\n"); } } return false; } fn lisp_exec(t: *TinyishLisp, command_list: *Expr) TinyishLisp.Error!*Expr { var list_iter = command_list; var parts_al = std.ArrayList([]const u8).init(alloc); defer parts_al.deinit(); while (try t.next_in_list_iter(&list_iter)) |item| { try parts_al.append(t.get_string(item)); } const parts = parts_al.toOwnedSlice(); defer alloc.free(parts); const exit_info = system_calls.exec(&georgios.ProcessInfo{ .path = parts[0], .name = parts[0], .args = parts[1..], }) catch { return t.err; }; return if (exit_info.crashed) t.nil else t.make_int(exit_info.status); } fn lisp_run(t: *TinyishLisp, command: *Expr) TinyishLisp.Error!*Expr { if (run_command(t.get_string(command))) { system_calls.exit(.{}); } return t.nil; } fn lisp_exit(t: *TinyishLisp, status_expr: *Expr) TinyishLisp.Error!*Expr { const status = status_expr.get_int(u8) orelse return t.err; system_calls.exit(.{.status = status}); return t.nil; } fn lisp_add_command(t: *TinyishLisp, name: *Expr, expr: *Expr) TinyishLisp.Error!*Expr { custom_commands.put(t.get_string(name), expr) catch return t.err; _ = try t.keep_expr(expr); return try t.keep_expr(name); } const lisp_gen_primitives = [_]TinyishLisp.GenPrimitive{ .{.name = "exec", .zig_func = lisp_exec, .pass_arg_list = true}, .{.name = "run", .zig_func = lisp_run}, .{.name = "exit", .zig_func = lisp_exit}, .{.name = "add_command", .zig_func = lisp_add_command, .preeval_args = false}, }; var lisp_primitives: [lisp_gen_primitives.len]TinyishLisp.Primitive = undefined; fn init_lisp() !void { tl = try TinyishLisp.new(alloc); tl.out = &generic_console; tl.error_out = &generic_console; try tl.populate_extra_primitives(lisp_gen_primitives[0..], lisp_primitives[0..]); custom_commands = @TypeOf(custom_commands).init(alloc); } fn print_lisp_result(expr: *Expr) void { if (expr.is_true()) { try console.print("{}\n", .{tl.fmt_expr(expr)}); } } fn run_lisp(command: []const u8) void { tl.set_input(command, null); while (true) { const expr_maybe = tl.parse_input() catch |err| { try console.print("Interpreter error: {s}\n", .{@errorName(err)}); break; }; if (expr_maybe) |expr| { print_lisp_result(expr); } else { break; } } } fn run_lisp_file(path: []const u8) !bool { var file = try georgios.fs.open(path, .{.ReadOnly = .{}}); defer file.close() catch unreachable; const reader = file.reader(); tl.parse_all_input(try reader.readAllAlloc(alloc, no_max), path) catch |e| { try console.print("shell: error in \"{s}\" error: {s}\n", .{path, @errorName(e)}); return true; }; return false; } pub fn main() !u8 { var arena = std.heap.ArenaAllocator.init(georgios.page_allocator); alloc = arena.allocator(); defer arena.deinit(); generic_console_impl.init(&console); generic_console = generic_console_impl.writer(); try init_lisp(); if (run_lisp_file("/etc/rc.lisp") catch false) { return 1; } for (georgios.proc_info.args) |arg| { if (run_lisp_file(arg) catch |e| { try console.print("shell: open \"{s}\" error: {s}\n", .{arg, @errorName(e)}); return 1; }) { return 1; } } var got: usize = 0; var running = true; while (running) { // Print Prompt print_string(segment_start ++ invert_colors); if (system_calls.get_cwd(cwd_buffer[0..])) |dir| { if (!(dir.len == 1 and dir[0] == '/')) { print_string(dir); } } else |e| { print_string("get_cwd failed: "); print_string(@errorName(e)); print_string("\n"); } print_string("%" ++ invert_colors); // Process command var getline = true; while (getline) { const key_event = system_calls.get_key(.Blocking).?; if (key_event.char) |c| { if (key_event.modifiers.control_is_pressed()) { switch (c) { 'd' => { got = 0; running = false; break; }, else => {}, } } var print = true; if (c == '\n') { getline = false; } else if (c == '\x08') { if (got > 0) { got -= 1; } else { print = false; } } else if ((got + 1) == command_buffer.len) { print = false; } else { command_buffer[got] = c; got += 1; } if (print) { print_string(@ptrCast([*]const u8, &c)[0..1]); } } } if (got > 0) { const command = command_buffer[0..got]; if (command[0] == '(' or command[0] == '\'') { run_lisp(command); } else if (command[0] == '!') { run_lisp(command[1..]); } else if (run_command(command)) { break; // exit was run } got = 0; } } print_string("<shell about to exit>\n"); return 0; }
0
repos/georgios/programs
repos/georgios/programs/test-mouse/test-mouse.zig
const std = @import("std"); const georgios = @import("georgios"); comptime {_ = georgios;} const I32Point = georgios.utils.I32Point; const U32Point = georgios.utils.U32Point; const system_calls = georgios.system_calls; const console = georgios.get_console_writer(); const esc = "\x1b"; const reset_console = esc ++ "c"; const ansi_esc = esc ++ "["; const invert_colors = ansi_esc ++ "7m"; var vbe: bool = undefined; var scale: u16 = undefined; var screen = U32Point{}; var last_pos = U32Point{}; var pos = U32Point{}; var last_delta = I32Point{}; var buttons = [_]bool{false} ** 3; fn draw_at(p: U32Point, comptime fmt: []const u8, args: anytype) void { try console.print(ansi_esc ++ "{};{}H", .{p.y / scale, p.x / scale}); try console.print(fmt, args); } const vbe_cursor = U32Point{.x = 4, .y = 4}; var vbe_index: u8 = 0; // import math // for i, n in enumerate([int(math.sin(i / 255 * 2 * math.pi) * 128 + 127) for i in range(0, 256)]): // if (i % 8 == 0): // print() // print('0x{:02x}, '.format(n), end='') // print() const sin = [_]u8 { 0x7f, 0x82, 0x85, 0x88, 0x8b, 0x8e, 0x91, 0x94, 0x98, 0x9b, 0x9e, 0xa1, 0xa4, 0xa7, 0xaa, 0xad, 0xb0, 0xb3, 0xb5, 0xb8, 0xbb, 0xbe, 0xc1, 0xc3, 0xc6, 0xc8, 0xcb, 0xce, 0xd0, 0xd2, 0xd5, 0xd7, 0xd9, 0xdb, 0xde, 0xe0, 0xe2, 0xe4, 0xe6, 0xe7, 0xe9, 0xeb, 0xed, 0xee, 0xf0, 0xf1, 0xf2, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfc, 0xfd, 0xfd, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfd, 0xfd, 0xfc, 0xfc, 0xfb, 0xfa, 0xfa, 0xf9, 0xf8, 0xf7, 0xf6, 0xf4, 0xf3, 0xf2, 0xf0, 0xef, 0xed, 0xec, 0xea, 0xe8, 0xe7, 0xe5, 0xe3, 0xe1, 0xdf, 0xdd, 0xda, 0xd8, 0xd6, 0xd4, 0xd1, 0xcf, 0xcc, 0xca, 0xc7, 0xc5, 0xc2, 0xbf, 0xbc, 0xba, 0xb7, 0xb4, 0xb1, 0xae, 0xab, 0xa8, 0xa5, 0xa2, 0x9f, 0x9c, 0x99, 0x96, 0x93, 0x90, 0x8d, 0x8a, 0x86, 0x83, 0x80, 0x7d, 0x7a, 0x77, 0x73, 0x70, 0x6d, 0x6a, 0x67, 0x64, 0x61, 0x5e, 0x5b, 0x58, 0x55, 0x52, 0x4f, 0x4c, 0x49, 0x46, 0x43, 0x41, 0x3e, 0x3b, 0x38, 0x36, 0x33, 0x31, 0x2e, 0x2c, 0x29, 0x27, 0x25, 0x23, 0x20, 0x1e, 0x1c, 0x1a, 0x18, 0x16, 0x15, 0x13, 0x11, 0x10, 0x0e, 0x0d, 0x0b, 0x0a, 0x09, 0x07, 0x06, 0x05, 0x04, 0x03, 0x03, 0x02, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0b, 0x0c, 0x0d, 0x0f, 0x10, 0x12, 0x14, 0x16, 0x17, 0x19, 0x1b, 0x1d, 0x1f, 0x22, 0x24, 0x26, 0x28, 0x2b, 0x2d, 0x2f, 0x32, 0x35, 0x37, 0x3a, 0x3c, 0x3f, 0x42, 0x45, 0x48, 0x4a, 0x4d, 0x50, 0x53, 0x56, 0x59, 0x5c, 0x5f, 0x62, 0x65, 0x69, 0x6c, 0x6f, 0x72, 0x75, 0x78, 0x7b, 0x7e, }; const cos = [_]u8 { 0xff, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfd, 0xfd, 0xfc, 0xfb, 0xfb, 0xfa, 0xf9, 0xf8, 0xf7, 0xf6, 0xf5, 0xf3, 0xf2, 0xf1, 0xef, 0xee, 0xec, 0xea, 0xe9, 0xe7, 0xe5, 0xe3, 0xe1, 0xdf, 0xdd, 0xdb, 0xd9, 0xd6, 0xd4, 0xd2, 0xcf, 0xcd, 0xca, 0xc8, 0xc5, 0xc3, 0xc0, 0xbd, 0xba, 0xb8, 0xb5, 0xb2, 0xaf, 0xac, 0xa9, 0xa6, 0xa3, 0xa0, 0x9d, 0x9a, 0x97, 0x94, 0x91, 0x8d, 0x8a, 0x87, 0x84, 0x81, 0x7e, 0x7b, 0x77, 0x74, 0x71, 0x6e, 0x6b, 0x68, 0x65, 0x62, 0x5f, 0x5b, 0x58, 0x55, 0x52, 0x50, 0x4d, 0x4a, 0x47, 0x44, 0x41, 0x3f, 0x3c, 0x39, 0x36, 0x34, 0x31, 0x2f, 0x2c, 0x2a, 0x28, 0x25, 0x23, 0x21, 0x1f, 0x1d, 0x1b, 0x19, 0x17, 0x15, 0x13, 0x12, 0x10, 0x0e, 0x0d, 0x0c, 0x0a, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0c, 0x0d, 0x0e, 0x10, 0x12, 0x13, 0x15, 0x17, 0x19, 0x1b, 0x1d, 0x1f, 0x21, 0x23, 0x25, 0x28, 0x2a, 0x2c, 0x2f, 0x31, 0x34, 0x36, 0x39, 0x3c, 0x3e, 0x41, 0x44, 0x47, 0x4a, 0x4d, 0x50, 0x52, 0x55, 0x58, 0x5b, 0x5f, 0x62, 0x65, 0x68, 0x6b, 0x6e, 0x71, 0x74, 0x77, 0x7b, 0x7e, 0x81, 0x84, 0x87, 0x8a, 0x8d, 0x91, 0x94, 0x97, 0x9a, 0x9d, 0xa0, 0xa3, 0xa6, 0xa9, 0xac, 0xaf, 0xb2, 0xb5, 0xb8, 0xba, 0xbd, 0xc0, 0xc3, 0xc5, 0xc8, 0xca, 0xcd, 0xcf, 0xd2, 0xd4, 0xd6, 0xd9, 0xdb, 0xdd, 0xdf, 0xe1, 0xe3, 0xe5, 0xe7, 0xe9, 0xea, 0xec, 0xee, 0xef, 0xf1, 0xf2, 0xf3, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfb, 0xfc, 0xfd, 0xfd, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xff, }; fn draw_cursor(e: *const georgios.MouseEvent) void { if (vbe) { vbe_index +%= 1; const ri = vbe_index +% @intCast(u8, @boolToInt(e.lmb_pressed)) * 128; const gi = vbe_index +% @intCast(u8, @boolToInt(e.mmb_pressed)) * 128; const bi = vbe_index +% @intCast(u8, @boolToInt(e.rmb_pressed)) * 128; system_calls.vbe_fill_rect(&.{.size = vbe_cursor, .pos = pos}, (@intCast(u32, sin[ri]) << 16) | (@intCast(u32, cos[gi]) << 8) | bi | 0xff000000); } else { var char: u8 = ' '; if (e.lmb_pressed) { char = 'L'; } else if (e.mmb_pressed) { char = 'M'; } else if (e.rmb_pressed) { char = 'R'; } draw_at(last_pos, "{c}", .{char}); draw_at(pos, "{s}{c}{s}", .{invert_colors, char, invert_colors}); } last_pos = pos; } fn draw_status() void { if (vbe) return; // TODO: Way too slow right now const pressed = [_][]const u8{invert_colors, invert_colors}; const not = [_][]const u8{"", ""}; const lmb: []const []const u8 = if (buttons[0]) pressed[0..] else not[0..]; const mmb: []const []const u8 = if (buttons[1]) pressed[0..] else not[0..]; const rmb: []const []const u8 = if (buttons[2]) pressed[0..] else not[0..]; draw_at(.{.y = screen.y + scale}, "[{s}L{s}]({s}M{s})[{s}R{s}] x = {} ({}), y = {} ({}) ", .{ lmb[0], lmb[1], mmb[0], mmb[1], rmb[0], rmb[1], pos.x, last_delta.x, pos.y, last_delta.y}); } fn mouse_move(axis: *u32, delta: i32, max: u32) i32 { const signed_max = @intCast(i32, max); var r: i32 = 0; if (@addWithOverflow(i32, @intCast(i32, axis.*), delta, &r)) { r = if (delta > 0) signed_max else 0; } if (r < 0) r = 0; if (r > signed_max) r = signed_max; axis.* = @intCast(u32, r); return delta; } fn reset() void { try console.print(reset_console ++ ansi_esc ++ "25l", .{}); if (system_calls.vbe_res()) |vbe_res| { vbe = true; scale = 1; screen = vbe_res; } else { vbe = false; scale = 16; screen = .{.x = system_calls.console_width() - 1, .y = system_calls.console_height() - 2}; } screen = screen.multiply(scale); pos = screen.divide(2); draw_status(); } pub fn main() void { reset(); while (true) { if (system_calls.get_key(.NonBlocking)) |e| { if (e.kind == .Pressed) { if (e.unshifted_key == .Key_Escape) { break; } if (e.unshifted_key == .Key_Delete) { reset(); } } } if (system_calls.get_mouse_event(.NonBlocking)) |e| { last_delta = .{ .x = mouse_move(&pos.x, e.delta.x, screen.x), .y = mouse_move(&pos.y, -e.delta.y, screen.y), }; buttons[0] = e.lmb_pressed; buttons[1] = e.mmb_pressed; buttons[2] = e.rmb_pressed; if (!last_pos.eq(pos)) { draw_cursor(&e); } draw_status(); } system_calls.sleep_milliseconds(5); } try console.print(reset_console, .{}); }
0
repos/georgios/programs
repos/georgios/programs/cat/cat.zig
const georgios = @import("georgios"); comptime {_ = georgios;} const system_calls = georgios.system_calls; const print_string = system_calls.print_string; pub fn main() u8 { for (georgios.proc_info.args) |arg| { var file = georgios.fs.open(arg, .{.ReadOnly = .{}}) catch |e| { print_string("cat: open error: "); print_string(@errorName(e)); print_string("\n"); return 1; }; var buffer: [128]u8 = undefined; var got: usize = 1; while (got > 0) { if (file.read(buffer[0..])) |g| { got = g; } else |e| { print_string("cat: file.read error: "); print_string(@errorName(e)); print_string("\n"); return 1; } if (got > 0) { print_string(buffer[0..got]); } } file.close() catch |e| { print_string("cat: file.close error: "); print_string(@errorName(e)); print_string("\n"); return 1; }; } return 0; }
0
repos/georgios/programs
repos/georgios/programs/img/img.zig
// If vbe is setup, img takes a file produced by scripts/make_img.sh and the // width and displays it on the screen until ESC is pressed. const std = @import("std"); const georgios = @import("georgios"); comptime {_ = georgios;} const utils = georgios.utils; const Point = utils.U32Point; const system_calls = georgios.system_calls; const print_string = system_calls.print_string; const print_uint = system_calls.print_uint; var console = georgios.get_console_writer(); var buffer: [2048]u8 align(@alignOf(u64)) = undefined; var alloc: std.mem.Allocator = undefined; fn draw_image(path: []const u8, fullscreen: bool, overlay: bool, res: Point, at: ?utils.I32Point) u8 { // Open image file var file = georgios.fs.open(path, .{.ReadOnly = .{}}) catch |e| { print_string("img: open error: "); print_string(@errorName(e)); print_string("\n"); return 2; }; var bmp_file = utils.Bmp(@TypeOf(file)).init(&file); bmp_file.read_header() catch |e| { print_string("img: failed to parse BMP header: "); print_string(@errorName(e)); print_string("\n"); return 2; }; var image_size = bmp_file.image_size_pixels() catch @panic("?"); // Figure out where the image is going. var last_scroll_count: u32 = undefined; var size: Point = .{}; var cur_pos: Point = .{}; var glyph_size: Point = .{}; system_calls.get_vbe_console_info(&last_scroll_count, &size, &cur_pos, &glyph_size); var pos = Point{.x = 10, .y = 20}; if (fullscreen) { if (!overlay) { // Reset Console system_calls.print_string("\x1bc"); } system_calls.print_string("Loading Image..."); } else if (at == null) { // Make sure the image appears between the two prompts, even if the // console scrolls. const prev_cur_y = glyph_size.y * cur_pos.y; const room = utils.align_up(image_size.y, glyph_size.y); const newlines: usize = room / glyph_size.y; var i: usize = 0; while (i < newlines) { print_string("\n"); i += 1; } system_calls.get_vbe_console_info(&last_scroll_count, &size, &cur_pos, &glyph_size); pos = .{.y = prev_cur_y - last_scroll_count * glyph_size.y}; } _ = res; if (at) |at_val| { const abs = at_val.abs().intCast(u32); pos = .{ .x = if (at_val.x >= 0) abs.x else (res.x - image_size.x - abs.x), .y = if (at_val.y >= 0) abs.y else (res.y - image_size.y - abs.y), }; } var exit_status: u8 = 0; // Draw the image on the screen var last = utils.U32Point{}; var bmp_pos: usize = 0; while (bmp_file.read_bitmap(&bmp_pos, buffer[0..]) catch @panic("TODO")) |got| { system_calls.vbe_draw_raw_image_chunk(buffer[0..got], image_size.x, pos, &last); } system_calls.vbe_flush_buffer(); file.close() catch |e| { print_string("img: file.close error: "); print_string(@errorName(e)); print_string("\n"); exit_status = 3; }; return exit_status; } const StrList = std.ArrayList([]const u8); fn handle_path(images_al: *StrList, path: []const u8) anyerror!void { // Is directory? var dir_file = georgios.fs.open(path, .{.ReadOnly = .{.dir = true}}) catch |e| { if (e == georgios.fs.Error.NotADirectory) { if (utils.ends_with(path, ".bmp")) { try images_al.append(try alloc.dupe(u8, path)); } } else { try console.print("img: handle_path open error: {s}\n", .{@errorName(e)}); } return; }; defer dir_file.close() catch unreachable; var name_buffer: [256]u8 = undefined; while (true) { const read = dir_file.read(name_buffer[0..]) catch |e| { try console.print("img: handle_path read error: {s}\n", .{@errorName(e)}); return; }; if (read == 0) break; const name = name_buffer[0..read]; if (utils.ends_with(name, ".bmp")) { var subpath_al = std.ArrayList(u8).init(alloc); defer subpath_al.deinit(); try subpath_al.appendSlice(path); try subpath_al.append('/'); try subpath_al.appendSlice(name); const subpath = subpath_al.toOwnedSlice(); defer alloc.free(subpath); try handle_path(images_al, subpath); } } } fn parse_int_arg(i: usize, what: []const u8) ?i32 { if (i == georgios.proc_info.args.len) { try console.print("img: no argument passed to {s}\n", .{what}); return null; } const arg = georgios.proc_info.args[i]; return std.fmt.parseInt(i32, arg, 10) catch |e| { try console.print("img: invalid value {s} passed to {s}: {s}\n", .{arg, what, @errorName(e)}); return null; }; } pub fn main() !u8 { var arena = std.heap.ArenaAllocator.init(georgios.page_allocator); alloc = arena.allocator(); defer arena.deinit(); // Parse arguments var args_al = StrList.init(alloc); defer args_al.deinit(); var fullscreen = true; var overlay = false; var at: ?utils.I32Point = null; var arg_i: usize = 0; var no_vbe = false; // No VBE is okay while (arg_i < georgios.proc_info.args.len) { const arg = georgios.proc_info.args[arg_i]; if (utils.memory_compare(arg, "--embed")) { fullscreen = false; } else if (utils.memory_compare(arg, "-e")) { fullscreen = false; } else if (utils.memory_compare(arg, "--overlay")) { overlay = true; } else if (utils.memory_compare(arg, "--at")) { at = utils.I32Point{}; arg_i += 1; at.?.x = parse_int_arg(arg_i, "--at X arg") orelse { return 1; }; arg_i += 1; at.?.y = parse_int_arg(arg_i, "--at Y arg") orelse { return 1; }; } else if (utils.memory_compare(arg, "--no-vbe")) { no_vbe = true; } else if (utils.starts_with(arg, "-")) { try console.print("img: invalid option: {s}\n", .{arg}); return 1; } else { try args_al.append(arg); } arg_i += 1; } const res = system_calls.vbe_res(); if (res == null) { if (no_vbe) { return 0; } print_string("img requires VBE graphics mode\n"); return 1; } // Process args for image files var images_al = std.ArrayList([]const u8).init(alloc); for (args_al.items) |arg| { try handle_path(&images_al, arg); } const images = images_al.toOwnedSlice(); defer alloc.free(images); if (images.len == 0) { print_string("img: requires image paths or directory paths with images in them\n"); return 1; } if (fullscreen) { system_calls.print_string("\x1bc"); } var i: usize = 0; while (i < images.len) { const exit_status = draw_image(images[i], fullscreen, overlay, res.?, at); if (exit_status != 0) { return exit_status; } if ((fullscreen and exit_status == 0 and !overlay) or (overlay and i == (images.len - 1))) { try console.print( "\x1b[0;0H({}/{}) images, press the ESC key to exit...", .{i + 1, images.len}); // Wait for ESC key to be pressed. while (true) { if (system_calls.get_key(.Blocking)) |key_event| { if (key_event.kind == .Pressed) { switch (key_event.unshifted_key) { .Key_CursorRight => { if (!overlay and i < (images.len - 1)) { i += 1; break; } }, .Key_CursorLeft => { if (!overlay and i > 0) { i -= 1; break; } }, .Key_Escape => { // Reset Console system_calls.print_string("\x1bc"); system_calls.exit(.{}); }, else => {}, } } } } } else { i += 1; } } for (images) |image| { defer alloc.free(image); } return 0; }
0
repos/georgios/programs
repos/georgios/programs/touch/touch.zig
const georgios = @import("georgios"); comptime {_ = georgios;} const console = georgios.get_console_writer(); pub fn main() u8 { for (georgios.proc_info.args) |path| { var dir = georgios.Directory{._port_id = georgios.MetaPort}; dir.create(path, .{.file = true}) catch |e| { try console.print("touch: error: {s}\n", .{@errorName(e)}); return 1; }; } return 0; }
0
repos/georgios/programs
repos/georgios/programs/snake/snake.zig
// TODO: Fix bug where the player can kill themselves with 2 segments when // trashing around wildly. const builtin = @import("builtin"); const georgios = @import("georgios"); comptime {_ = georgios;} const system_calls = georgios.system_calls; pub const panic = georgios.panic; const Game = struct { const Rng = georgios.utils.Rand(u32); const Dir = enum { Up, Down, Right, Left, }; const Point = struct { x: u32, y: u32, pub fn eql(self: *const Point, other: Point) bool { return self.x == other.x and self.y == other.y; } }; max: Point = undefined, running: bool = true, head: Point = undefined, // NOTE: After 128, the snake will stop growing, but also will leave behind // a segment for each food it gets over 128. body: georgios.utils.CircularBuffer(Point, 128, .DiscardOldest) = .{}, score: usize = undefined, dir: Dir = .Right, rng: Rng = undefined, food: Point = undefined, fn get_input(self: *Game) void { while (system_calls.get_key(.NonBlocking)) |key_event| { if (key_event.kind == .Pressed) { switch (key_event.unshifted_key) { .Key_CursorUp => if (self.dir != .Down) { self.dir = .Up; }, .Key_CursorDown => if (self.dir != .Up) { self.dir = .Down; }, .Key_CursorRight => if (self.dir != .Left) { self.dir = .Right; }, .Key_CursorLeft => if (self.dir != .Right) { self.dir = .Left; }, .Key_Escape => { system_calls.print_string("\x1bc"); system_calls.exit(.{}); }, else => {}, } } } } fn in_body(self: *const Game, point: Point) bool { var i: usize = 0; while (self.body.get(i)) |p| { if (p.eql(point)) return true; i += 1; } return false; } fn draw(s: []const u8, p: Point) void { var buffer: [128]u8 = undefined; var ts = georgios.utils.ToString{.buffer = buffer[0..]}; ts.string("\x1b[") catch unreachable; ts.uint(p.y) catch unreachable; ts.char(';') catch unreachable; ts.uint(p.x) catch unreachable; ts.char('H') catch unreachable; ts.string(s) catch unreachable; system_calls.print_string(ts.get()); } fn draw_head(self: *const Game, alive: bool) void { draw(if (alive) "♦" else "‼", self.head); } fn update_head_and_body(self: *Game, new_pos: Point) void { const old_pos = self.head; self.head = new_pos; self.draw_head(true); if (self.head.eql(self.food)) { self.body.push(old_pos); self.score += 1; self.show_score(); self.gen_food(); } else { if (self.score > 0) { self.body.push(old_pos); draw(" ", self.body.pop().?); } else { draw(" ", old_pos); } } } fn random_point(self: *Game) Point { return .{ .x = self.rng.get() % self.max.x, .y = self.rng.get() % self.max.y, }; } fn gen_food(self: *Game) void { self.food = self.random_point(); while (self.in_body(self.food)) { self.food = self.random_point(); } draw("@", self.food); } fn show_score(self: *Game) void { var p: Point = .{.x = 0, .y = self.max.y + 1}; while (p.x < self.max.x + 1) { draw("▓", p); p.x += 1; } p.x = 1; var buffer: [128]u8 = undefined; var ts = georgios.utils.ToString{.buffer = buffer[0..]}; ts.string("SCORE: ") catch unreachable; ts.uint(self.score) catch unreachable; draw(ts.get(), p); } pub fn reset(self: *Game) void { self.max = .{ .x = system_calls.console_width() - 2, .y = system_calls.console_height() - 2, }; self.rng = .{.seed = system_calls.time()}; system_calls.print_string("\x1bc\x1b[25l"); self.head = .{.x = self.max.x / 2, .y = self.max.y / 2}; self.draw_head(true); self.gen_food(); self.score = 0; self.show_score(); self.body.reset(); } pub fn game_over(self: *Game) usize { self.draw_head(false); // Dead system_calls.sleep_milliseconds(500); self.reset(); return 500; } pub fn tick(self: *Game) usize { self.get_input(); if ((self.dir == .Up and self.head.y == 0) or (self.dir == .Down and self.head.y == self.max.y) or (self.dir == .Right and self.head.x == self.max.x) or (self.dir == .Left and self.head.x == 0)) { return self.game_over(); } var new_pos = self.head; switch (self.dir) { .Up => new_pos.y -= 1, .Down => new_pos.y += 1, .Right => new_pos.x += 1, .Left => new_pos.x -= 1, } if (self.in_body(new_pos)) { return self.game_over(); } self.update_head_and_body(new_pos); // Speed up a bit as time goes on var delay: usize = if (self.score < 32) 100 - 10 * self.score / 4 else 20; if (self.dir == .Down or self.dir == .Up) { delay *= 2; } return delay; } }; pub fn main() void { var game = Game{}; game.reset(); while (game.running) { // TODO: Delta time to correct for speed? system_calls.sleep_milliseconds(game.tick()); } }
0
repos/georgios/libs
repos/georgios/libs/tinyishlisp/main.zig
const std = @import("std"); const utils = @import("utils"); const TinyishLisp = @import("TinyishLisp.zig"); const no_max = std.math.maxInt(usize); pub fn main() !u8 { var gpa: std.heap.GeneralPurposeAllocator(.{.stack_trace_frames = 32}) = .{}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); const stdin = std.io.getStdIn().reader(); var stdout = std.io.getStdOut().writer(); var stderr = std.io.getStdErr().writer(); var tl = try TinyishLisp.new(allocator); defer tl.done(); var generic_stdout_impl = utils.GenericWriterImpl(@TypeOf(stdout)){}; generic_stdout_impl.init(&stdout); var generic_stdout = generic_stdout_impl.writer(); tl.out = &generic_stdout; var generic_stderr_impl = utils.GenericWriterImpl(@TypeOf(stderr)){}; generic_stderr_impl.init(&stderr); var generic_stderr = generic_stderr_impl.writer(); tl.error_out = &generic_stderr; var argit = std.process.args(); _ = argit.skip(); while (argit.next(allocator)) |_arg| { const arg = _arg catch unreachable; try stdout.print("{s}\n", .{arg}); const lisp_file = try std.fs.cwd().openFile(arg, .{.read = true}); defer lisp_file.close(); const reader = lisp_file.reader(); try tl.parse_all_input(try reader.readAllAlloc(allocator, no_max), arg); } var line_contents = std.ArrayList(u8).init(allocator); defer line_contents.deinit(); while (true) { try stdout.print("> ", .{}); stdin.readUntilDelimiterArrayList(&line_contents, '\n', no_max) catch |e| { if (e == error.EndOfStream) { break; } else { return e; } }; const line = line_contents.toOwnedSlice(); defer allocator.free(line); tl.set_input(line, null); while (true) { const expr_maybe = tl.parse_input() catch |err| { try stderr.print("Interpreter error: {s}\n", .{@errorName(err)}); continue; }; if (expr_maybe) |expr| { if (expr.is_true()) { try stdout.print("{repr}\n", tl.fmt_expr(expr)); } } else { break; } } } return 0; }
0
repos/georgios/libs
repos/georgios/libs/tinyishlisp/test.zig
test "tinyishlisp test root" { _ = @import("TinyishLisp.zig"); }
0
repos/georgios/libs
repos/georgios/libs/tinyishlisp/TinyishLisp.zig
// Tinyish Lisp is based on: // https://github.com/Robert-van-Engelen/tinylisp/blob/main/tinylisp.pdf // // TODO: // - Replace atom strings and environment with hash maps const std = @import("std"); const Allocator = std.mem.Allocator; const utils = @import("utils"); const streq = utils.memory_compare; const GenericWriter = utils.GenericWriter; const Self = @This(); const IntType = i64; const debug = false; const print_raw_list = false; pub const Error = error { LispInvalidPrimitiveIndex, LispInvalidPrimitiveArgCount, LispUnexpectedEndOfInput, LispInvalidParens, LispInvalidSyntax, LispInvalidEnv, } || utils.Error || std.mem.Allocator.Error || GenericWriter.GenericWriterError; const ExprList = utils.List(Expr); const AtomMap = std.StringHashMap(*Expr); const ExprSet = std.AutoHashMap(*Expr, void); allocator: Allocator, // Expr/Values atoms: AtomMap = undefined, nil: *Expr = undefined, tru: *Expr = undefined, err: *Expr = undefined, global_env: *Expr = undefined, gc_owned: ExprList = undefined, gc_keep: ExprSet = undefined, parse_return: ?*Expr = null, // Primitive Functions builtin_primitives: [gen_builtin_primitives.len]Primitive = undefined, extra_primitives: ?[]Primitive = null, // Parsing input: ?[]const u8 = null, pos: usize = 0, input_name: ?[]const u8 = null, lineno: usize = 1, out: ?*GenericWriter.Writer = null, error_out: ?*GenericWriter.Writer = null, pub fn new_barren(allocator: Allocator) Self { return .{ .allocator = allocator, .atoms = AtomMap.init(allocator), .gc_owned = .{.alloc = allocator}, .gc_keep = ExprSet.init(allocator), }; } pub fn new(allocator: Allocator) Error!Self { var tl = new_barren(allocator); tl.nil = try tl.make_expr(.Nil); tl.tru = try tl.make_atom("#t", .NoCopy); tl.err = try tl.make_atom("#e", .NoCopy); tl.global_env = try tl.tack_pair_to_list(tl.tru, tl.tru, tl.nil); try tl.populate_primitives(gen_builtin_primitives[0..], 0, tl.builtin_primitives[0..]); return tl; } pub fn done(self: *Self) void { _ = self.collect(.All); self.gc_owned.clear(); self.atoms.deinit(); self.gc_keep.deinit(); } pub fn set_input(self: *Self, input: []const u8, input_name: ?[]const u8) void { self.pos = 0; self.input = input; self.input_name = input_name; } pub fn got_zig_error(self: *Self, error_value: Error) Error { return self.print_zig_error(error_value); } pub fn got_lisp_error(self: *Self, reason: []const u8, expr: ?*Expr) *Expr { self.print_error(reason, expr); return self.err; } const TestTl = struct { var stderr = std.io.getStdErr().writer(); ta: utils.TestAlloc = .{}, tl: Self = undefined, generic_stderr_impl: utils.GenericWriterImpl(@TypeOf(stderr)) = .{}, generic_stderr: utils.GenericWriter.Writer = undefined, fn init(self: *TestTl) Error!void { errdefer self.ta.deinit(.NoPanic); self.tl = try Self.new(self.ta.alloc()); self.generic_stderr_impl.init(&stderr); self.generic_stderr = self.generic_stderr_impl.writer(); self.tl.error_out = &self.generic_stderr; } fn done(self: *TestTl) void { self.tl.done(); self.ta.deinit(.Panic); } }; // Expr ======================================================================= pub const ExprKind = enum { Int, Atom, // Unique symbol String, Primitive, // Primitive function Cons, // (Cons)tructed List Closure, Nil, }; pub const Expr = struct { pub const StringValue = struct { string: []const u8, gc_owned: bool, }; pub const ConsValue = struct { x: *Expr, y: *Expr, }; pub const Value = union (ExprKind) { Int: IntType, String: StringValue, Atom: *Expr, Primitive: usize, // Index in primitives Cons: ConsValue, Closure: *Expr, // Pointer to Cons List Nil: void, }; pub const GcOwned = struct { marked: bool = false, }; pub const Owner = union (enum) { Gc: GcOwned, Other: void, }; value: Value = .Nil, owner: Owner = .Other, pub fn int(value: IntType) Expr { return Expr{.value = .{.Int = value}}; } pub fn get_int(self: *const Expr, comptime As: type) ?As { return if (@as(ExprKind, self.value) != .Int) null else std.math.cast(As, self.value.Int) catch null; } pub fn get_cons(self: *Expr) *Expr { return switch (self.value) { ExprKind.Cons => self, ExprKind.Closure => |cons_expr| cons_expr, else => @panic("Expr.get_cons() called with non-list-like"), }; } pub fn get_string(self: *const Expr) ?[]const u8 { return switch (self.value) { ExprKind.String => |string_value| string_value.string, ExprKind.Atom => |string_expr| string_expr.get_string(), else => null, }; } pub fn primitive_obj(self: *Expr, tl: *Self) Error!*const Primitive { return switch (self.value) { ExprKind.Primitive => |index| try tl.get_primitive(index), else => @panic("Expr.primitive_obj() called with non-primitive"), }; } pub fn call_primitive(self: *Expr, tl: *Self, args: *Expr, env: *Expr) Error!*Expr { return (try self.primitive_obj(tl)).rt_func(tl, args, env); } pub fn primitive_name(self: *Expr, tl: *Self) Error![]const u8 { return (try self.primitive_obj(tl)).name; } pub fn not(self: *const Expr) bool { return @as(ExprKind, self.value) == .Nil; } pub fn is_true(self: *const Expr) bool { return !self.not(); } pub fn eq(self: *const Expr, other: *const Expr) bool { if (self == other) return true; return utils.any_equal(self.value, other.value); } }; test "Expr" { const int1 = Expr.int(1); const int2 = Expr.int(2); var str = Expr{.value = .{.String = .{.string = "hello", .gc_owned = false}}}; const atom = Expr{.value = .{.Atom = &str}}; const nil = Expr{}; try std.testing.expect(int1.eq(&int1)); try std.testing.expect(!int1.eq(&int2)); try std.testing.expect(!int1.eq(&str)); try std.testing.expect(str.eq(&str)); try std.testing.expect(!str.eq(&atom)); try std.testing.expect(nil.eq(&nil)); try std.testing.expect(!nil.eq(&int1)); } pub fn get_string(self: *Self, expr: *Expr) []const u8 { if (expr.get_string()) |str| return str; const msg = "TinyishLisp.get_string called on non-string-like"; self.print_error(msg, expr); @panic(msg); } // Garbage Collection ========================================================= pub fn make_expr(self: *Self, from: Expr.Value) std.mem.Allocator.Error!*Expr { try self.gc_owned.push_back(.{ .value = from, .owner = .{.Gc = .{}}, }); return &self.gc_owned.tail.?.value; } pub fn keep_expr(self: *Self, expr: *Expr) Error!*Expr { try self.gc_keep.putNoClobber(expr, .{}); return expr; } pub fn discard_expr(self: *Self, expr: *Expr) void { _ = self.gc_keep.remove(expr); } pub fn make_int(self: *Self, value: IntType) Error!*Expr { return self.make_expr(.{.Int = value}); } pub fn make_bool(self: *const Self, value: bool) *Expr { return if (value) self.tru else self.nil; } const StringManage = enum { NoCopy, // Use string as is, do not free when done PassOwnership, // Use string as is, free when done Copy, // Copy string, free when done }; pub fn make_string(self: *Self, str: []const u8, manage: StringManage) Error!*Expr { var string: []const u8 = str; var gc_owned = true; switch (manage) { .NoCopy => gc_owned = false, .Copy => string = try self.allocator.dupe(u8, str), .PassOwnership => {}, } return self.make_expr(.{.String = .{.string = string, .gc_owned = gc_owned}}); } pub fn make_atom(self: *Self, name: []const u8, manage: StringManage) Error!*Expr { if (self.atoms.get(name)) |atom| { if (manage == .PassOwnership) { @panic("make_atom: passed existing name with passing ownership"); } return atom; } const atom = try self.make_expr(.{.Atom = undefined}); errdefer _ = self.unmake_expr(atom, .All); const string = try self.make_string(name, manage); errdefer _ = self.unmake_expr(string, .All); try self.atoms.putNoClobber(self.get_string(string), atom); atom.value.Atom = string; return atom; } fn get_atom(self: *Self, name: []const u8) Error!*Expr { if (self.atoms.get(name)) |atom| { return atom; } else { if (debug) std.debug.print("error: {s} is not defined\n", .{name}); return self.err; } } fn mark(self: *Self, expr: *Expr) void { _ = self; switch (expr.owner) { .Gc => |*gc| { if (gc.marked) { return; } gc.marked = true; }, else => {}, } switch (expr.value) { .Cons => |pair| { self.mark(pair.x); self.mark(pair.y); }, .Closure => |ptr| { self.mark(ptr); }, .Atom => |string_expr| { self.mark(string_expr); }, else => {}, } } const CollectKind = enum { Unused, All, }; fn unmake_expr(self: *Self, expr: *Expr, kind: CollectKind) bool { switch (expr.owner) { .Gc => |*gc| { if (kind == .Unused and gc.marked) { gc.marked = false; return false; } else { switch (expr.value) { .String => |string_value| { if (string_value.gc_owned) { self.allocator.free(string_value.string); } }, .Atom => |string_expr| { _ = self.atoms.remove(self.get_string(string_expr)); }, else => {}, } self.gc_owned.remove_node(@fieldParentPtr(ExprList.Node, "value", expr)); return true; } }, else => @panic("unmake_expr passed non-gc owned expr"), } } fn collect(self: *Self, kind: CollectKind) usize { // Mark Phase if (kind == .Unused) { self.mark(self.nil); self.mark(self.tru); self.mark(self.err); self.mark(self.global_env); { var it = self.atoms.valueIterator(); while (it.next()) |atom| { self.mark(atom.*); } } { var it = self.gc_keep.keyIterator(); while (it.next()) |expr| { self.mark(expr.*); } } if (self.parse_return) |expr| { self.mark(expr); } } // Sweep Phase var count: usize = 0; var node_maybe = self.gc_owned.head; while (node_maybe) |node| { node_maybe = node.next; if (self.unmake_expr(&node.value, kind)) { count += 1; } } return count; } test "gc" { var ta = utils.TestAlloc{}; defer ta.deinit(.Panic); errdefer ta.deinit(.NoPanic); var tl = try Self.new(ta.alloc()); defer tl.done(); _ = try tl.make_expr(.Nil); try std.testing.expectEqual(@as(usize, 1), tl.collect(.Unused)); try std.testing.expectEqual(@as(usize, 0), tl.collect(.Unused)); _ = try tl.make_list([_]*Expr{ try tl.make_int(1), // Cons + Int try tl.make_int(2), // Cons + Int try tl.make_int(3), // Cons + Int }); try std.testing.expectEqual(@as(usize, 6), tl.collect(.Unused)); try std.testing.expectEqual(@as(usize, 0), tl.collect(.Unused)); { // Make a cycle // +---+ // V | // a>b>c>d const a = try tl.make_expr(.{.Cons = .{.x = tl.nil, .y = tl.nil}}); const b = try tl.make_expr(.{.Cons = .{.x = tl.nil, .y = tl.nil}}); const c = try tl.make_expr(.{.Cons = .{.x = tl.nil, .y = tl.nil}}); const d = try tl.make_expr(.{.Cons = .{.x = tl.nil, .y = tl.nil}}); a.value.Cons.y = b; b.value.Cons.y = c; c.value.Cons.y = d; d.value.Cons.y = b; try std.testing.expectEqual(@as(usize, 4), tl.collect(.Unused)); try std.testing.expectEqual(@as(usize, 0), tl.collect(.Unused)); } } // Primitive Function Support ================================================= pub const GenPrimitive = struct { name: []const u8, zig_func: anytype, preeval_args: bool = true, pass_env: bool = false, pass_arg_list: bool = false, }; const gen_builtin_primitives = [_]GenPrimitive{ // zig_func should be like fn(tl: *Self, [env: Expr,] [args: Expr|arg1: Expr, ...]) Error!Expr .{.name = "eval", .zig_func = eval}, .{.name = "quote", .zig_func = quote, .preeval_args = false}, .{.name = "cons", .zig_func = cons}, .{.name = "car", .zig_func = car}, .{.name = "cdr", .zig_func = cdr}, .{.name = "+", .zig_func = add, .pass_arg_list = true}, .{.name = "-", .zig_func = subtract, .pass_arg_list = true}, .{.name = "*", .zig_func = multiply, .pass_arg_list = true}, .{.name = "/", .zig_func = divide, .pass_arg_list = true}, .{.name = "<", .zig_func = less}, .{.name = "eq?", .zig_func = eq}, .{.name = "or", .zig_func = @"or"}, .{.name = "and", .zig_func = @"and"}, .{.name = "not", .zig_func = not}, .{.name = "cond", .zig_func = cond, .preeval_args = false, .pass_env = true, .pass_arg_list = true}, .{.name = "if", .zig_func = @"if", .preeval_args = false, .pass_env = true}, .{.name = "let*", .zig_func = leta, .preeval_args = false, .pass_env = true, .pass_arg_list = true}, .{.name = "lambda", .zig_func = lambda, .preeval_args = false, .pass_env = true}, .{.name = "define", .zig_func = define, .preeval_args = false, .pass_env = true}, .{.name = "print", .zig_func = print, .pass_arg_list = true}, .{.name = "progn", .zig_func = progn, .preeval_args = false, .pass_env = true, .pass_arg_list = true}, }; pub const Primitive = struct { name: []const u8, rt_func: fn(tl: *Self, args: *Expr, env: *Expr) Error!*Expr, }; // Use comptime info to dynamically setup, check, and pass arguments to // primitive functions. fn PrimitiveAdaptor(comptime prim: GenPrimitive) type { return struct { fn rt_func(tl: *Self, args: *Expr, env: *Expr) Error!*Expr { // TODO: assert expresion types and count const zfti = @typeInfo(@TypeOf(prim.zig_func)).Fn; if (zfti.args.len == 0) { @compileError(prim.name ++ " primitive fn must at least take *TinyishLisp"); } if (zfti.return_type != Error!*Expr) { @compileError(prim.name ++ " primitive fn must return Error!*Expr"); } var arg_tuple: std.meta.ArgsTuple(@TypeOf(prim.zig_func)) = undefined; var args_list = args; if (prim.preeval_args) { args_list = try tl.evlis(args_list, env); } inline for (zfti.args) |arg, i| { if (i == 0) { if (arg.arg_type.? != *Self) { @compileError(prim.name ++ " primitive fn 1st arg must be *TinyishLisp"); } else { arg_tuple[0] = tl; } } else if (arg.arg_type.? == *Expr) { if (i == 1 and prim.pass_env) { arg_tuple[i] = env; } else if (prim.pass_arg_list) { // Pass in args as a list arg_tuple[i] = args_list; break; } else { // Single Argument arg_tuple[i] = try tl.car(args_list); args_list = try tl.cdr(args_list); } } else { @compileError(prim.name ++ " invalid primitive fn arg: " ++ @typeName(arg.arg_type.?)); } } return @call(.{}, prim.zig_func, arg_tuple); } }; } fn populate_primitives(self: *Self, comptime gen: []const GenPrimitive, index_offset: usize, primitives: []Primitive) Error!void { comptime var i = 0; @setEvalBranchQuota(2000); inline while (i < gen.len) { primitives[i] = .{ .name = gen[i].name, .rt_func = PrimitiveAdaptor(gen[i]).rt_func, }; self.global_env = try self.tack_pair_to_list(try self.make_atom(gen[i].name, .NoCopy), try self.make_expr(.{.Primitive = index_offset + i}), self.global_env); i += 1; } } pub fn populate_extra_primitives(self: *Self, comptime gen: []const GenPrimitive, primitives: []Primitive) Error!void { try self.populate_primitives(gen, self.builtin_primitives.len, primitives); self.extra_primitives = primitives; } fn get_primitive(self: *Self, index: usize) Error!*const Primitive { const bpl = self.builtin_primitives.len; if (index < bpl) { return &self.builtin_primitives[index]; } else if (self.extra_primitives) |ep| { if (index < bpl + ep.len) { return &ep[index - bpl]; } } return self.got_zig_error(Error.LispInvalidPrimitiveIndex); } // List Functions ============================================================= // (cons x y): return the pair (x y)/list pub fn cons(self: *Self, x: *Expr, y: *Expr) Error!*Expr { return self.make_expr(.{.Cons = .{.x = x, .y = y}}); } fn car_cdr(self: *Self, x: *Expr, get_x: bool) Error!*Expr { return switch (x.value) { ExprKind.Cons => |*pair| if (get_x) pair.x else pair.y, else => blk: { break :blk self.got_lisp_error("value passed to cdr or car isn't a list", x); } }; } // (car x y): return x pub fn car(self: *Self, x: *Expr) Error!*Expr { return try self.car_cdr(x, true); } // (cdr x y): return y pub fn cdr(self: *Self, x: *Expr) Error!*Expr { return try self.car_cdr(x, false); } test "cons, car, cdr" { var ta = utils.TestAlloc{}; defer ta.deinit(.Panic); errdefer ta.deinit(.NoPanic); var tl = Self.new_barren(ta.alloc()); defer tl.done(); const ten = try tl.make_int(10); const twenty = try tl.make_int(20); const list = try tl.cons(ten, twenty); try std.testing.expectEqual(ten, try tl.car(list)); try std.testing.expectEqual(twenty, try tl.cdr(list)); } pub fn make_list(self: *Self, items: anytype) Error!*Expr { var head = self.nil; var i = items.len; while (i > 0) { i -= 1; head = try self.cons(items[i], head); } return head; } pub fn make_string_list(self: *Self, items: anytype, manage: StringManage) Error!*Expr { var head = self.nil; var i = items.len; while (i > 0) { i -= 1; head = try self.cons(try self.make_string(items[i], manage), head); } return head; } pub fn next_in_list_iter(self: *Self, list_iter: **Expr) Error!?*Expr { if (list_iter.*.not()) { return null; } const value = try self.car(list_iter.*); const next_list_iter = try self.cdr(list_iter.*); list_iter.* = next_list_iter; return value; } pub fn assert_next_in_list_iter(self: *Self, list_iter: **Expr) ?*Expr { return self.next_in_list_iter(list_iter) catch { @panic("assert_next_in_list_iter: not a list"); }; } test "make_list, next_in_list_iter" { var ta = utils.TestAlloc{}; defer ta.deinit(.Panic); errdefer ta.deinit(.NoPanic); var tl = Self.new_barren(ta.alloc()); tl.nil = try tl.make_expr(.Nil); defer tl.done(); const items = [_]*Expr{try tl.make_int(30), try tl.make_expr(.Nil), try tl.make_int(40)}; var list_iter = try tl.make_list(items); for (items) |item| { try std.testing.expect((try tl.next_in_list_iter(&list_iter)).?.eq(item)); } const nul: ?*Expr = null; try std.testing.expectEqual(nul, try tl.next_in_list_iter(&list_iter)); } // Tack a pair of "first" and "second" on to "list" and return the new list. pub fn tack_pair_to_list(self: *Self, first: *Expr, second: *Expr, list: *Expr) Error!*Expr { return try self.cons(try self.cons(first, second), list); } // print_expr ================================================================= const PrintKind = enum { Repr, RawRepr, Display, }; // TODO: Remove error hack if https://github.com/ziglang/zig/issues/2971 is fixed pub fn print_expr(self: *Self, writer: anytype, expr: *Expr, kind: PrintKind) @typeInfo(@typeInfo(@TypeOf(writer.write)).BoundFn.return_type.?).ErrorUnion.error_set!void { const repr = kind == .Repr or kind == .RawRepr; switch (expr.value) { .Int => |value| try writer.print("{}", .{value}), .Atom => |value| try self.print_expr(writer, value, .Display), .String => |string_value| if (repr) { try writer.print("\"{}\"", .{std.zig.fmtEscapes(string_value.string)}); } else { _ = try writer.write(string_value.string); }, .Cons => |*pair| { _ = try writer.write("("); if (kind == .RawRepr) { try self.print_expr(writer, pair.x, kind); _ = try writer.write(" . "); try self.print_expr(writer, pair.y, kind); } else { var cons_expr = expr; while (@as(ExprKind, cons_expr.value) == .Cons) { try self.print_expr(writer, cons_expr.value.Cons.x, kind); const next_cons_expr = cons_expr.value.Cons.y; if (next_cons_expr.is_true()) { if (@as(ExprKind, next_cons_expr.value) != .Cons) { _ = try writer.write(" . "); try self.print_expr(writer, next_cons_expr, kind); break; } _ = try writer.write(" "); } cons_expr = next_cons_expr; } } _ = try writer.write(")"); }, .Closure => try self.print_expr(writer, expr.get_cons(), kind), .Primitive => try writer.print("#{s}", .{&(expr.primitive_name(self) catch "(could not get primitive name)")}), .Nil => if (repr) { _ = try writer.write("nil"); }, } } pub fn print_expr_to_string(self: *Self, expr: *Expr, kind: PrintKind) Error![]const u8 { var string_writer = utils.StringWriter.init(self.allocator); defer string_writer.deinit(); try self.print_expr(string_writer.writer(), expr, kind); return string_writer.get(); } test "print_expr" { var ta = utils.TestAlloc{}; defer ta.deinit(.Panic); errdefer ta.deinit(.NoPanic); const alloc = ta.alloc(); var tl = try Self.new(alloc); defer tl.done(); var list = try tl.make_list([_]*Expr{ try tl.make_int(30), tl.nil, try tl.make_int(-40), try tl.make_list([_]*Expr{ try tl.make_string("Hello\n", .NoCopy), }), }); { const str = try tl.print_expr_to_string(list, .Repr); defer alloc.free(str); try std.testing.expectEqualStrings("(30 nil -40 (\"Hello\\n\"))", str); } { const str = try tl.print_expr_to_string(list, .RawRepr); defer alloc.free(str); try std.testing.expectEqualStrings( "(30 . (nil . (-40 . ((\"Hello\\n\" . nil) . nil))))", str); } { const str = try tl.print_expr_to_string(list, .Display); defer alloc.free(str); // TODO: Better way to display list? try std.testing.expectEqualStrings("(30 -40 (Hello\n))", str); } } const TlExprPair = struct { tl: *Self, expr: *Expr, }; fn fmt_expr_impl(pair: TlExprPair, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { _ = options; try pair.tl.print_expr(writer, pair.expr, if (fmt.len == 0 or comptime std.mem.eql(u8, fmt, "display")) .Display else if (comptime std.mem.eql(u8, fmt, "repr")) .Repr); } pub fn fmt_expr(self: *Self, expr: *Expr) std.fmt.Formatter(fmt_expr_impl) { return .{.data = .{.tl = self, .expr = expr}}; } fn expect_expr(self: *Self, expected: *Expr, result: *Expr) !void { const are_equal = expected.eq(result); if (!are_equal) { std.debug.print( \\ \\Expected this expression: ===================================================== \\{repr} \\But found this: =============================================================== \\{repr} \\=============================================================================== \\ , .{self.fmt_expr(expected), self.fmt_expr(result)}); } try std.testing.expect(are_equal); } // eval and Helpers =========================================================== // Find definition of atom fn assoc(self: *Self, atom: *Expr, env: *Expr) Error!*Expr { var list_iter = env; while (try self.next_in_list_iter(&list_iter)) |item| { if (@as(ExprKind, item.value) != .Cons) { return self.got_zig_error(Error.LispInvalidEnv); } if (atom.eq(try self.car(item))) { return self.cdr(item); } } return self.nil; } test "assoc" { var ta = utils.TestAlloc{}; defer ta.deinit(.Panic); errdefer ta.deinit(.NoPanic); var tl = try Self.new(ta.alloc()); defer tl.done(); const tru = try tl.get_atom("#t"); try tl.expect_expr(tru, try tl.assoc(tru, tl.global_env)); try tl.expect_expr(try tl.make_expr(.{.Primitive = 5}), try tl.assoc(try tl.get_atom("+"), tl.global_env)); } fn bind(self: *Self, vars: *Expr, args: *Expr, env: *Expr) Error!*Expr { return switch (vars.value) { ExprKind.Nil => env, ExprKind.Cons => try self.bind(try self.cdr(vars), try self.cdr(args), try self.tack_pair_to_list(try self.car(vars), try self.car(args), env)), else => try self.tack_pair_to_list(vars, args, env), }; } // Eval every item in list "exprs" fn evlis(self: *Self, exprs: *Expr, env: *Expr) Error!*Expr { return switch (exprs.value) { ExprKind.Cons => try self.cons( try self.eval(try self.car(exprs), env), try self.evlis(try self.cdr(exprs), env) ), else => try self.eval(exprs, env), }; } // Run closure fn reduce(self: *Self, closure: *Expr, args: *Expr, env: *Expr) Error!*Expr { const c = closure.get_cons(); return try self.eval( try self.cdr(try self.car(c)), try self.bind( try self.car(try self.car(c)), try self.evlis(args, env), if ((try self.cdr(c)).not()) self.global_env else try self.cdr(c) ) ); } // Run func with args and env fn apply(self: *Self, callable: *Expr, args: *Expr, env: *Expr) Error!*Expr { return switch (callable.value) { ExprKind.Primitive => try callable.call_primitive(self, args, env), ExprKind.Closure => try self.reduce(callable, args, env), else => blk: { break :blk self.got_lisp_error("value passed to apply isn't callable", callable); } }; } pub fn eval(self: *Self, val: *Expr, env: *Expr) Error!*Expr { // if (debug) std.debug.print("eval: {s}\n", .{try self.debug_print(val)}); const rv = switch (val.value) { ExprKind.Atom => try self.assoc(val, env), ExprKind.Cons => try self.apply( try self.eval(try self.car(val), env), try self.cdr(val), env), else => val, }; // if (debug) std.debug.print("eval return: {s}\n", .{try self.debug_print(rv)}); return rv; } test "eval" { var ta = utils.TestAlloc{}; defer ta.deinit(.Panic); errdefer ta.deinit(.NoPanic); var tl = try Self.new(ta.alloc()); defer tl.done(); try tl.expect_expr(try tl.make_int(6), try tl.eval( try tl.make_list([_]*Expr{ try tl.get_atom("+"), try tl.make_int(1), try tl.make_int(2), try tl.make_int(3), }), tl.global_env )); } // Parsing ==================================================================== const TokenKind = enum { IntValue, Atom, String, Open, Close, Quote, Dot, }; const Token = union (TokenKind) { IntValue: IntType, Atom: []const u8, String: []const u8, Open: void, Close: void, Quote: void, Dot: void, fn eq(self: Token, other: Token) bool { return utils.any_equal(self, other); } }; fn get_token(self: *Self) Error!?Token { if (self.input) |input| { while (self.pos < input.len) { switch (input[self.pos]) { '\n' => { self.lineno += 1; self.pos += 1; }, ' ', '\t' => { self.pos += 1; }, ';' => { while (self.pos < input.len and input[self.pos] != '\n') { self.pos += 1; } }, else => break, } } var token: ?Token = null; var start: usize = self.pos; var first = true; while (self.pos < input.len) { var special_token: ?Token = null; switch (input[self.pos]) { '(' => special_token = Token.Open, ')' => special_token = Token.Close, '\'' => special_token = Token.Quote, '.' => special_token = Token.Dot, ' ', '\n', '\t' => { break; }, '"' => { if (first) { start = self.pos; self.pos += 1; // starting quote var escaped = false; while (true) { if (self.pos >= input.len) return Error.LispInvalidSyntax; const c = input[self.pos]; switch (c) { '\n' => return Error.LispInvalidSyntax, '\\' => escaped = !escaped, '"' => if (escaped) { escaped = false; } else { break; }, else => if (escaped) { escaped = false; }, } self.pos += 1; } self.pos += 1; // ending quote token = Token{.String = input[start..self.pos]}; } break; }, else => { first = false; self.pos += 1; continue; }, } if (token == null and first) { token = special_token.?; self.pos += 1; } break; } const str = input[start..self.pos]; if (token == null and str.len > 0) { const int_value: ?IntType = std.fmt.parseInt(IntType, str, 0) catch null; token = if (int_value) |iv| Token{.IntValue = iv} else Token{.Atom = str}; } return token; } return null; } fn must_get_token(self: *Self) Error!Token { return (try self.get_token()) orelse self.print_zig_error(Error.LispUnexpectedEndOfInput); } fn print_error(self: *Self, reason: []const u8, expr: ?*Expr) void { if (self.error_out) |eo| { eo.print("ERROR on line {}", .{self.lineno}) catch unreachable; if (self.input_name) |in| { eo.print(" of {s}", .{in}) catch unreachable; } eo.print(": {s}\n", .{reason}) catch unreachable; if (expr) |e| { eo.print("Problem is with: {repr}\n", .{self.fmt_expr(e)}) catch unreachable; } } } fn print_zig_error(self: *Self, error_value: Error) Error { self.print_error(@errorName(error_value), null); return error_value; } test "tokenize" { var ta = utils.TestAlloc{}; defer ta.deinit(.Panic); errdefer ta.deinit(.NoPanic); var tl = Self.new_barren(ta.alloc()); defer tl.done(); tl.input = " (x 1( y \"hello\\\"\" ' ; This is a comment\n(24 . ab))c) ; comment at end"; try std.testing.expect((try tl.must_get_token()).eq(Token.Open)); try std.testing.expect((try tl.must_get_token()).eq(Token{.Atom = "x"})); try std.testing.expect((try tl.must_get_token()).eq(Token{.IntValue = 1})); try std.testing.expect((try tl.must_get_token()).eq(Token.Open)); try std.testing.expect((try tl.must_get_token()).eq(Token{.Atom = "y"})); try std.testing.expect((try tl.must_get_token()).eq(Token{.String = "\"hello\\\"\""})); try std.testing.expect((try tl.must_get_token()).eq(Token.Quote)); try std.testing.expect((try tl.must_get_token()).eq(Token.Open)); try std.testing.expect((try tl.must_get_token()).eq(Token{.IntValue = 24})); try std.testing.expect((try tl.must_get_token()).eq(Token.Dot)); try std.testing.expect((try tl.must_get_token()).eq(Token{.Atom = "ab"})); try std.testing.expect((try tl.must_get_token()).eq(Token.Close)); try std.testing.expect((try tl.must_get_token()).eq(Token.Close)); try std.testing.expect((try tl.must_get_token()).eq(Token{.Atom = "c"})); try std.testing.expect((try tl.must_get_token()).eq(Token.Close)); try std.testing.expectError(Error.LispUnexpectedEndOfInput, tl.must_get_token()); } fn parse_list(self: *Self) Error!*Expr { const token = try self.must_get_token(); return switch (token) { TokenKind.Close => self.nil, TokenKind.Dot => dot_blk: { const second = self.must_parse_token(); const expected_close = try self.must_get_token(); if (@as(TokenKind, expected_close) != .Close) { return self.print_zig_error(Error.LispInvalidParens); } break :dot_blk second; }, else => else_blk: { const first = try self.parse_i(token); const second = try self.parse_list(); break :else_blk try self.cons(first, second); } }; } fn parse_quote(self: *Self) Error!*Expr { return try self.cons(try self.get_atom("quote"), try self.cons(try self.must_parse_token(), self.nil)); } fn parse_i(self: *Self, token: Token) Error!*Expr { return switch (token) { TokenKind.Open => self.parse_list(), TokenKind.Quote => self.parse_quote(), TokenKind.Atom => |name| try self.make_atom(name, .Copy), TokenKind.IntValue => |value| try self.make_int(value), TokenKind.String => |literal| blk: { var buf = std.ArrayList(u8).init(self.allocator); defer buf.deinit(); switch (try std.zig.string_literal.parseAppend(&buf, literal)) { .success => {}, else => return Error.LispInvalidSyntax, } break :blk try self.make_string(buf.toOwnedSlice(), .PassOwnership); }, TokenKind.Close => self.print_zig_error(Error.LispInvalidParens), TokenKind.Dot => self.print_zig_error(Error.LispInvalidSyntax), }; } fn must_parse_token(self: *Self) Error!*Expr { return self.parse_i(try self.must_get_token()); } fn parse_tokenizer(self: *Self) Error!?*Expr { var rv: ?*Expr = null; if (try self.get_token()) |t| { defer _ = self.collect(.Unused); rv = try self.eval(try self.parse_i(t), self.global_env); self.parse_return = rv; } else if (self.parse_return != null) { self.parse_return = null; _ = self.collect(.Unused); } return rv; } fn parse_str(self: *Self, input: []const u8) Error!?*Expr { self.set_input(input, null); return self.parse_tokenizer(); } test "parse_str" { var ta = utils.TestAlloc{}; defer ta.deinit(.Panic); errdefer ta.deinit(.NoPanic); var tl = try Self.new(ta.alloc()); defer tl.done(); const n = try tl.keep_expr(try tl.make_int(6)); try tl.expect_expr(n, (try tl.parse_str("(+ 1 2 3)")).?); try std.testing.expectEqualStrings("Hello", (try tl.parse_str("\"Hello\"")).?.get_string().?); } pub fn parse_input(self: *Self) Error!?*Expr { var rv: ?*Expr = null; rv = try self.parse_tokenizer(); return rv; } pub fn parse_all_input(self: *Self, input: []const u8, input_name: ?[]const u8) Error!void { self.set_input(input, input_name); if (utils.starts_with(input, "#!")) { // Skip over shebang line while (true) { self.pos += 1; if (self.pos >= input.len) break; if (input[self.pos] == '\n') { self.pos += 1; break; } } } while (try self.parse_input()) |e| { _ = e; } } test "parse_all_input" { var ta = utils.TestAlloc{}; defer ta.deinit(.Panic); errdefer ta.deinit(.NoPanic); var tl = try Self.new(ta.alloc()); defer tl.done(); try tl.parse_all_input("#!", null); try tl.parse_all_input( \\#!This isn't lisp \\(define a 5) \\(define b 3) \\(define func (lambda (x y) (+ (* x y) y))) , null ); // Make sure both lists and pairs are parsed correctly try tl.parse_all_input( "(define begin (lambda (x . args) (if args (begin . args) x)))\n", null); const n = try tl.keep_expr(try tl.make_int(18)); try tl.expect_expr(n, (try tl.parse_str("(func a b)")).?); } // Custom Primitive Functions ================================================= var custom_primitive_test_value: i64 = 10; fn custom_primitive(self: *Self, value: *Expr) Error!*Expr { defer custom_primitive_test_value = value.value.Int; return self.make_int(custom_primitive_test_value); } test "custom primitive" { var ta = utils.TestAlloc{}; defer ta.deinit(.Panic); errdefer ta.deinit(.NoPanic); var tl = try Self.new(ta.alloc()); defer tl.done(); const custom = [_]GenPrimitive{ .{.name = "cp", .zig_func = custom_primitive}, }; var custom_primitives: [custom.len]Primitive = undefined; try tl.populate_extra_primitives(custom[0..], custom_primitives[0..]); const n = try tl.keep_expr(try tl.make_int(10)); try tl.expect_expr(n, (try tl.parse_str("(cp 20)")).?); try std.testing.expectEqual(@as(i64, 20), custom_primitive_test_value); } // Rest of Primitive Functions ================================================ // (` x): return x fn quote(self: *Self, x: *Expr) Error!*Expr { _ = self; return x; } // (eq? x y): return tru if x equals y else nil pub fn eq(self: *Self, x: *Expr, y: *Expr) Error!*Expr { return self.make_bool(x.eq(y)); } pub fn add(self: *Self, args: *Expr) Error!*Expr { var expr_kind: ?ExprKind = null; var total_string_len: usize = 0; { var check_iter = args; while (try self.next_in_list_iter(&check_iter)) |arg| { if (expr_kind) |ek| { const kind = @as(ExprKind, arg.value); if (ek != kind) { return self.got_lisp_error("inconsistent arg types in +, expected int", arg); } } else { expr_kind = @as(ExprKind, arg.value); } switch (@as(ExprKind, arg.value)) { .String => total_string_len += arg.get_string().?.len, .Int => {}, else => { return self.got_lisp_error("inconsistent arg types in +, expected int", arg); } } } } if (expr_kind) |ek| { switch (ek) { ExprKind.Int => { var list_iter = args; var result: IntType = (try self.next_in_list_iter(&list_iter)).?.value.Int; while (try self.next_in_list_iter(&list_iter)) |arg| { result += arg.value.Int; } return self.make_int(result); }, ExprKind.String => { var list_iter = args; var result: []u8 = try self.allocator.alloc(u8, total_string_len); var got: usize = 0; while (try self.next_in_list_iter(&list_iter)) |arg| { const s = arg.get_string().?; for (s) |c| { result[got] = c; got += 1; } } return self.make_string(result, .PassOwnership); }, else => unreachable, } } return self.nil; } test "add" { var ta = utils.TestAlloc{}; defer ta.deinit(.Panic); errdefer ta.deinit(.NoPanic); var tl = try Self.new(ta.alloc()); defer tl.done(); const n = try tl.keep_expr(try tl.make_int(6)); try tl.expect_expr(n, (try tl.parse_str("(+ 1 2 3)")).?); try std.testing.expectEqualStrings("Hello world", ( try tl.parse_str("(+ \"Hello\" \" world\")")).?.get_string().?); } pub fn subtract(self: *Self, args: *Expr) Error!*Expr { var list_iter = args; var result: IntType = (try self.next_in_list_iter(&list_iter)).?.value.Int; while (try self.next_in_list_iter(&list_iter)) |arg| { result -= arg.value.Int; } return self.make_int(result); } pub fn multiply(self: *Self, args: *Expr) Error!*Expr { var list_iter = args; var result: IntType = (try self.next_in_list_iter(&list_iter)).?.value.Int; while (try self.next_in_list_iter(&list_iter)) |arg| { result *= arg.value.Int; } return self.make_int(result); } pub fn divide(self: *Self, args: *Expr) Error!*Expr { var list_iter = args; var result: IntType = (try self.next_in_list_iter(&list_iter)).?.value.Int; while (try self.next_in_list_iter(&list_iter)) |arg| { result = @divFloor(result, arg.value.Int); } return self.make_int(result); } pub fn less(self: *Self, x: *Expr, y: *Expr) Error!*Expr { return self.make_bool(x.value.Int < y.value.Int); } pub fn @"or"(self: *Self, x: *Expr, y: *Expr) Error!*Expr { return self.make_bool(x.is_true() or y.is_true()); } pub fn @"and"(self: *Self, x: *Expr, y: *Expr) Error!*Expr { return self.make_bool(x.is_true() and y.is_true()); } pub fn @"not"(self: *Self, x: *Expr) Error!*Expr { return self.make_bool(x.not()); } pub fn cond(self: *Self, env: *Expr, args: *Expr) Error!*Expr { var list_iter = args; var rv = self.nil; while (try self.next_in_list_iter(&list_iter)) |cond_value| { var cond_value_it = cond_value; const test_cond = (try self.next_in_list_iter(&cond_value_it)).?; const return_value = (try self.next_in_list_iter(&cond_value_it)).?; if ((try self.eval(test_cond, env)).is_true()) { rv = try self.eval(return_value, env); } } return rv; } test "cond" { var ta = utils.TestAlloc{}; defer ta.deinit(.Panic); errdefer ta.deinit(.NoPanic); var tl = try Self.new(ta.alloc()); defer tl.done(); const n = try tl.keep_expr(try tl.make_int(3)); try tl.expect_expr(n, (try tl.parse_str("(cond ((eq? 'a 'b) 1) ((< 2 1) 2) (#t 3))")).?); } pub fn @"if"(self: *Self, env: *Expr, test_expr: *Expr, then_expr: *Expr, else_expr: *Expr) Error!*Expr { const result_expr = if ((try self.eval(test_expr, env)).is_true()) then_expr else else_expr; return try self.eval(result_expr, env); } test "if" { var ta = utils.TestAlloc{}; defer ta.deinit(.Panic); errdefer ta.deinit(.NoPanic); var tl = try Self.new(ta.alloc()); defer tl.done(); const n = try tl.keep_expr(try tl.make_int(1)); try tl.expect_expr(n, (try tl.parse_str("(if (eq? 'a 'a) 1 2)")).?); } // (let* (a x) (b x) ... (+ a b)) pub fn leta(self: *Self, env: *Expr, args: *Expr) Error!*Expr { var list_iter = args; var this_env = env; while (try self.next_in_list_iter(&list_iter)) |arg| { if (list_iter.is_true()) { var var_value_it = arg; const var_expr = (try self.next_in_list_iter(&var_value_it)).?; const value_expr = (try self.next_in_list_iter(&var_value_it)).?; const value = try self.eval(value_expr, this_env); this_env = try self.tack_pair_to_list(var_expr, value, this_env); } else { return try self.eval(arg, this_env); } } return self.got_zig_error(Error.LispInvalidPrimitiveArgCount); } test "leta" { var ta = utils.TestAlloc{}; defer ta.deinit(.Panic); errdefer ta.deinit(.NoPanic); var tl = try Self.new(ta.alloc()); defer tl.done(); const n = try tl.keep_expr(try tl.make_int(12)); try tl.expect_expr(n, (try tl.parse_str("(let* (a 3) (b (* a a)) (+ a b))")).?); } // (lambda args expr) pub fn lambda(self: *Self, env: *Expr, args: *Expr, expr: *Expr) Error!*Expr { return self.make_expr(.{.Closure = try self.tack_pair_to_list(args, expr, if (env.eq(self.global_env)) self.nil else env)}); } test "lambda" { var ta = utils.TestAlloc{}; defer ta.deinit(.Panic); errdefer ta.deinit(.NoPanic); var tl = try Self.new(ta.alloc()); defer tl.done(); const n = try tl.keep_expr(try tl.make_int(9)); try tl.expect_expr(n, (try tl.parse_str("((lambda (x) (* x x)) 3)")).?); } // (define var expr) pub fn define(self: *Self, env: *Expr, atom: *Expr, expr: *Expr) Error!*Expr { var use_atom = atom; if (@as(ExprKind, use_atom.value) == .String) { use_atom = try self.make_atom(use_atom.get_string().?, .Copy); } if (@as(ExprKind, use_atom.value) != .Atom) { return self.got_lisp_error("define got non-atom", use_atom); } self.global_env = try self.tack_pair_to_list(use_atom, try self.eval(expr, env), env); return use_atom; } test "define" { var ta = utils.TestAlloc{}; defer ta.deinit(.Panic); errdefer ta.deinit(.NoPanic); var tl = try Self.new(ta.alloc()); defer tl.done(); _ = try tl.parse_str("(define x 1)"); _ = try tl.parse_str("(define \"y\" 3)"); const n = try tl.keep_expr(try tl.make_int(4)); try tl.expect_expr(n, (try tl.parse_str("(+ x y)")).?); } pub fn print(self: *Self, args: *Expr) Error!*Expr { if (self.out) |out| { var check_iter = args; while (try self.next_in_list_iter(&check_iter)) |arg| { try self.print_expr(out, arg, .Display); } } return self.nil; } // (progn statement ... return_value) // Eval every statement in args, discarding the result from each except the // last one, which is returned. pub fn progn(self: *Self, init_env: *Expr, statements: *Expr) Error!*Expr { var env = init_env; var result = self.nil; if (statements != self.err) { // TODO: Handle getting an error better here and elsewhere var iter = statements; while (try self.next_in_list_iter(&iter)) |statement| { result = try self.eval(statement, env); env = self.global_env; } } return result; } test "progn" { var ttl = TestTl{}; try ttl.init(); errdefer ttl.ta.deinit(.NoPanic); defer ttl.done(); try ttl.tl.expect_expr(ttl.tl.nil, (try ttl.tl.parse_str("(progn ())")).?); try ttl.tl.parse_all_input( \\(define z (progn \\ (define x 1) \\ (define y (+ x 1)) \\ ((lambda () y)) \\)) , null ); const two = try ttl.tl.keep_expr(try ttl.tl.make_int(2)); try ttl.tl.expect_expr(two, (try ttl.tl.parse_str("z")).?); }