diff --git a/ableos/Cargo.lock b/ableos/Cargo.lock index e4e8b503d..ee8ad1297 100644 --- a/ableos/Cargo.lock +++ b/ableos/Cargo.lock @@ -4,9 +4,9 @@ version = 3 [[package]] name = "ab_glyph" -version = "0.2.13" +version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61caed9aec6daeee1ea38ccf5fb225e4f96c1eeead1b4a5c267324a63cf02326" +checksum = "24606928a235e73cdef55a0c909719cadd72fce573e5713d58cb2952d8f5794c" dependencies = [ "ab_glyph_rasterizer", "libm", @@ -24,7 +24,7 @@ dependencies = [ [[package]] name = "ableos" -version = "0.1.0" +version = "0.1.1" dependencies = [ "ab_glyph", "acpi", @@ -35,13 +35,14 @@ dependencies = [ "facepalm", "genfs", "hashbrown 0.11.2", + "kernel", "lazy_static", "libwasm", "linked_list_allocator", "lliw", "log", + "logos", "pc-beeper", - "pci", "pic8259", "picorand", "pretty-hex", @@ -50,9 +51,9 @@ dependencies = [ "riscv", "rkyv", "serde", - "serde_json", "shadeable", "spin 0.5.2", + "toml", "uart_16550", "unicode-width", "volatile 0.2.7", @@ -73,6 +74,12 @@ dependencies = [ "rsdp", ] +[[package]] +name = "ahash" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8fd72866655d1904d6b0997d0b07ba561047d070fbe29de039031c641b61217" + [[package]] name = "ahash" version = "0.7.6" @@ -106,6 +113,12 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fe8f5a8a398345e52358e18ff07cc17a568fbca5c6f73873d3a62056309603" +[[package]] +name = "beef" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bed554bd50246729a1ec158d08aa3235d1b69d94ad120ebe187e28894787e736" + [[package]] name = "bit_field" version = "0.10.1" @@ -120,9 +133,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bootloader" -version = "0.9.21" +version = "0.9.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a62c8f6168cd106687ee36a2b71a46c4144d73399f72814104d33094b8092fd2" +checksum = "de78decc37247c7cfac5dbf3495c7298c6ac97cb355161caa7e15969c6648e6c" [[package]] name = "cfg-if" @@ -204,6 +217,12 @@ dependencies = [ "log", ] +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + [[package]] name = "genfs" version = "0.1.4" @@ -212,15 +231,25 @@ checksum = "65b9e52a0ffd4c2f11f9f84e8885a40cb99f490971eee78bbd7ddffd6ac023d6" [[package]] name = "getrandom" -version = "0.2.4" +version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "418d37c8b1d42553c93648be529cb70f920d3baf8ef469b74b9638df426e0b4c" +checksum = "d39cd93900197114fa1fcb7ae84ca742095eed9442088988ae74fa744e930e77" dependencies = [ "cfg-if", "libc", "wasi", ] +[[package]] +name = "hashbrown" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96282e96bfcd3da0d3aa9938bedf1e50df3269b6db08b4876d2da0bb1a0841cf" +dependencies = [ + "ahash 0.3.8", + "autocfg", +] + [[package]] name = "hashbrown" version = "0.11.2" @@ -233,7 +262,7 @@ version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8c21d40587b92fa6a6c6e3c1bdbf87d75511db5672f9c93175574b3a00df1758" dependencies = [ - "ahash", + "ahash 0.7.6", ] [[package]] @@ -246,10 +275,13 @@ dependencies = [ ] [[package]] -name = "itoa" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aab8fc367588b89dcee83ab0fd66b72b50b72fa1904d7095045ace2b0c81c35" +name = "kernel" +version = "0.1.2" +dependencies = [ + "lazy_static", + "log", + "versioning", +] [[package]] name = "lazy_static" @@ -262,9 +294,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.118" +version = "0.2.119" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06e509672465a0504304aa87f9f176f2b2b716ed8fb105ebe5c02dc6dce96a94" +checksum = "1bf2e165bb3457c8e098ea76f3e3bc9db55f87aa90d52d0e6be741470916aaa4" [[package]] name = "libm" @@ -275,7 +307,7 @@ checksum = "33a33a362ce288760ec6a508b94caaec573ae7d3bbbd91b87aa0bad4456839db" [[package]] name = "libwasm" version = "0.1.0" -source = "git+https://git.ablecorp.us/able/libwasm.git#a89b8fc701ba0196cc9cca9989d9beb93d02a317" +source = "git+https://git.ablecorp.us/able/libwasm.git#dedbb769ba01a4b75992437e52ca9a5c2bb9e0f9" [[package]] name = "linked_list_allocator" @@ -310,6 +342,30 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "logos" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "427e2abca5be13136da9afdbf874e6b34ad9001dd70f2b103b083a85daa7b345" +dependencies = [ + "logos-derive", +] + +[[package]] +name = "logos-derive" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56a7d287fd2ac3f75b11f19a1c8a874a7d55744bd91f7a1b3e7cf87d4343c36d" +dependencies = [ + "beef", + "fnv", + "proc-macro2", + "quote", + "regex-syntax", + "syn", + "utf8-ranges", +] + [[package]] name = "memchr" version = "2.4.1" @@ -361,15 +417,15 @@ dependencies = [ [[package]] name = "once_cell" -version = "1.9.0" +version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da32515d9f6e6e489d7bc9d84c71b060db7247dc035bbe44eac88cf87486d8d5" +checksum = "87f3e037eac156d1775da914196f0f37741a274155e34a0b7e427c35d2a2ecb9" [[package]] name = "owned_ttf_parser" -version = "0.14.0" +version = "0.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ef05f2882a8b3e7acc10c153ade2631f7bfc8ce00d2bf3fb8f4e9d2ae6ea5c3" +checksum = "4fb1e509cfe7a12db2a90bfa057dfcdbc55a347f5da677c506b53dd099cfec9d" dependencies = [ "ttf-parser", ] @@ -388,14 +444,6 @@ dependencies = [ "x86_64", ] -[[package]] -name = "pci" -version = "0.0.1" -source = "git+https://gitlab.com/robigalia/pci#4e2fddc61825568b1d14d09fdc669389e6c43f02" -dependencies = [ - "bitflags", -] - [[package]] name = "pic8259" version = "0.10.2" @@ -478,9 +526,9 @@ dependencies = [ [[package]] name = "regex" -version = "1.5.4" +version = "1.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d07a8629359eb56f1e2fb1652bb04212c072a87ba68546a04065d525673ac461" +checksum = "1a11647b6b25ff05a515cb92c365cec08801e83423a235b51e231e1808747286" dependencies = [ "aho-corasick", "memchr", @@ -499,7 +547,7 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49c94fda0280985896ed6d8bf0b43bbb5a7f0e39ccc8728ac907ddb4f06dae94" dependencies = [ - "ahash", + "ahash 0.7.6", "core-error", "instant", "libm", @@ -544,9 +592,9 @@ dependencies = [ [[package]] name = "rkyv" -version = "0.7.32" +version = "0.7.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e3791595bf1ee951356964271bea7dafd1e1730e8be812f44a31afc38fa7bba" +checksum = "2cdcf5caf69bcc87b1e3f5427b4f21a32fdd53c2847687bdf9861abb1cdaa0d8" dependencies = [ "hashbrown 0.12.0", "ptr_meta", @@ -556,9 +604,9 @@ dependencies = [ [[package]] name = "rkyv_derive" -version = "0.7.32" +version = "0.7.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca655472e721430bfb5c995a5602278e089c329cde96a0a53e1f711e3ba39c55" +checksum = "a6cf557da1f81b8c7e889c59c9c3abaf6978f7feb156b9579e4f8bf6d7a2bada" dependencies = [ "proc-macro2", "quote", @@ -580,12 +628,6 @@ dependencies = [ "log", ] -[[package]] -name = "ryu" -version = "1.0.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73b4b750c782965c211b42f022f59af1fbceabdd026623714f104152f1ec149f" - [[package]] name = "scopeguard" version = "1.1.0" @@ -618,17 +660,6 @@ dependencies = [ "syn", ] -[[package]] -name = "serde_json" -version = "1.0.79" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e8d9fa5c3b304765ce1fd9c4c8a3de2c8db365a5b91be52f186efc675681d95" -dependencies = [ - "itoa", - "ryu", - "serde", -] - [[package]] name = "shadeable" version = "0.1.0" @@ -646,9 +677,9 @@ checksum = "f2dd574626839106c320a323308629dcb1acfc96e32a8cba364ddc61ac23ee83" [[package]] name = "smartstring" -version = "0.2.9" +version = "0.2.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31aa6a31c0c2b21327ce875f7e8952322acfcfd0c27569a6e18a647281352c9b" +checksum = "e714dff2b33f2321fdcd475b71cec79781a692d846f37f415fb395a1d2bcd48e" dependencies = [ "static_assertions", ] @@ -703,11 +734,20 @@ dependencies = [ "crunchy", ] +[[package]] +name = "toml" +version = "0.5.6" +source = "git+https://github.com/diondokter/toml-rs#c4161aa70202b3992dbec79b76e7a8659713b604" +dependencies = [ + "hashbrown 0.7.2", + "serde", +] + [[package]] name = "ttf-parser" -version = "0.14.0" +version = "0.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ccbe8381883510b6a2d8f1e32905bddd178c11caef8083086d0c0c9ab0ac281" +checksum = "c74c96594835e10fa545e2a51e8709f30b173a092bfd6036ef2cec53376244f3" [[package]] name = "uart_16550" @@ -731,12 +771,23 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" +[[package]] +name = "utf8-ranges" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ae116fef2b7fea257ed6440d3cfcff7f190865f170cdad00bb6465bf18ecba" + [[package]] name = "version_check" version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" +[[package]] +name = "versioning" +version = "0.1.2" +source = "git+https://git.ablecorp.us/able/versioning#ef472283e6e7a2e395ee56434087b3a6fad53ff2" + [[package]] name = "volatile" version = "0.2.7" diff --git a/ableos/Cargo.toml b/ableos/Cargo.toml index bdb49ac2a..ee6ede2e2 100644 --- a/ableos/Cargo.toml +++ b/ableos/Cargo.toml @@ -1,7 +1,7 @@ [package] edition = "2021" name = "ableos" -version = "0.1.0" +version = "0.1.1" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [profile.release] @@ -9,6 +9,9 @@ panic = "abort" [package.metadata.bootimage] run-args = [ + "--nodefaults", + + "-cpu", "Broadwell-v3", @@ -17,27 +20,24 @@ run-args = [ "-smp", "cores=2", - # An example gpu used with ableOS - "-device", - "virtio-gpu", - # An example disk used with ableOS - "-device", - "virtio-blk-pci,drive=drive0,id=virtblk0,num-queues=4", + "-device", #"ati-vga", + "cirrus-vga", + + + + + # "-device", + # "virtio-blk-pci,drive=drive0,id=virtblk0,num-queues=4", # A simple example of a boot image - "-drive", - "file=disk.qcow2,if=none,id=drive0", + # "-drive", + # "file=disk.qcow2,if=none,id=drive0", + # "-device", + # "virtio-rng", - - - "-device", -"virtio-rng", - - -"-qmp", - "unix:../qmp-sock,server,nowait" - + # "-qmp", + # "unix:../qmp-sock,server,nowait" ] test-args = [ @@ -48,7 +48,10 @@ test-args = [ ] [dependencies] -linked_list_allocator = "0.9.0" + + + +linked_list_allocator = "0.9.0" lliw = "0.2.0" # qoi_rs = "*" spin = "0.5.2" @@ -65,15 +68,14 @@ genfs = "0.1.0" # pc-beeper = "0.1.0" rhai = "1.5" -pci = {git="https://gitlab.com/robigalia/pci"} +# pci = {git="https://gitlab.com/robigalia/pci"} libwasm = {git="https://git.ablecorp.us:443/able/libwasm.git"} acpi = "4.1.0" - -# [dependencies.ockam] -# version = "0.46.0" -# no-default-features = false -# features = ["alloc"] +[dependencies.logos] +version = "0.12.0" +default-features = false +features = ["export_derive"] [dependencies.rdrand] @@ -81,16 +83,15 @@ version = "0.8.1" default-features = false +[dependencies.kernel] +path = "../kernel" [dependencies.serde] version = "*" default-features = false features = ["derive", "alloc"] -[dependencies.serde_json] -version = "*" -default-features = false -features = ["alloc"] + [dependencies.hashbrown] version = "0.11.2" @@ -113,6 +114,15 @@ git = "https://git.ablecorp.us:443/able/y-compositor-protocol.git" [dependencies.ext2] git = "https://git.ablecorp.us:443/able/ext2-rs.git" + + + +[dependencies.toml] +git = "https://github.com/diondokter/toml-rs" +# version = "0.5.8" +default-features = false + + [dependencies.shadeable] path = "../shadeable" diff --git a/ableos/assets/kernel.toml b/ableos/assets/kernel.toml new file mode 100644 index 000000000..b666058d5 --- /dev/null +++ b/ableos/assets/kernel.toml @@ -0,0 +1,12 @@ +[boot] +system_processes = [] +user_processes = ["shell"] + +[logging] +enabled = false +level = "Trace" + +[tests] +run_tests = false +run_demos = false +run_shader_tests = false \ No newline at end of file diff --git a/ableos/assets/kernel_config.json b/ableos/assets/kernel_config.json deleted file mode 100644 index 88b0866c8..000000000 --- a/ableos/assets/kernel_config.json +++ /dev/null @@ -1,7 +0,0 @@ - { - "logging_level": "Trace", - "logger_padding": 10, - "run_tests": false, - "run_demos": false, - "run_shader_tests": false - } \ No newline at end of file diff --git a/ableos/assets/key_event.txt b/ableos/assets/key_event.txt new file mode 100644 index 000000000..0617522d8 --- /dev/null +++ b/ableos/assets/key_event.txt @@ -0,0 +1,17 @@ +pub struct KeyEvent{ + lctrl 1 + rctrl 2 + lalt 3 + ralt 4 + lsup 5 + rsup 6 + lshift 7 + rshift 8 + caps 9 + + down 10 + # Keycodes + key 11-32 +} + + diff --git a/ableos/src/alias_table/mod.rs b/ableos/src/alias_table/mod.rs index 36d3d1d8b..3457b66b7 100644 --- a/ableos/src/alias_table/mod.rs +++ b/ableos/src/alias_table/mod.rs @@ -1,4 +1,3 @@ -use alloc::string::{String, ToString}; use hashbrown::HashMap; lazy_static::lazy_static! { diff --git a/ableos/src/allocator/aalloc.rs b/ableos/src/allocator/aalloc.rs index 652c74a8c..f67e60f42 100644 --- a/ableos/src/allocator/aalloc.rs +++ b/ableos/src/allocator/aalloc.rs @@ -9,6 +9,11 @@ pub struct AAloc; unsafe impl GlobalAlloc for AAloc { unsafe fn alloc(&self, _layout: Layout) -> *mut u8 { + println!("Allocating memory"); + + println!("{}", _layout.size()); + println!("{}", _layout.align()); + null_mut() } diff --git a/ableos/src/allocator/mod.rs b/ableos/src/allocator/mod.rs index 45a1f21fd..d58069824 100644 --- a/ableos/src/allocator/mod.rs +++ b/ableos/src/allocator/mod.rs @@ -8,13 +8,7 @@ pub const HEAP_MULTIPLIER: usize = 100000; pub const HEAP_BASE: usize = 100; pub const HEAP_SIZE: usize = HEAP_BASE * HEAP_MULTIPLIER; -// X86 alloc should be in arch/drivers/x86/alloc.rs -/* -use crate::arch::drivers::allocator::Dummy; -#[global_allocator] -static ALLOCATOR: Dummy = Dummy; -*/ use linked_list_allocator::LockedHeap; #[global_allocator] @@ -22,5 +16,7 @@ pub static ALLOCATOR: LockedHeap = LockedHeap::empty(); #[alloc_error_handler] fn alloc_error_handler(layout: alloc::alloc::Layout) -> ! { + // error!("allocation error: {:?}", layout); + panic!("allocation error: {:?}", layout) } diff --git a/ableos/src/arch/x86_64/drivers/allocator.rs b/ableos/src/arch/x86_64/drivers/allocator.rs index 2b8c708b2..353e0e027 100644 --- a/ableos/src/arch/x86_64/drivers/allocator.rs +++ b/ableos/src/arch/x86_64/drivers/allocator.rs @@ -1,5 +1,5 @@ use alloc::alloc::{GlobalAlloc, Layout}; -// use core::alloc::{GlobalAlloc, Layout}; + use crate::allocator::{HEAP_SIZE, HEAP_START}; use core::ptr::null_mut; use x86_64::{ diff --git a/ableos/src/arch/x86_64/drivers/serial.rs b/ableos/src/arch/x86_64/drivers/serial.rs index 16703c4e8..85b29cc9c 100644 --- a/ableos/src/arch/x86_64/drivers/serial.rs +++ b/ableos/src/arch/x86_64/drivers/serial.rs @@ -2,19 +2,19 @@ use lazy_static::lazy_static; use spin::Mutex; use uart_16550::SerialPort; lazy_static! { - pub static ref SERIAL1: Mutex = { - let mut serial_port = unsafe { SerialPort::new(0x3F8) }; - serial_port.init(); - Mutex::new(serial_port) - }; + pub static ref SERIAL1: Mutex = { + let mut serial_port = unsafe { SerialPort::new(0x3F8) }; + serial_port.init(); + Mutex::new(serial_port) + }; } #[doc(hidden)] pub fn _print(args: ::core::fmt::Arguments) { - use core::fmt::Write; - SERIAL1 - .lock() - .write_fmt(args) - .expect("Printing to serial failed"); + use core::fmt::Write; + SERIAL1 + .lock() + .write_fmt(args) + .expect("Printing to serial failed"); } /// Prints to the host through the serial interface. #[macro_export] diff --git a/ableos/src/arch/x86_64/init.rs b/ableos/src/arch/x86_64/init.rs index ea1046685..75faf68c6 100644 --- a/ableos/src/arch/x86_64/init.rs +++ b/ableos/src/arch/x86_64/init.rs @@ -5,6 +5,12 @@ use super::{gdt, interrupts}; /// x86_64 initialization pub fn init() { + use crate::network::socket::SimpleSock; + use crate::relib::network::socket::Socket; + + let mut log_socket_id = SimpleSock::new(); + log_socket_id.register_protocol("Logger".to_string()); + let result = logger::init(); match result { Ok(_) => {} diff --git a/ableos/src/arch/x86_64/interrupts.rs b/ableos/src/arch/x86_64/interrupts.rs index 1429a9b83..f16208aef 100644 --- a/ableos/src/arch/x86_64/interrupts.rs +++ b/ableos/src/arch/x86_64/interrupts.rs @@ -1,9 +1,11 @@ use crate::{ arch::{drivers::vga::WRITER, gdt}, kernel_state::KERNEL_STATE, - print, println, KEYBUFF, + print, println, + rhai_shell::KEYBUFF, }; +use cpuio::outb; use lazy_static::lazy_static; use pic8259::ChainedPics; use spin; @@ -19,6 +21,8 @@ pub static PICS: spin::Mutex = pub enum InterruptIndex { Timer = PIC_1_OFFSET, Keyboard, + // SecondInterrupt = PIC_2_OFFSET, + Cmos = 0x70, } impl InterruptIndex { fn as_u8(self) -> u8 { @@ -37,10 +41,18 @@ lazy_static! { idt.breakpoint.set_handler_fn(breakpoint_handler); unsafe { idt.double_fault.set_handler_fn(double_fault_handler) - .set_stack_index(gdt::DOUBLE_FAULT_IST_INDEX); // new + .set_stack_index(gdt::DOUBLE_FAULT_IST_INDEX); } + + // This gives fast interrupts + set_pit_frequency(1000); + idt[InterruptIndex::Timer.as_usize()].set_handler_fn(timer_interrupt_handler); idt[InterruptIndex::Keyboard.as_usize()] .set_handler_fn(keyboard_interrupt_handler); + + idt[6].set_handler_fn(floppy_disk_interrupt_handler); + + idt }; } @@ -55,7 +67,7 @@ extern "x86-interrupt" fn double_fault_handler( panic!("EXCEPTION: DOUBLE FAULT\n{:#?}", stack_frame); } extern "x86-interrupt" fn timer_interrupt_handler(_stack_frame: InterruptStackFrame) { - crate::kmain::tick(); + kernel::tick(); unsafe { PICS.lock() .notify_end_of_interrupt(InterruptIndex::Timer.as_u8()); @@ -90,6 +102,7 @@ extern "x86-interrupt" fn keyboard_interrupt_handler(_stack_frame: InterruptStac // Backspace 8 => { WRITER.lock().backspace(); + KEYBUFF.lock().push(8_u8 as _); // print!(" "); // WRITER.lock().backspace(); } @@ -126,16 +139,17 @@ extern "x86-interrupt" fn keyboard_interrupt_handler(_stack_frame: InterruptStac } } -/* -extern "x86-interrupt" fn page_fault_handler( - stack_frame: InterruptStackFrame, - error_code: PageFaultErrorCode, -) { - use x86_64::registers::control::Cr2; - println!["Exception: Page Fault"]; - println!["Address: {:?}", Cr2::read()]; - println!["Error Code: {:?}", error_code]; - println!["{:#?}", stack_frame]; - sloop(); +extern "x86-interrupt" fn floppy_disk_interrupt_handler(_stack_frame: InterruptStackFrame) { + println!("EXCEPTION: FLOPPY DISK"); +} + +fn set_pit_frequency(freq: u32) { + let divisor: u16 = (1193180 / freq).try_into().unwrap(); + + unsafe { + outb(0x36, 0x43); + + outb((divisor & 0xFF) as u8, 0x40); + outb((divisor >> 8) as u8, 0x40); + } } -*/ diff --git a/ableos/src/arch/x86_64/memory.rs b/ableos/src/arch/x86_64/memory.rs index 9c42a182e..10725d02f 100644 --- a/ableos/src/arch/x86_64/memory.rs +++ b/ableos/src/arch/x86_64/memory.rs @@ -1,112 +1,112 @@ use bootloader::bootinfo::{MemoryMap, MemoryRegionType}; use x86_64::{ - structures::paging::{ - FrameAllocator, Mapper, OffsetPageTable, Page, PageTable, PhysFrame, Size4KiB, - }, - PhysAddr, VirtAddr, + structures::paging::{ + FrameAllocator, Mapper, OffsetPageTable, Page, PageTable, PhysFrame, Size4KiB, + }, + PhysAddr, VirtAddr, }; pub unsafe fn init(physical_memory_offset: VirtAddr) -> OffsetPageTable<'static> { - let level_4_table = active_level_4_table(physical_memory_offset); - OffsetPageTable::new(level_4_table, physical_memory_offset) + let level_4_table = active_level_4_table(physical_memory_offset); + OffsetPageTable::new(level_4_table, physical_memory_offset) } unsafe fn active_level_4_table(physical_memory_offset: VirtAddr) -> &'static mut PageTable { - use x86_64::registers::control::Cr3; + use x86_64::registers::control::Cr3; - let (level_4_table_frame, _) = Cr3::read(); + let (level_4_table_frame, _) = Cr3::read(); - let phys = level_4_table_frame.start_address(); - let virt = physical_memory_offset + phys.as_u64(); - let page_table_ptr: *mut PageTable = virt.as_mut_ptr(); + let phys = level_4_table_frame.start_address(); + let virt = physical_memory_offset + phys.as_u64(); + let page_table_ptr: *mut PageTable = virt.as_mut_ptr(); - // THIS IS UNSAFE - &mut *page_table_ptr + // THIS IS UNSAFE + &mut *page_table_ptr } fn translate_addr_inner(addr: VirtAddr, physical_memory_offset: VirtAddr) -> Option { - use x86_64::registers::control::Cr3; - use x86_64::structures::paging::page_table::FrameError; + use x86_64::registers::control::Cr3; + use x86_64::structures::paging::page_table::FrameError; - let (level_4_table_frame, _) = Cr3::read(); + let (level_4_table_frame, _) = Cr3::read(); - let table_indexes = [ - addr.p4_index(), - addr.p3_index(), - addr.p2_index(), - addr.p1_index(), - ]; - let mut frame = level_4_table_frame; + let table_indexes = [ + addr.p4_index(), + addr.p3_index(), + addr.p2_index(), + addr.p1_index(), + ]; + let mut frame = level_4_table_frame; - for &index in &table_indexes { - // convert the frame into a page table reference - let virt = physical_memory_offset + frame.start_address().as_u64(); - let table_ptr: *const PageTable = virt.as_ptr(); - let table = unsafe { &*table_ptr }; + for &index in &table_indexes { + // convert the frame into a page table reference + let virt = physical_memory_offset + frame.start_address().as_u64(); + let table_ptr: *const PageTable = virt.as_ptr(); + let table = unsafe { &*table_ptr }; - let entry = &table[index]; - frame = match entry.frame() { - Ok(frame) => frame, - Err(FrameError::FrameNotPresent) => return None, - Err(FrameError::HugeFrame) => panic!["huge pages not supported"], - }; - } + let entry = &table[index]; + frame = match entry.frame() { + Ok(frame) => frame, + Err(FrameError::FrameNotPresent) => return None, + Err(FrameError::HugeFrame) => panic!["huge pages not supported"], + }; + } - Some(frame.start_address() + u64::from(addr.page_offset())) + Some(frame.start_address() + u64::from(addr.page_offset())) } pub unsafe fn translate_addr(addr: VirtAddr, physical_memory_offset: VirtAddr) -> Option { - translate_addr_inner(addr, physical_memory_offset) + translate_addr_inner(addr, physical_memory_offset) } pub fn create_example_mapping( - page: Page, - mapper: &mut OffsetPageTable, - frame_allocator: &mut impl FrameAllocator, + page: Page, + mapper: &mut OffsetPageTable, + frame_allocator: &mut impl FrameAllocator, ) { - use x86_64::structures::paging::PageTableFlags as Flags; + use x86_64::structures::paging::PageTableFlags as Flags; - let frame = PhysFrame::containing_address(PhysAddr::new(0xb8000)); - let flags = Flags::PRESENT | Flags::WRITABLE; + let frame = PhysFrame::containing_address(PhysAddr::new(0xb8000)); + let flags = Flags::PRESENT | Flags::WRITABLE; - let map_to_result = unsafe { mapper.map_to(page, frame, flags, frame_allocator) }; - map_to_result.expect("map_to failed").flush(); + let map_to_result = unsafe { mapper.map_to(page, frame, flags, frame_allocator) }; + map_to_result.expect("map_to failed").flush(); } pub struct EmptyFrameAllocator; unsafe impl FrameAllocator for EmptyFrameAllocator { - fn allocate_frame(&mut self) -> Option> { - None - } + fn allocate_frame(&mut self) -> Option> { + None + } } pub struct BootInfoFrameAllocator { - memory_map: &'static MemoryMap, - next: usize, + memory_map: &'static MemoryMap, + next: usize, } impl BootInfoFrameAllocator { - pub unsafe fn init(memory_map: &'static MemoryMap) -> Self { - Self { - memory_map, - next: 0, - } - } + pub unsafe fn init(memory_map: &'static MemoryMap) -> Self { + Self { + memory_map, + next: 0, + } + } - fn usable_frames(&self) -> impl Iterator { - let regions = self.memory_map.iter(); - let usable_regions = regions.filter(|r| r.region_type == MemoryRegionType::Usable); - let addr_range = usable_regions.map(|r| r.range.start_addr()..r.range.end_addr()); - let frame_address = addr_range.flat_map(|r| r.step_by(4096)); - frame_address.map(|addr| PhysFrame::containing_address(PhysAddr::new(addr))) - } + fn usable_frames(&self) -> impl Iterator { + let regions = self.memory_map.iter(); + let usable_regions = regions.filter(|r| r.region_type == MemoryRegionType::Usable); + let addr_range = usable_regions.map(|r| r.range.start_addr()..r.range.end_addr()); + let frame_address = addr_range.flat_map(|r| r.step_by(4096)); + frame_address.map(|addr| PhysFrame::containing_address(PhysAddr::new(addr))) + } } unsafe impl FrameAllocator for BootInfoFrameAllocator { - fn allocate_frame(&mut self) -> Option> { - let frame = self.usable_frames().nth(self.next); - self.next += 1; - frame - } + fn allocate_frame(&mut self) -> Option> { + let frame = self.usable_frames().nth(self.next); + self.next += 1; + frame + } } diff --git a/ableos/src/boot_conf.rs b/ableos/src/boot_conf.rs index 1678a8c82..e71128784 100644 --- a/ableos/src/boot_conf.rs +++ b/ableos/src/boot_conf.rs @@ -1,5 +1,4 @@ use log::LevelFilter; -// use rkyv::{Deserialize, Serialize}; use serde::{Deserialize, Serialize}; #[derive(Serialize, Debug, Deserialize)] @@ -19,29 +18,21 @@ pub enum LogLevel { } #[derive(Serialize, Debug, Deserialize)] -pub struct BootConfig { - pub logging_level: LogLevel, - pub logger_padding: usize, - pub run_tests: bool, - pub run_demos: bool, - pub run_shader_tests: bool, +pub struct KernelConfig { + pub boot: BootConfig, + pub logging: LoggingConfig, + pub tests: TestsConfig, } -impl BootConfig { +impl KernelConfig { pub fn new() -> Self { - let data = include_str!("../assets/kernel_config.json"); - - // Parse the string of data into a Person object. This is exactly the - // same function as the one that produced serde_json::Value above, but - // now we are asking it for a Person as output. - let p: BootConfig = serde_json::from_str(data).unwrap(); - // info!("{:?}", p); + let p: KernelConfig = toml::from_str(include_str!("../assets/kernel.toml")).unwrap(); p } pub fn log_level(&self) -> LevelFilter { use LevelFilter::*; - match self.logging_level { + match self.logging.level { LogLevel::Off => Off, LogLevel::Error => Error, LogLevel::Warn => Warn, @@ -51,3 +42,20 @@ impl BootConfig { } } } + +#[derive(Serialize, Debug, Deserialize)] +pub struct LoggingConfig { + pub enabled: bool, + pub level: LogLevel, +} +#[derive(Serialize, Debug, Deserialize)] +pub struct TestsConfig { + pub run_tests: bool, + pub run_demos: bool, + pub run_shader_tests: bool, +} + +#[derive(Serialize, Debug, Deserialize)] +pub struct BootConfig { + pub processes: Vec, +} diff --git a/ableos/src/devices/character_devs/dev_null.rs b/ableos/src/devices/character_devs/dev_null.rs index 405fb2fa3..cb9dff76a 100644 --- a/ableos/src/devices/character_devs/dev_null.rs +++ b/ableos/src/devices/character_devs/dev_null.rs @@ -1,6 +1,4 @@ -use alloc::string::String; - -use crate::character_device::CharacterDevice; +use kernel::device_interface::character::CharacterDevice; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -22,4 +20,12 @@ impl CharacterDevice for DevNull { fn write_char(&mut self, _: char) -> bool { true } + + fn reset(&mut self) { + todo!() + } + + fn initialize(&mut self) -> bool { + todo!() + } } diff --git a/ableos/src/devices/character_devs/dev_unicode.rs b/ableos/src/devices/character_devs/dev_unicode.rs index aa25ca0fa..0ba031909 100644 --- a/ableos/src/devices/character_devs/dev_unicode.rs +++ b/ableos/src/devices/character_devs/dev_unicode.rs @@ -1,4 +1,4 @@ -use crate::character_device::CharacterDevice; +use kernel::device_interface::character::CharacterDevice; #[derive(Debug)] pub struct DevUnicode { @@ -29,6 +29,15 @@ impl CharacterDevice for DevUnicode { true } + + fn reset(&mut self) { + self.next_write_char = 0x00 as char; + self.next_read_char = 0x00 as char; + } + + fn initialize(&mut self) -> bool { + true + } } fn add1_char(c: char) -> char { diff --git a/ableos/src/devices/character_devs/dev_zero.rs b/ableos/src/devices/character_devs/dev_zero.rs index 09a1ad44e..f5cc3b6ca 100644 --- a/ableos/src/devices/character_devs/dev_zero.rs +++ b/ableos/src/devices/character_devs/dev_zero.rs @@ -1,4 +1,4 @@ -use crate::character_device::CharacterDevice; +use kernel::device_interface::character::CharacterDevice; #[derive(Debug)] pub struct DevZero; @@ -19,4 +19,10 @@ impl CharacterDevice for DevZero { fn write_char(&mut self, _: char) -> bool { true } + + fn reset(&mut self) {} + + fn initialize(&mut self) -> bool { + true + } } diff --git a/ableos/src/devices/character_devs/mod.rs b/ableos/src/devices/character_devs/mod.rs index 061ae6e00..9a2f29485 100644 --- a/ableos/src/devices/character_devs/mod.rs +++ b/ableos/src/devices/character_devs/mod.rs @@ -1,3 +1,5 @@ pub mod dev_null; pub mod dev_unicode; pub mod dev_zero; + +pub use kernel::device_interface::character::CharacterDevice; diff --git a/ableos/src/devices/id.rs b/ableos/src/devices/id.rs new file mode 100644 index 000000000..f2f286ddb --- /dev/null +++ b/ableos/src/devices/id.rs @@ -0,0 +1,15 @@ +#[derive(Debug)] +pub enum Vendor { + Unknown = 0, + + Ati = 1002, +} + +pub fn match_vendor(id: u16) -> Vendor { + use Vendor::*; + match id { + 1002 => Ati, + + _ => Unknown, + } +} diff --git a/ableos/src/devices/mod.rs b/ableos/src/devices/mod.rs index 132c3f874..fb6d00426 100644 --- a/ableos/src/devices/mod.rs +++ b/ableos/src/devices/mod.rs @@ -1,20 +1,15 @@ pub mod character_devs; +pub mod id; pub mod pci_inner; -use alloc::{ - boxed::Box, - string::{String, ToString}, -}; use hashbrown::HashMap; -use pci::PCIDevice; -use crate::character_device::CharacterDevice; +use kernel::device_interface::character::CharacterDevice; // FIXME: This is a hack to hold a device. // #[derive(Debug)] pub enum Device { Character(Box), - Pci(PCIDevice), } unsafe impl Sync for Device {} unsafe impl Send for Device {} diff --git a/ableos/src/devices/pci_inner.rs b/ableos/src/devices/pci_inner.rs index d0f5fc50e..a85c83252 100644 --- a/ableos/src/devices/pci_inner.rs +++ b/ableos/src/devices/pci_inner.rs @@ -1,56 +1,55 @@ //! map the DeviceClass via -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub enum DeviceClass { - UnclassifiedDevice = 0, - MassStorageController = 0x01, - NetworkController = 0x02, - DisplayController = 0x03, - MultimediaController = 0x04, - MemoryController = 0x05, - BridgeDevice = 0x06, +//! +//! - CommunicationController = 0x07, - GenericSystemPeripheral = 0x08, - InputDevice = 0x09, - DockingStation = 0x0a, - Processor = 0x0b, - SerialBusController = 0x0c, - WirelessController = 0x0d, - IntelligentController = 0x0e, - SatelliteCommunicationController = 0x0f, - EncryptionController = 0x10, - SignalProcessingController = 0x11, +#[allow(dead_code)] +fn scan_pci_bus() {} - // 14 - // 15 - // 16 - Coprocessor = 40, - // 64 +pub enum Vendors { + ThreeDfxInteractiveInc = 0x121a, + ThreeDLabs = 0x3d3d, + AllianceSemiconductorCorp = 0x1142, + ARKLogicInc = 0xedd8, + ATITechnologiesInc = 0x1002, + AvanceLogicIncALI = 0x1005, + ChipsandTechnologies = 0x102c, + CirrusLogic = 0x1013, + Compaq = 0x0e11, + CyrixCorp = 0x1078, + DiamondMultimediaSystems = 0x1092, + DigitalEquipmentCorp = 0x1011, + Iit = 0x1061, + IntegratedMicroSolutionsInc = 0x10e0, + IntelCorp = 0x8086, + IntergraphicsSystems = 0x10ea, + MacronixInc = 0x10d9, + MatroxGraphicsInc = 0x102b, + MiroComputersProductsAG = 0x1031, + NationalSemiconductorCorp = 0x100b, + NeoMagicCorp = 0x10c8, + Number9ComputerCompany = 0x105d, + NVidiaCorporation = 0x10de, + NVidiaSgsthomson = 0x12d2, + OakTechnologyInc = 0x104e, + QuantumDesignsHKLtd = 0x1098, + Real3D = 0x003d, + Rendition = 0x1163, + S3Inc = 0x5333, + SierraSemiconductor = 0x10a8, + SiliconIntegratedSystemsSiS = 0x1039, + SiliconMotionInc = 0x126f, + STBSystemsInc = 0x10b4, + TexasInstruments = 0x104c, + ToshibaAmericaInfoSystems = 0x1179, + TridentMicrosystems = 0x1023, + TsengLabsInc = 0x100c, + TundraSemiconductorCorp = 0x10e3, + VIATechnologiesInc = 0x1106, + VMWareInc = 0x15ad, + Weitek = 0x100e, + Unknown = 0xffff, } -impl DeviceClass { - pub fn from_u8(val: u8) -> DeviceClass { - match val { - 0x00 => DeviceClass::UnclassifiedDevice, - 0x01 => DeviceClass::MassStorageController, - 0x02 => DeviceClass::NetworkController, - 0x03 => DeviceClass::DisplayController, - 0x04 => DeviceClass::MultimediaController, - 0x05 => DeviceClass::MemoryController, - 0x06 => DeviceClass::BridgeDevice, - 0x07 => DeviceClass::CommunicationController, - 0x08 => DeviceClass::GenericSystemPeripheral, - 0x09 => DeviceClass::InputDevice, - 0x0a => DeviceClass::DockingStation, - 0x0b => DeviceClass::Processor, - 0x0c => DeviceClass::SerialBusController, - 0x0d => DeviceClass::WirelessController, - 0x0e => DeviceClass::IntelligentController, - 0x0f => DeviceClass::SatelliteCommunicationController, - 0x10 => DeviceClass::EncryptionController, - 0x11 => DeviceClass::SignalProcessingController, - 0x40 => DeviceClass::Coprocessor, - _ => DeviceClass::UnclassifiedDevice, - } - } +pub struct PciDevice { + pub vendor: Vendors, } diff --git a/ableos/src/driver_traits/mod.rs b/ableos/src/driver_traits/mod.rs index ec4063f2f..b832ebf91 100644 --- a/ableos/src/driver_traits/mod.rs +++ b/ableos/src/driver_traits/mod.rs @@ -1,4 +1,2 @@ pub mod graphics; pub mod serial; - -pub mod character_device; diff --git a/ableos/src/experiments/absi.rs b/ableos/src/experiments/absi.rs index 6c824d917..aae1bee42 100644 --- a/ableos/src/experiments/absi.rs +++ b/ableos/src/experiments/absi.rs @@ -1,5 +1,3 @@ - -/* // TODO improve tokenizer/parser pub fn colorify(eval: &str) { let y = eval.split("$"); @@ -63,8 +61,48 @@ pub fn colorify(eval: &str) { } } +use logos::Logos; +#[derive(Logos, Debug, PartialEq)] +pub enum Token { + // Hex(u32), + #[regex(r"\$RED\$")] + Red, + #[regex(r"\$RESET\$")] + Reset, -*/ -pub fn colorify(eval: &str) {} + #[regex("[a-zA-Z!@#$%^&*\">()\n ]+", parse_text, priority = 2)] + Text(String), + + #[error] + #[regex(r"[ \t\n\f]+", logos::skip)] + Error, +} +pub fn colorify_2(eval: &str) { + let lexer = Token::lexer(eval); + for token in lexer { + use Token::*; + match token { + Red => { + set_vga_color(Color::Red, Color::Black); + } + Reset => { + set_vga_color(Color::White, Color::Black); + } + Text(text) => { + kprint!("{}", text); + } + err => { + error!("Error parsing {:?}", err); + } + } + } +} +use logos::Lexer; + +use crate::kprint; +fn parse_text(lex: &mut Lexer) -> Option { + let slice = lex.slice(); + Some(String::from(slice)) +} diff --git a/ableos/src/experiments/futex.rs b/ableos/src/experiments/futex.rs index 13b1ac89d..6453a5f50 100644 --- a/ableos/src/experiments/futex.rs +++ b/ableos/src/experiments/futex.rs @@ -1,7 +1,5 @@ use core::time::Duration; -use alloc::vec::Vec; - // pub struct Duration {} pub struct AtomicU32(u32); diff --git a/ableos/src/experiments/info.rs b/ableos/src/experiments/info.rs index 901a3d4f5..3455af3d8 100644 --- a/ableos/src/experiments/info.rs +++ b/ableos/src/experiments/info.rs @@ -1,4 +1,3 @@ -#![feature(asm)] #![cfg_attr( not(any(target_arch = "x86_64", target_arch = "x86")), allow(dead_code) diff --git a/ableos/src/experiments/kinfo.rs b/ableos/src/experiments/kinfo.rs index 193d0acac..c048f78fb 100644 --- a/ableos/src/experiments/kinfo.rs +++ b/ableos/src/experiments/kinfo.rs @@ -1,34 +1,34 @@ // Can be standardized // NOTE: Move this to relib pub struct SemanticVersion { - pub major: u8, - pub minor: u8, - pub patch: u8, + pub major: u8, + pub minor: u8, + pub patch: u8, } impl core::fmt::Display for SemanticVersion { - fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { - write!(f, "v{}.{}.{}", self.major, self.minor, self.patch) - } + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + write!(f, "v{}.{}.{}", self.major, self.minor, self.patch) + } } // NOTE: Move to somewhere else lazy_static! { - pub static ref KINFO: KernelInfo = KernelInfo { - kernel_version: SemanticVersion { - major: 0, - minor: 0, - patch: 0, - }, - memory: SystemMemory { used: 0, total: 0 } - }; + pub static ref KINFO: KernelInfo = KernelInfo { + kernel_version: SemanticVersion { + major: 0, + minor: 0, + patch: 0, + }, + memory: SystemMemory { used: 0, total: 0 } + }; } /// simple info you would want to know in a neofetch like program pub struct KernelInfo { - // os: String, - // host: String, - pub kernel_version: SemanticVersion, - // cpu: String, - // gpu: String, - pub memory: SystemMemory, + // os: String, + // host: String, + pub kernel_version: SemanticVersion, + // cpu: String, + // gpu: String, + pub memory: SystemMemory, } use super::systeminfo::SystemMemory; use lazy_static::lazy_static; diff --git a/ableos/src/experiments/server.rs b/ableos/src/experiments/server.rs index 42d82acf0..c8576064c 100644 --- a/ableos/src/experiments/server.rs +++ b/ableos/src/experiments/server.rs @@ -1,10 +1,10 @@ pub trait Server { - /// Initialize the server and return a number - fn initialize() -> u32; - /// kill the server - fn kill() -> bool; - // put data in the servers outbox - fn send(); - // put data in the servers inbox and notify it - fn recieve(); + /// Initialize the server and return a number + fn initialize() -> u32; + /// kill the server + fn kill() -> bool; + // put data in the servers outbox + fn send(); + // put data in the servers inbox and notify it + fn recieve(); } diff --git a/ableos/src/experiments/y_compositor/mod.rs b/ableos/src/experiments/y_compositor/mod.rs index a09d7f8dd..32bd83877 100644 --- a/ableos/src/experiments/y_compositor/mod.rs +++ b/ableos/src/experiments/y_compositor/mod.rs @@ -1,3 +1,3 @@ //! +pub mod compositor; pub mod window; -pub mod compositor; \ No newline at end of file diff --git a/ableos/src/experiments/y_compositor/window.rs b/ableos/src/experiments/y_compositor/window.rs index 683cfb76f..6e4a44f78 100644 --- a/ableos/src/experiments/y_compositor/window.rs +++ b/ableos/src/experiments/y_compositor/window.rs @@ -1,8 +1,5 @@ use crate::driver_traits::graphics::Point; -use alloc::string::String; -use alloc::vec::Vec; - pub struct MenuOption { symbol: char, } diff --git a/ableos/src/filesystem/mod.rs b/ableos/src/filesystem/mod.rs index b842d6491..9eceb5178 100644 --- a/ableos/src/filesystem/mod.rs +++ b/ableos/src/filesystem/mod.rs @@ -1,13 +1,10 @@ -use { - alloc::{format, string::String, vec::Vec}, - ext2::{ - fs::{ - sync::{Inode, Synced}, - Ext2, - }, - sector::{SectorSize, Size1024}, - volume::Volume, +use ext2::{ + fs::{ + sync::{Inode, Synced}, + Ext2, }, + sector::{SectorSize, Size1024}, + volume::Volume, }; fn load_fs() -> Synced>> { diff --git a/ableos/src/graphics/mod.rs b/ableos/src/graphics/mod.rs index 93172fb5d..2e487b85e 100644 --- a/ableos/src/graphics/mod.rs +++ b/ableos/src/graphics/mod.rs @@ -1,6 +1,6 @@ // use crate::vga_e::VGAE; use ab_glyph::{Font, FontRef, Glyph}; -use alloc::{boxed::Box, vec, vec::Vec}; + use shadeable::{evaluate_shader, pixel_format::Rgba64}; use spin; // use vga::{colors::Color16, writers::GraphicsWriter}; @@ -126,8 +126,7 @@ impl ScreenBuffer { // TODO force clear pub fn force_redraw(&mut self) { - // use shadeable::pixel_format::into_vga_16; - // VGAE.lock().clear_screen(vga::colors::Color16::Black); + VGAE.lock().clear_screen(vga::colors::Color16::Black); } /// Draw a glyph on the screen at the given position diff --git a/ableos/src/kernel_state.rs b/ableos/src/kernel_state.rs index 52057404e..78f8d1483 100644 --- a/ableos/src/kernel_state.rs +++ b/ableos/src/kernel_state.rs @@ -1,4 +1,3 @@ -use alloc::string::{String, ToString}; use lazy_static::lazy_static; lazy_static! { @@ -7,7 +6,7 @@ lazy_static! { } pub struct KernelInternalState { - hostname: String, + pub hostname: String, should_shutdown: bool, } diff --git a/ableos/src/keyboard/abstractions/custom_layout.rs b/ableos/src/keyboard/abstractions/custom_layout.rs index 0c42378ea..9939c2438 100644 --- a/ableos/src/keyboard/abstractions/custom_layout.rs +++ b/ableos/src/keyboard/abstractions/custom_layout.rs @@ -1,16 +1,16 @@ use crate::{ - DecodedKey, HandleControl, KeyCode, KeyboardLayout, LayoutEntry, LayoutEntryKind, Modifiers, + DecodedKey, HandleControl, KeyCode, KeyboardLayout, LayoutEntry, LayoutEntryKind, Modifiers, }; // Do not edit this file directly. Instead, create a `Keyboard` and modify that. pub struct CustomLayout { - mapping: [LayoutEntry; 256], + mapping: [LayoutEntry; 256], } impl Default for CustomLayout { - fn default() -> Self { - Self::new_us104key() - } + fn default() -> Self { + Self::new_us104key() + } } #[rustfmt::skip] impl CustomLayout { @@ -101,76 +101,76 @@ impl CustomLayout { } } impl KeyboardLayout for CustomLayout { - fn map_keycode( - &self, - keycode: KeyCode, - modifiers: &Modifiers, - handle_ctrl: HandleControl, - ) -> DecodedKey { - let map_to_unicode = handle_ctrl == HandleControl::MapLettersToUnicode; - let spot = &self.mapping[keycode as usize]; - if let Some(k) = if map_to_unicode && modifiers.is_ctrl() { - match spot.kind { - LayoutEntryKind::Regular => spot.raw_unicode, - LayoutEntryKind::Numlockable => None, - LayoutEntryKind::Capslockable => spot.raw_unicode, - } - } else if modifiers.alt_gr { - match spot.kind { - LayoutEntryKind::Regular => spot.altgr, - LayoutEntryKind::Numlockable => None, - LayoutEntryKind::Capslockable => spot.altgr, - } - } else if modifiers.is_shifted() { - match spot.kind { - LayoutEntryKind::Regular => spot.shifted, - LayoutEntryKind::Numlockable => { - if modifiers.numlock { - spot.locked_shifted - } else { - spot.shifted - } + fn map_keycode( + &self, + keycode: KeyCode, + modifiers: &Modifiers, + handle_ctrl: HandleControl, + ) -> DecodedKey { + let map_to_unicode = handle_ctrl == HandleControl::MapLettersToUnicode; + let spot = &self.mapping[keycode as usize]; + if let Some(k) = if map_to_unicode && modifiers.is_ctrl() { + match spot.kind { + LayoutEntryKind::Regular => spot.raw_unicode, + LayoutEntryKind::Numlockable => None, + LayoutEntryKind::Capslockable => spot.raw_unicode, } - LayoutEntryKind::Capslockable => { - if modifiers.is_caps() { - spot.locked_shifted - } else { - spot.shifted - } + } else if modifiers.alt_gr { + match spot.kind { + LayoutEntryKind::Regular => spot.altgr, + LayoutEntryKind::Numlockable => None, + LayoutEntryKind::Capslockable => spot.altgr, } - } - } else { - match spot.kind { - LayoutEntryKind::Regular => spot.unshifted, - LayoutEntryKind::Numlockable => { - if modifiers.numlock { - spot.locked - } else { - spot.unshifted - } + } else if modifiers.is_shifted() { + match spot.kind { + LayoutEntryKind::Regular => spot.shifted, + LayoutEntryKind::Numlockable => { + if modifiers.numlock { + spot.locked_shifted + } else { + spot.shifted + } + } + LayoutEntryKind::Capslockable => { + if modifiers.is_caps() { + spot.locked_shifted + } else { + spot.shifted + } + } } - LayoutEntryKind::Capslockable => { - if modifiers.is_caps() { - spot.locked - } else { - spot.unshifted - } + } else { + match spot.kind { + LayoutEntryKind::Regular => spot.unshifted, + LayoutEntryKind::Numlockable => { + if modifiers.numlock { + spot.locked + } else { + spot.unshifted + } + } + LayoutEntryKind::Capslockable => { + if modifiers.is_caps() { + spot.locked + } else { + spot.unshifted + } + } } - } - } { - k - } else { - DecodedKey::RawKey(keycode as u8) - } - } + } { + k + } else { + DecodedKey::RawKey(keycode as u8) + } + } } // Note(elfein) Not super hard to get right, but still- DO NOT TOUCH impl CustomLayout { - // See how hard this is to get right? - // See the complexity of all the methods? - // Yeah- if you don't know what you're doing, ask before you touch! - pub fn set(&mut self, pos: KeyCode, entry: LayoutEntry) { - self.mapping[pos as usize] = entry; - } + // See how hard this is to get right? + // See the complexity of all the methods? + // Yeah- if you don't know what you're doing, ask before you touch! + pub fn set(&mut self, pos: KeyCode, entry: LayoutEntry) { + self.mapping[pos as usize] = entry; + } } diff --git a/ableos/src/keyboard/abstractions/custom_scancode_set.rs b/ableos/src/keyboard/abstractions/custom_scancode_set.rs index 5f226d992..8cb6950af 100644 --- a/ableos/src/keyboard/abstractions/custom_scancode_set.rs +++ b/ableos/src/keyboard/abstractions/custom_scancode_set.rs @@ -1,253 +1,255 @@ -use crate::{KeyCode, ScancodeSet, DecodeState, KeyEvent, Error, KeyState, keyboard::EXTENDED_KEY_CODE}; +use crate::{ + keyboard::EXTENDED_KEY_CODE, DecodeState, Error, KeyCode, KeyEvent, KeyState, ScancodeSet, +}; pub struct CustomScancodeSet { - single_byte: [Option; 256], - extended: [Option; 256], + single_byte: [Option; 256], + extended: [Option; 256], } impl Default for CustomScancodeSet { - fn default() -> Self { - Self::scancode_set1() - } + fn default() -> Self { + Self::scancode_set1() + } } impl CustomScancodeSet { - pub fn scancode_set1() -> Self { - let mut scancode_set = Self { - single_byte: [None; 256], - extended: [None; 256], - }; - scancode_set.single_byte[0x01] = Some(KeyCode::Escape); // 01 - scancode_set.single_byte[0x02] = Some(KeyCode::Key1); // 02 - scancode_set.single_byte[0x03] = Some(KeyCode::Key2); // 03 - scancode_set.single_byte[0x04] = Some(KeyCode::Key3); // 04 - scancode_set.single_byte[0x05] = Some(KeyCode::Key4); // 05 - scancode_set.single_byte[0x06] = Some(KeyCode::Key5); // 06 - scancode_set.single_byte[0x07] = Some(KeyCode::Key6); // 07 - scancode_set.single_byte[0x08] = Some(KeyCode::Key7); // 08 - scancode_set.single_byte[0x09] = Some(KeyCode::Key8); // 09 - scancode_set.single_byte[0x0A] = Some(KeyCode::Key9); // 0A - scancode_set.single_byte[0x0B] = Some(KeyCode::Key0); // 0B - scancode_set.single_byte[0x0C] = Some(KeyCode::Minus); // 0C - scancode_set.single_byte[0x0D] = Some(KeyCode::Equals); // 0D - scancode_set.single_byte[0x0E] = Some(KeyCode::Backspace); // 0E - scancode_set.single_byte[0x0F] = Some(KeyCode::Tab); // 0F - scancode_set.single_byte[0x10] = Some(KeyCode::Q); // 10 - scancode_set.single_byte[0x11] = Some(KeyCode::W); // 11 - scancode_set.single_byte[0x12] = Some(KeyCode::E); // 12 - scancode_set.single_byte[0x13] = Some(KeyCode::R); // 13 - scancode_set.single_byte[0x14] = Some(KeyCode::T); // 14 - scancode_set.single_byte[0x15] = Some(KeyCode::Y); // 15 - scancode_set.single_byte[0x16] = Some(KeyCode::U); // 16 - scancode_set.single_byte[0x17] = Some(KeyCode::I); // 17 - scancode_set.single_byte[0x18] = Some(KeyCode::O); // 18 - scancode_set.single_byte[0x19] = Some(KeyCode::P); // 19 - scancode_set.single_byte[0x1A] = Some(KeyCode::BracketSquareLeft); // 1A - scancode_set.single_byte[0x1B] = Some(KeyCode::BracketSquareRight); // 1B - scancode_set.single_byte[0x1C] = Some(KeyCode::Enter); // 1C - scancode_set.single_byte[0x1D] = Some(KeyCode::ControlLeft); // 1D - scancode_set.single_byte[0x1E] = Some(KeyCode::A); // 1E - scancode_set.single_byte[0x1F] = Some(KeyCode::S); // 1F - scancode_set.single_byte[0x20] = Some(KeyCode::D); // 20 - scancode_set.single_byte[0x21] = Some(KeyCode::F); // 21 - scancode_set.single_byte[0x22] = Some(KeyCode::G); // 22 - scancode_set.single_byte[0x23] = Some(KeyCode::H); // 23 - scancode_set.single_byte[0x24] = Some(KeyCode::J); // 24 - scancode_set.single_byte[0x25] = Some(KeyCode::K); // 25 - scancode_set.single_byte[0x26] = Some(KeyCode::L); // 26 - scancode_set.single_byte[0x27] = Some(KeyCode::SemiColon); // 27 - scancode_set.single_byte[0x28] = Some(KeyCode::Quote); // 28 - scancode_set.single_byte[0x29] = Some(KeyCode::BackTick); // 29 - scancode_set.single_byte[0x2A] = Some(KeyCode::ShiftLeft); // 2A - scancode_set.single_byte[0x2B] = Some(KeyCode::BackSlash); // 2B - scancode_set.single_byte[0x2C] = Some(KeyCode::Z); // 2C - scancode_set.single_byte[0x2D] = Some(KeyCode::X); // 2D - scancode_set.single_byte[0x2E] = Some(KeyCode::C); // 2E - scancode_set.single_byte[0x2F] = Some(KeyCode::V); // 2F - scancode_set.single_byte[0x30] = Some(KeyCode::B); // 30 - scancode_set.single_byte[0x31] = Some(KeyCode::N); // 31 - scancode_set.single_byte[0x32] = Some(KeyCode::M); // 32 - scancode_set.single_byte[0x33] = Some(KeyCode::Comma); // 33 - scancode_set.single_byte[0x34] = Some(KeyCode::Fullstop); // 34 - scancode_set.single_byte[0x35] = Some(KeyCode::Slash); // 35 - scancode_set.single_byte[0x36] = Some(KeyCode::ShiftRight); // 36 - scancode_set.single_byte[0x37] = Some(KeyCode::NumpadStar); // 37 - scancode_set.single_byte[0x38] = Some(KeyCode::AltLeft); // 38 - scancode_set.single_byte[0x39] = Some(KeyCode::Spacebar); // 39 - scancode_set.single_byte[0x3A] = Some(KeyCode::CapsLock); // 3A - scancode_set.single_byte[0x3B] = Some(KeyCode::F1); // 3B - scancode_set.single_byte[0x3C] = Some(KeyCode::F2); // 3C - scancode_set.single_byte[0x3D] = Some(KeyCode::F3); // 3D - scancode_set.single_byte[0x3E] = Some(KeyCode::F4); // 3E - scancode_set.single_byte[0x3F] = Some(KeyCode::F5); // 3F - scancode_set.single_byte[0x40] = Some(KeyCode::F6); // 40 - scancode_set.single_byte[0x41] = Some(KeyCode::F7); // 41 - scancode_set.single_byte[0x42] = Some(KeyCode::F8); // 42 - scancode_set.single_byte[0x43] = Some(KeyCode::F9); // 43 - scancode_set.single_byte[0x44] = Some(KeyCode::F10); // 44 - scancode_set.single_byte[0x45] = Some(KeyCode::NumpadLock); // 45 - scancode_set.single_byte[0x46] = Some(KeyCode::ScrollLock); // 46 - scancode_set.single_byte[0x47] = Some(KeyCode::Numpad7); // 47 - scancode_set.single_byte[0x48] = Some(KeyCode::Numpad8); // 48 - scancode_set.single_byte[0x49] = Some(KeyCode::Numpad9); // 49 - scancode_set.single_byte[0x4A] = Some(KeyCode::NumpadMinus); // 4A - scancode_set.single_byte[0x4B] = Some(KeyCode::Numpad4); // 4B - scancode_set.single_byte[0x4C] = Some(KeyCode::Numpad5); // 4C - scancode_set.single_byte[0x4D] = Some(KeyCode::Numpad6); // 4D - scancode_set.single_byte[0x4E] = Some(KeyCode::NumpadPlus); // 4E - scancode_set.single_byte[0x4F] = Some(KeyCode::Numpad1); // 4F - scancode_set.single_byte[0x50] = Some(KeyCode::Numpad2); // 50 - scancode_set.single_byte[0x51] = Some(KeyCode::Numpad3); // 51 - scancode_set.single_byte[0x52] = Some(KeyCode::Numpad0); // 52 - scancode_set.single_byte[0x53] = Some(KeyCode::NumpadPeriod); // 53 - // 0x54 - // 0x55 - // 0x56 - scancode_set.single_byte[0x57] = Some(KeyCode::F11); // 57 - scancode_set.single_byte[0x58] = Some(KeyCode::F12); // 58 - for i in 0x81..=0xD8 { - scancode_set.single_byte[i] = scancode_set.single_byte[i - 0x80]; - } - scancode_set.extended[0x10] = Some(KeyCode::PrevTrack); // E010 - //0x11 - //0x12 - //0x13 - //0x14 - //0x15 - //0x16 - //0x17 - //0x18 - scancode_set.extended[0x19] = Some(KeyCode::NextTrack); // E019 - //0x1A - //0x1B - scancode_set.extended[0x1C] = Some(KeyCode::NumpadEnter); // E01C - scancode_set.extended[0x1D] = Some(KeyCode::ControlRight); // E01D - //0x1E - //0x1F - scancode_set.extended[0x20] = Some(KeyCode::Mute); // E020 - scancode_set.extended[0x21] = Some(KeyCode::Calculator); // E021 - scancode_set.extended[0x22] = Some(KeyCode::Play); // E022 - //0x23 - scancode_set.extended[0x24] = Some(KeyCode::Stop); // E024 - //0x25 - //0x26 - //0x27 - //0x28 - //0x29 - //0x2A - //0x2B - //0x2C - //0x2D - scancode_set.extended[0x2E] = Some(KeyCode::VolumeDown); // E02E - //0x2F - scancode_set.extended[0x30] = Some(KeyCode::VolumeUp); // E030 - //0x31 - scancode_set.extended[0x32] = Some(KeyCode::WWWHome); // E032 - //0x33 - //0x34 - scancode_set.extended[0x35] = Some(KeyCode::NumpadSlash); // E035 - //0x36 - //0x37 - scancode_set.extended[0x38] = Some(KeyCode::AltRight); // E038 - //0x39 - //0x3A - //0x3B - //0x3C - //0x3D - //0x3E - //0x3F - //0x40 - //0x41 - //0x42 - //0x43 - //0x44 - //0x45 - //0x46 - scancode_set.extended[0x47] = Some(KeyCode::Home); // E047 - scancode_set.extended[0x48] = Some(KeyCode::ArrowUp); // E048 - scancode_set.extended[0x49] = Some(KeyCode::PageUp); // E049 - //0x4A - scancode_set.extended[0x4B] = Some(KeyCode::ArrowLeft); // E04B - //0x4C - scancode_set.extended[0x4D] = Some(KeyCode::ArrowRight); // E04D - //0x4E - scancode_set.extended[0x4F] = Some(KeyCode::End); // E04F - scancode_set.extended[0x50] = Some(KeyCode::ArrowDown); // E050 - scancode_set.extended[0x51] = Some(KeyCode::PageDown); // E051 - scancode_set.extended[0x52] = Some(KeyCode::Insert); // E052 - scancode_set.extended[0x53] = Some(KeyCode::Delete); // E053 - for i in 0x90..=0xED { - scancode_set.extended[i] = scancode_set.extended[i - 0x80]; - } - scancode_set - } - pub fn scancode_set2() -> Self { - Self { - single_byte: [None; 256], - extended: [None; 256], - } - } + pub fn scancode_set1() -> Self { + let mut scancode_set = Self { + single_byte: [None; 256], + extended: [None; 256], + }; + scancode_set.single_byte[0x01] = Some(KeyCode::Escape); // 01 + scancode_set.single_byte[0x02] = Some(KeyCode::Key1); // 02 + scancode_set.single_byte[0x03] = Some(KeyCode::Key2); // 03 + scancode_set.single_byte[0x04] = Some(KeyCode::Key3); // 04 + scancode_set.single_byte[0x05] = Some(KeyCode::Key4); // 05 + scancode_set.single_byte[0x06] = Some(KeyCode::Key5); // 06 + scancode_set.single_byte[0x07] = Some(KeyCode::Key6); // 07 + scancode_set.single_byte[0x08] = Some(KeyCode::Key7); // 08 + scancode_set.single_byte[0x09] = Some(KeyCode::Key8); // 09 + scancode_set.single_byte[0x0A] = Some(KeyCode::Key9); // 0A + scancode_set.single_byte[0x0B] = Some(KeyCode::Key0); // 0B + scancode_set.single_byte[0x0C] = Some(KeyCode::Minus); // 0C + scancode_set.single_byte[0x0D] = Some(KeyCode::Equals); // 0D + scancode_set.single_byte[0x0E] = Some(KeyCode::Backspace); // 0E + scancode_set.single_byte[0x0F] = Some(KeyCode::Tab); // 0F + scancode_set.single_byte[0x10] = Some(KeyCode::Q); // 10 + scancode_set.single_byte[0x11] = Some(KeyCode::W); // 11 + scancode_set.single_byte[0x12] = Some(KeyCode::E); // 12 + scancode_set.single_byte[0x13] = Some(KeyCode::R); // 13 + scancode_set.single_byte[0x14] = Some(KeyCode::T); // 14 + scancode_set.single_byte[0x15] = Some(KeyCode::Y); // 15 + scancode_set.single_byte[0x16] = Some(KeyCode::U); // 16 + scancode_set.single_byte[0x17] = Some(KeyCode::I); // 17 + scancode_set.single_byte[0x18] = Some(KeyCode::O); // 18 + scancode_set.single_byte[0x19] = Some(KeyCode::P); // 19 + scancode_set.single_byte[0x1A] = Some(KeyCode::BracketSquareLeft); // 1A + scancode_set.single_byte[0x1B] = Some(KeyCode::BracketSquareRight); // 1B + scancode_set.single_byte[0x1C] = Some(KeyCode::Enter); // 1C + scancode_set.single_byte[0x1D] = Some(KeyCode::ControlLeft); // 1D + scancode_set.single_byte[0x1E] = Some(KeyCode::A); // 1E + scancode_set.single_byte[0x1F] = Some(KeyCode::S); // 1F + scancode_set.single_byte[0x20] = Some(KeyCode::D); // 20 + scancode_set.single_byte[0x21] = Some(KeyCode::F); // 21 + scancode_set.single_byte[0x22] = Some(KeyCode::G); // 22 + scancode_set.single_byte[0x23] = Some(KeyCode::H); // 23 + scancode_set.single_byte[0x24] = Some(KeyCode::J); // 24 + scancode_set.single_byte[0x25] = Some(KeyCode::K); // 25 + scancode_set.single_byte[0x26] = Some(KeyCode::L); // 26 + scancode_set.single_byte[0x27] = Some(KeyCode::SemiColon); // 27 + scancode_set.single_byte[0x28] = Some(KeyCode::Quote); // 28 + scancode_set.single_byte[0x29] = Some(KeyCode::BackTick); // 29 + scancode_set.single_byte[0x2A] = Some(KeyCode::ShiftLeft); // 2A + scancode_set.single_byte[0x2B] = Some(KeyCode::BackSlash); // 2B + scancode_set.single_byte[0x2C] = Some(KeyCode::Z); // 2C + scancode_set.single_byte[0x2D] = Some(KeyCode::X); // 2D + scancode_set.single_byte[0x2E] = Some(KeyCode::C); // 2E + scancode_set.single_byte[0x2F] = Some(KeyCode::V); // 2F + scancode_set.single_byte[0x30] = Some(KeyCode::B); // 30 + scancode_set.single_byte[0x31] = Some(KeyCode::N); // 31 + scancode_set.single_byte[0x32] = Some(KeyCode::M); // 32 + scancode_set.single_byte[0x33] = Some(KeyCode::Comma); // 33 + scancode_set.single_byte[0x34] = Some(KeyCode::Fullstop); // 34 + scancode_set.single_byte[0x35] = Some(KeyCode::Slash); // 35 + scancode_set.single_byte[0x36] = Some(KeyCode::ShiftRight); // 36 + scancode_set.single_byte[0x37] = Some(KeyCode::NumpadStar); // 37 + scancode_set.single_byte[0x38] = Some(KeyCode::AltLeft); // 38 + scancode_set.single_byte[0x39] = Some(KeyCode::Spacebar); // 39 + scancode_set.single_byte[0x3A] = Some(KeyCode::CapsLock); // 3A + scancode_set.single_byte[0x3B] = Some(KeyCode::F1); // 3B + scancode_set.single_byte[0x3C] = Some(KeyCode::F2); // 3C + scancode_set.single_byte[0x3D] = Some(KeyCode::F3); // 3D + scancode_set.single_byte[0x3E] = Some(KeyCode::F4); // 3E + scancode_set.single_byte[0x3F] = Some(KeyCode::F5); // 3F + scancode_set.single_byte[0x40] = Some(KeyCode::F6); // 40 + scancode_set.single_byte[0x41] = Some(KeyCode::F7); // 41 + scancode_set.single_byte[0x42] = Some(KeyCode::F8); // 42 + scancode_set.single_byte[0x43] = Some(KeyCode::F9); // 43 + scancode_set.single_byte[0x44] = Some(KeyCode::F10); // 44 + scancode_set.single_byte[0x45] = Some(KeyCode::NumpadLock); // 45 + scancode_set.single_byte[0x46] = Some(KeyCode::ScrollLock); // 46 + scancode_set.single_byte[0x47] = Some(KeyCode::Numpad7); // 47 + scancode_set.single_byte[0x48] = Some(KeyCode::Numpad8); // 48 + scancode_set.single_byte[0x49] = Some(KeyCode::Numpad9); // 49 + scancode_set.single_byte[0x4A] = Some(KeyCode::NumpadMinus); // 4A + scancode_set.single_byte[0x4B] = Some(KeyCode::Numpad4); // 4B + scancode_set.single_byte[0x4C] = Some(KeyCode::Numpad5); // 4C + scancode_set.single_byte[0x4D] = Some(KeyCode::Numpad6); // 4D + scancode_set.single_byte[0x4E] = Some(KeyCode::NumpadPlus); // 4E + scancode_set.single_byte[0x4F] = Some(KeyCode::Numpad1); // 4F + scancode_set.single_byte[0x50] = Some(KeyCode::Numpad2); // 50 + scancode_set.single_byte[0x51] = Some(KeyCode::Numpad3); // 51 + scancode_set.single_byte[0x52] = Some(KeyCode::Numpad0); // 52 + scancode_set.single_byte[0x53] = Some(KeyCode::NumpadPeriod); // 53 + // 0x54 + // 0x55 + // 0x56 + scancode_set.single_byte[0x57] = Some(KeyCode::F11); // 57 + scancode_set.single_byte[0x58] = Some(KeyCode::F12); // 58 + for i in 0x81..=0xD8 { + scancode_set.single_byte[i] = scancode_set.single_byte[i - 0x80]; + } + scancode_set.extended[0x10] = Some(KeyCode::PrevTrack); // E010 + //0x11 + //0x12 + //0x13 + //0x14 + //0x15 + //0x16 + //0x17 + //0x18 + scancode_set.extended[0x19] = Some(KeyCode::NextTrack); // E019 + //0x1A + //0x1B + scancode_set.extended[0x1C] = Some(KeyCode::NumpadEnter); // E01C + scancode_set.extended[0x1D] = Some(KeyCode::ControlRight); // E01D + //0x1E + //0x1F + scancode_set.extended[0x20] = Some(KeyCode::Mute); // E020 + scancode_set.extended[0x21] = Some(KeyCode::Calculator); // E021 + scancode_set.extended[0x22] = Some(KeyCode::Play); // E022 + //0x23 + scancode_set.extended[0x24] = Some(KeyCode::Stop); // E024 + //0x25 + //0x26 + //0x27 + //0x28 + //0x29 + //0x2A + //0x2B + //0x2C + //0x2D + scancode_set.extended[0x2E] = Some(KeyCode::VolumeDown); // E02E + //0x2F + scancode_set.extended[0x30] = Some(KeyCode::VolumeUp); // E030 + //0x31 + scancode_set.extended[0x32] = Some(KeyCode::WWWHome); // E032 + //0x33 + //0x34 + scancode_set.extended[0x35] = Some(KeyCode::NumpadSlash); // E035 + //0x36 + //0x37 + scancode_set.extended[0x38] = Some(KeyCode::AltRight); // E038 + //0x39 + //0x3A + //0x3B + //0x3C + //0x3D + //0x3E + //0x3F + //0x40 + //0x41 + //0x42 + //0x43 + //0x44 + //0x45 + //0x46 + scancode_set.extended[0x47] = Some(KeyCode::Home); // E047 + scancode_set.extended[0x48] = Some(KeyCode::ArrowUp); // E048 + scancode_set.extended[0x49] = Some(KeyCode::PageUp); // E049 + //0x4A + scancode_set.extended[0x4B] = Some(KeyCode::ArrowLeft); // E04B + //0x4C + scancode_set.extended[0x4D] = Some(KeyCode::ArrowRight); // E04D + //0x4E + scancode_set.extended[0x4F] = Some(KeyCode::End); // E04F + scancode_set.extended[0x50] = Some(KeyCode::ArrowDown); // E050 + scancode_set.extended[0x51] = Some(KeyCode::PageDown); // E051 + scancode_set.extended[0x52] = Some(KeyCode::Insert); // E052 + scancode_set.extended[0x53] = Some(KeyCode::Delete); // E053 + for i in 0x90..=0xED { + scancode_set.extended[i] = scancode_set.extended[i - 0x80]; + } + scancode_set + } + pub fn scancode_set2() -> Self { + Self { + single_byte: [None; 256], + extended: [None; 256], + } + } } impl ScancodeSet for CustomScancodeSet { - fn advance_state(&self, state: &mut DecodeState, code: u8) -> Result, Error> { - match *state { - DecodeState::Start => { - match code { - EXTENDED_KEY_CODE => { - *state = DecodeState::Extended; - Ok(None) - } - 0x80..=0xFF => { - // Release codes - Ok(Some(KeyEvent::new( - self.map_scancode(code - 0x80)?, - KeyState::Up, - ))) - } - _ => { - // Normal codes - Ok(Some(KeyEvent::new( - self.map_scancode(code)?, - KeyState::Down, - ))) - } + fn advance_state(&self, state: &mut DecodeState, code: u8) -> Result, Error> { + match *state { + DecodeState::Start => { + match code { + EXTENDED_KEY_CODE => { + *state = DecodeState::Extended; + Ok(None) + } + 0x80..=0xFF => { + // Release codes + Ok(Some(KeyEvent::new( + self.map_scancode(code - 0x80)?, + KeyState::Up, + ))) + } + _ => { + // Normal codes + Ok(Some(KeyEvent::new( + self.map_scancode(code)?, + KeyState::Down, + ))) + } + } } - } - DecodeState::Extended => { - *state = DecodeState::Start; - match code { - 0x80..=0xFF => { - // Extended Release codes - Ok(Some(KeyEvent::new( - self.map_extended_scancode(code - 0x80)?, - KeyState::Up, - ))) - } - _ => { - // Normal release codes - Ok(Some(KeyEvent::new( - self.map_extended_scancode(code)?, - KeyState::Down, - ))) - } + DecodeState::Extended => { + *state = DecodeState::Start; + match code { + 0x80..=0xFF => { + // Extended Release codes + Ok(Some(KeyEvent::new( + self.map_extended_scancode(code - 0x80)?, + KeyState::Up, + ))) + } + _ => { + // Normal release codes + Ok(Some(KeyEvent::new( + self.map_extended_scancode(code)?, + KeyState::Down, + ))) + } + } } - } - _ => { - // Can't get in to this state - unimplemented!(); - } - } - } - fn map_scancode(&self, code: u8) -> Result { - if let Some(kc) = self.single_byte[code as usize] { - Ok(kc) - } else { - Err(Error::UnknownKeyCode) - } - } - fn map_extended_scancode(&self, code: u8) -> Result { - if let Some(kc) = self.extended[code as usize] { - Ok(kc) - } else { - Err(Error::UnknownKeyCode) - } - } -} \ No newline at end of file + _ => { + // Can't get in to this state + unimplemented!(); + } + } + } + fn map_scancode(&self, code: u8) -> Result { + if let Some(kc) = self.single_byte[code as usize] { + Ok(kc) + } else { + Err(Error::UnknownKeyCode) + } + } + fn map_extended_scancode(&self, code: u8) -> Result { + if let Some(kc) = self.extended[code as usize] { + Ok(kc) + } else { + Err(Error::UnknownKeyCode) + } + } +} diff --git a/ableos/src/keyboard/abstractions/layout_entry.rs b/ableos/src/keyboard/abstractions/layout_entry.rs index 54351fb79..a24af3a7e 100644 --- a/ableos/src/keyboard/abstractions/layout_entry.rs +++ b/ableos/src/keyboard/abstractions/layout_entry.rs @@ -2,104 +2,102 @@ use super::DecodedKey; #[derive(Debug, Clone, Copy)] pub enum LayoutEntryKind { - Regular, - Numlockable, - Capslockable, + Regular, + Numlockable, + Capslockable, } impl Default for LayoutEntryKind { - fn default() -> Self { - Self::Regular - } + fn default() -> Self { + Self::Regular + } } #[derive(Debug, Clone, Copy, Default)] pub struct LayoutEntry { - pub kind: LayoutEntryKind, - pub unshifted: Option, - pub shifted: Option, - pub locked: Option, - pub locked_shifted: Option, - pub altgr: Option, - pub raw_unicode: Option, + pub kind: LayoutEntryKind, + pub unshifted: Option, + pub shifted: Option, + pub locked: Option, + pub locked_shifted: Option, + pub altgr: Option, + pub raw_unicode: Option, } impl LayoutEntry { - #[must_use] - pub fn regular() -> Self { - Self { - kind: LayoutEntryKind::Regular, - ..Default::default() - } - } - #[must_use] - pub fn numpad() -> Self { - Self { - kind: LayoutEntryKind::Numlockable, - ..Default::default() - } - } - #[must_use] - pub fn alphabet() -> Self { - Self { - kind: LayoutEntryKind::Capslockable, - ..Default::default() - } - } - #[must_use] - pub fn unshifted(mut self, c: impl Into) -> Self { - self.unshifted = Some(c.into()); - self - } - #[must_use] - pub fn shifted(mut self, c: impl Into) -> Self { - self.shifted = Some(c.into()); - self - } - #[must_use] - pub fn altgr(mut self, c: impl Into) -> Self { - self.altgr = Some(c.into()); - self - } - #[must_use] - pub fn raw_unicode(mut self, c: impl Into) -> Self { - self.raw_unicode = Some(c.into()); - self - } - #[must_use] - pub fn locked(mut self, c: impl Into) -> Self { - self.locked = Some(c.into()); - self - } - #[must_use] - pub fn locked_shifted(mut self, c: impl Into) -> Self { - self.locked_shifted = Some(c.into()); - self - } - #[must_use] - pub fn common(self, c: impl Into + Clone) -> Self { - self - .unshifted(c.clone()) - .shifted(c.clone()) - .locked(c.clone()) - .locked_shifted(c) - } - #[must_use] - pub fn low(self, c: impl Into + Clone) -> Self { - self.unshifted(c.clone()).locked_shifted(c) - } - #[must_use] - pub fn high(self, c: impl Into + Clone) -> Self { - self.shifted(c.clone()).locked(c) - } - #[must_use] - pub fn all(self, c: impl Into + Clone) -> Self { - self - .unshifted(c.clone()) - .shifted(c.clone()) - .locked(c.clone()) - .locked_shifted(c.clone()) - .altgr(c.clone()) - .raw_unicode(c) - } + #[must_use] + pub fn regular() -> Self { + Self { + kind: LayoutEntryKind::Regular, + ..Default::default() + } + } + #[must_use] + pub fn numpad() -> Self { + Self { + kind: LayoutEntryKind::Numlockable, + ..Default::default() + } + } + #[must_use] + pub fn alphabet() -> Self { + Self { + kind: LayoutEntryKind::Capslockable, + ..Default::default() + } + } + #[must_use] + pub fn unshifted(mut self, c: impl Into) -> Self { + self.unshifted = Some(c.into()); + self + } + #[must_use] + pub fn shifted(mut self, c: impl Into) -> Self { + self.shifted = Some(c.into()); + self + } + #[must_use] + pub fn altgr(mut self, c: impl Into) -> Self { + self.altgr = Some(c.into()); + self + } + #[must_use] + pub fn raw_unicode(mut self, c: impl Into) -> Self { + self.raw_unicode = Some(c.into()); + self + } + #[must_use] + pub fn locked(mut self, c: impl Into) -> Self { + self.locked = Some(c.into()); + self + } + #[must_use] + pub fn locked_shifted(mut self, c: impl Into) -> Self { + self.locked_shifted = Some(c.into()); + self + } + #[must_use] + pub fn common(self, c: impl Into + Clone) -> Self { + self.unshifted(c.clone()) + .shifted(c.clone()) + .locked(c.clone()) + .locked_shifted(c) + } + #[must_use] + pub fn low(self, c: impl Into + Clone) -> Self { + self.unshifted(c.clone()).locked_shifted(c) + } + #[must_use] + pub fn high(self, c: impl Into + Clone) -> Self { + self.shifted(c.clone()).locked(c) + } + #[must_use] + pub fn all(self, c: impl Into + Clone) -> Self { + self.unshifted(c.clone()) + .shifted(c.clone()) + .locked(c.clone()) + .locked_shifted(c.clone()) + .altgr(c.clone()) + .raw_unicode(c) + } } diff --git a/ableos/src/keyboard/small_types.rs b/ableos/src/keyboard/small_types.rs index 46c3bf718..1ab5bfea1 100644 --- a/ableos/src/keyboard/small_types.rs +++ b/ableos/src/keyboard/small_types.rs @@ -1,111 +1,111 @@ #![allow(non_snake_case)] #[derive(Debug)] pub struct Modifiers { - pub lshift: bool, - pub rshift: bool, - pub lctrl: bool, - pub rctrl: bool, - pub numlock: bool, - pub capslock: bool, - pub alt_gr: bool, + pub lshift: bool, + pub rshift: bool, + pub lctrl: bool, + pub rctrl: bool, + pub numlock: bool, + pub capslock: bool, + pub alt_gr: bool, } impl Modifiers { - pub fn is_shifted(&self) -> bool { - self.lshift | self.rshift - } - pub fn is_ctrl(&self) -> bool { - self.lctrl | self.rctrl - } - pub fn is_caps(&self) -> bool { - self.capslock - } + pub fn is_shifted(&self) -> bool { + self.lshift | self.rshift + } + pub fn is_ctrl(&self) -> bool { + self.lctrl | self.rctrl + } + pub fn is_caps(&self) -> bool { + self.capslock + } } #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub enum KeyState { - Up, - Down, + Up, + Down, } #[derive(Debug, PartialEq, Eq, Clone)] pub struct KeyEvent { - pub code: KeyCode, - pub state: KeyState, + pub code: KeyCode, + pub state: KeyState, } impl KeyEvent { - pub fn new(code: KeyCode, state: KeyState) -> KeyEvent { - KeyEvent { code, state } - } + pub fn new(code: KeyCode, state: KeyState) -> KeyEvent { + KeyEvent { code, state } + } } #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub enum HandleControl { - /// If either Ctrl key is held down, convert the letters A through Z into - /// Unicode chars U+0001 through U+001A. If the Ctrl keys are not held - /// down, letters go through normally. - MapLettersToUnicode, - /// Don't do anything special - send through the Ctrl key up/down events, - /// and leave the letters as letters. - Ignore, + /// If either Ctrl key is held down, convert the letters A through Z into + /// Unicode chars U+0001 through U+001A. If the Ctrl keys are not held + /// down, letters go through normally. + MapLettersToUnicode, + /// Don't do anything special - send through the Ctrl key up/down events, + /// and leave the letters as letters. + Ignore, } #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum DecodeState { - Start, - Extended, - Release, - ExtendedRelease, + Start, + Extended, + Release, + ExtendedRelease, } /// Indicates different error conditions. #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub enum Error { - BadStartBit, - BadStopBit, - ParityError, - UnknownKeyCode, - InvalidState, + BadStartBit, + BadStopBit, + ParityError, + UnknownKeyCode, + InvalidState, } #[derive(Debug, PartialEq, Eq, Copy, Clone)] #[repr(u8)] pub enum DecodedKeyKind { - RawKey = 0, - Unicode = 1, + RawKey = 0, + Unicode = 1, } #[derive(Debug, PartialEq, Eq, Copy, Clone)] #[repr(C)] pub struct DecodedKey { - pub kind: DecodedKeyKind, - pub value: u32, + pub kind: DecodedKeyKind, + pub value: u32, } impl From for DecodedKey { - fn from(ch: char) -> Self { - Self { - kind: DecodedKeyKind::Unicode, - value: ch as u32, - } - } + fn from(ch: char) -> Self { + Self { + kind: DecodedKeyKind::Unicode, + value: ch as u32, + } + } } impl From for DecodedKey { - fn from(kc: KeyCode) -> Self { - Self { - kind: DecodedKeyKind::RawKey, - value: kc as u32, - } - } + fn from(kc: KeyCode) -> Self { + Self { + kind: DecodedKeyKind::RawKey, + value: kc as u32, + } + } } impl DecodedKey { - pub const ZERO: Self = Self { - kind: DecodedKeyKind::Unicode, - value: 0, - }; - pub fn Unicode(ch: char) -> Self { - Self { - kind: DecodedKeyKind::Unicode, - value: ch.into(), - } - } - pub fn RawKey(byte: u8) -> Self { - Self { - kind: DecodedKeyKind::RawKey, - value: byte.into(), - } - } + pub const ZERO: Self = Self { + kind: DecodedKeyKind::Unicode, + value: 0, + }; + pub fn Unicode(ch: char) -> Self { + Self { + kind: DecodedKeyKind::Unicode, + value: ch.into(), + } + } + pub fn RawKey(byte: u8) -> Self { + Self { + kind: DecodedKeyKind::RawKey, + value: byte.into(), + } + } } macro_rules! keycode_enum { (@get_last $Variant:ident) => { diff --git a/ableos/src/kmain.rs b/ableos/src/kmain.rs index 4143230bc..7e148edc7 100644 --- a/ableos/src/kmain.rs +++ b/ableos/src/kmain.rs @@ -1,7 +1,5 @@ #![allow(clippy::empty_loop)] -use crate::scheduler::SCHEDULER; - // use acpi::AcpiTables; // use x86_64::instructions::interrupts::{disable, enable}; @@ -10,11 +8,7 @@ use crate::scheduler::SCHEDULER; use { crate::{ arch::{init, sloop}, - boot_conf, - boot_conf::BootConfig, - // capabilities::FileAccess, - experiments::systeminfo::{KERNEL_VERSION, RELEASE_TYPE}, - // file::PathRep, + relib::network::socket::{SimpleSock, Socket}, // scheduler::SCHEDULER, // VgaBuffer, @@ -23,30 +17,25 @@ use { // SCHEDULER, SCREEN_BUFFER, }, - alloc::{ - format, - string::{String, ToString}, - vec, - }, - core::sync::atomic::{AtomicU64, Ordering::*}, facepalm::start_facepalm, lazy_static::lazy_static, - log::*, - // shadeable::pixel_format::from_vga_16, - // vga::colors::Color16, }; lazy_static! { // TODO: Change this structure to allow for multiple cores loaded - pub static ref TICK: AtomicU64 = AtomicU64::new(0); - pub static ref BOOT_CONF: BootConfig = boot_conf::BootConfig::new(); + pub static ref KERNEL_CONF: KernelConfig = KernelConfig::new(); } /// The main entry point of the kernel #[no_mangle] pub fn kernel_main() -> ! { init::init(); - // log::set_max_level(BOOT_CONF.log_level()); + + if KERNEL_CONF.logging.enabled { + log::set_max_level(KERNEL_CONF.log_level()); + } else { + log::set_max_level(log::LevelFilter::Off); + } let mut scheduler = SCHEDULER.lock(); /* @@ -73,33 +62,41 @@ pub fn kernel_main() -> ! { // use crate::proto_filetable::file::FileLocations; /* - if false { - let mut sock_print_id = SimpleSock::new(); - sock_print_id.register_protocol("Screen Printer".to_string()); - sock_print_id.write(format!("🐑").into()); + if false { + let mut sock_print_id = SimpleSock::new(); + sock_print_id.register_protocol("Screen Printer".to_string()); + sock_print_id.write(format!("🐑").into()); - let mut mode = SCREEN_BUFFER.lock(); + let mut mode = SCREEN_BUFFER.lock(); - mode.force_redraw(); - for current in (*String::from_utf8_lossy(&sock_print_id.peek().unwrap())).chars() { - // mode.draw_char(0, 0, current, from_vga_16(Color16::Red)); + mode.force_redraw(); + for current in (*String::from_utf8_lossy(&sock_print_id.peek().unwrap())).chars() { + // mode.draw_char(0, 0, current, from_vga_16(Color16::Red)); + } + // mode.copy_to_buffer(); } - // mode.copy_to_buffer(); - } - */ + <<<<<<< HEAD + */ /* - // TODO: create a scratchpad module - if false { - // Currently not implemented - let acpi_handler = AcpiStruct {}; - let mut table; - unsafe { - table = AcpiTables::search_for_rsdp_bios(acpi_handler); + // TODO: create a scratchpad module + if false { + // Currently not implemented + let acpi_handler = AcpiStruct {}; + let mut table; + unsafe { + table = AcpiTables::search_for_rsdp_bios(acpi_handler); + } } - } + ======= + mode.copy_to_buffer(); + } - */ + start_facepalm(); + scratchpad(); + >>>>>>> master + + */ // start_facepalm(); // scratchpad(); @@ -126,19 +123,6 @@ pub fn kernel_main() -> ! { sloop() } -/// called by arch specific timers to tick up all kernel related functions -pub fn tick() { - let mut data = TICK.load(Relaxed); - data += 1; - - crate::kernel_state::KERNEL_STATE.lock().update_state(); - // let mut scheduler = SCHEDULER.lock(); - // scheduler.bump_exec(); - // drop(scheduler); - - TICK.store(data, Relaxed) -} - pub fn cpu_socket_startup() { let mut cpu_info_socket = SimpleSock::new(); cpu_info_socket.register_protocol("CPU_INFO".to_string()); @@ -184,7 +168,7 @@ impl acpi::AcpiHandler for AcpiStruct { todo!("map_physical_region"); } - fn unmap_physical_region(region: &acpi::PhysicalMapping) { + fn unmap_physical_region(_region: &acpi::PhysicalMapping) { todo!("unmap_physical_region"); } } diff --git a/ableos/src/lib.rs b/ableos/src/lib.rs index 8a78b5926..27adca8b7 100644 --- a/ableos/src/lib.rs +++ b/ableos/src/lib.rs @@ -12,7 +12,8 @@ exclusive_range_pattern, lang_items, naked_functions, - slice_pattern + slice_pattern, + prelude_import )] /// Contains architecture specific code for aarch64. @@ -32,8 +33,10 @@ pub mod arch; #[macro_use] pub mod print; -// pub mod devices; -// pub mod wasm_jumploader; +pub mod devices; +pub mod port_io; +pub mod rhai_shell; +pub mod wasm_jumploader; #[macro_use] pub extern crate log; @@ -42,7 +45,6 @@ pub extern crate log; // Modules // ///////////// pub mod allocator; -pub mod boot_conf; pub mod driver_traits; pub mod experiments; pub mod graphics; @@ -50,8 +52,7 @@ pub mod kernel_state; pub mod keyboard; pub mod kmain; pub mod logger; -pub mod panic; -// pub mod proto_filetable; +pub mod proto_filetable; pub mod relib; pub mod scheduler; mod unicode_utils; @@ -66,34 +67,40 @@ pub extern crate externc_libm as libm; // Re-exports /// //////////////// pub use allocator::*; -pub use boot_conf::*; pub use driver_traits::*; pub use experiments::*; pub use graphics::*; pub use kernel_state::*; pub use keyboard::*; pub use logger::*; -pub use panic::*; -// pub use proto_filetable::*; +pub use proto_filetable::*; pub use relib::*; // pub use scheduler::*; pub use utils::*; // pub use vga_e::*; pub use wasm::*; - -////////////////// +pub mod boot_conf; pub mod virtio; pub use virtio::*; // pub mod alias_table; // pub use alias_table::*; -/* pub mod tests; pub use tests::*; -pub mod syscalls; -pub use syscalls::*; -*/ + pub mod scratchpad; pub use scratchpad::*; -// pub mod filesystem; +pub mod filesystem; + +/////////////// +/// Kernel /// +///////////// +pub use kernel; +pub use kernel::messaging; +pub use kernel::panic; + +pub mod prelude; + +#[prelude_import] +pub use prelude::rust_2021::*; diff --git a/ableos/src/logger.rs b/ableos/src/logger.rs index a0e083ffe..0b5cfdbc1 100644 --- a/ableos/src/logger.rs +++ b/ableos/src/logger.rs @@ -1,17 +1,12 @@ use core::sync::atomic::Ordering; -use crate::kmain::TICK; -// use crate::println; -use alloc::format; -// use alloc::fmt; +use crate::network::socket::{SimpleSock, Socket}; +use crate::serial_println; + +use kernel::TICK; use lliw::{Fg, Reset}; -pub use log::{debug, info, trace, warn}; use log::{Level, Metadata, Record}; -// use crate::arch::drivers::timer::TIMER_INTERRUPT_HERTZ; - -pub const TIMER_INTERRUPT_HERTZ: f64 = 100.0; - struct SimpleLogger; // TODO: Rebuild this to take advantage of sockets // DETAIL: Log to a socket instead of the screen @@ -26,7 +21,7 @@ impl log::Log for SimpleLogger { let color; let time = TICK.load(Ordering::Relaxed) as f64; - let time_float = time / TIMER_INTERRUPT_HERTZ; + let time_float = time; match record.level() { log::Level::Error => color = (Fg::Red, "$RED$"), @@ -35,7 +30,14 @@ impl log::Log for SimpleLogger { log::Level::Debug => color = (Fg::Blue, "$BLUE$"), log::Level::Trace => color = (Fg::Yellow, "$YELLOW$"), } - let xyz = format!( + let msg = format!( + "[{}{}$RESET$][$GREEN${}$RESET$]{}\n", + color.1, + record.level(), + time_float, + record.args() + ); + serial_println!( "[{}{}{}][{}{}{}] {}", color.0, record.level(), @@ -45,6 +47,14 @@ impl log::Log for SimpleLogger { Reset, record.args() ); + + let log_socket_id = SimpleSock::grab_socket("Logger".to_string()); + match log_socket_id { + Some(mut log_socket_id) => { + log_socket_id.write(msg.as_bytes().to_vec()); + } + None => warn!("No socket found for Logger"), + } } } /// Clear the log buffer diff --git a/ableos/src/panic.rs b/ableos/src/panic.rs deleted file mode 100644 index 28117a714..000000000 --- a/ableos/src/panic.rs +++ /dev/null @@ -1,30 +0,0 @@ -use alloc::string::ToString; - -use {crate::arch::sloop, core::panic::PanicInfo}; - -/// A function to handle a panic in the kernel. -/// # Example -/// ``` -/// use ableos::panic::panic; -/// panic!("This is a panic!"); -/// ``` -/// -/// # Safety -/// This function is unsafe because it does not guarantee that the panic is handled. -#[panic_handler] -fn panic(info: &PanicInfo) -> ! { - // error!("{}", info); - // help me use facepalm::start_facepalm; - - let uart_data = 0x10000000 as *mut u8; - - for c in b"panic" { - unsafe { uart_data.write_volatile(*c) }; - } - - sloop() -} - -pub fn test_panic() { - panic!("test panic!"); -} diff --git a/ableos/src/port_io.rs b/ableos/src/port_io.rs new file mode 100644 index 000000000..15b6d6669 --- /dev/null +++ b/ableos/src/port_io.rs @@ -0,0 +1,16 @@ +use cpuio::{inb, inl, outb, outl}; + +pub fn read32(reg: u16) -> u32 { + unsafe { inl(reg) } +} +pub fn read8(reg: u16) -> u8 { + unsafe { inb(reg) } +} + +pub fn write32(reg: u16, val: u32) { + unsafe { outl(val, reg) } +} + +pub fn write8(reg: u16, val: u8) { + unsafe { outb(val, reg) } +} diff --git a/ableos/src/prelude/mod.rs b/ableos/src/prelude/mod.rs new file mode 100644 index 000000000..77dad8eb6 --- /dev/null +++ b/ableos/src/prelude/mod.rs @@ -0,0 +1 @@ +pub mod rust_2021; diff --git a/ableos/src/prelude/rust_2021.rs b/ableos/src/prelude/rust_2021.rs new file mode 100644 index 000000000..dc001f504 --- /dev/null +++ b/ableos/src/prelude/rust_2021.rs @@ -0,0 +1,8 @@ +pub use core::arch::asm; +pub use core::prelude::rust_2021::*; +pub use core::prelude::v1::*; + +pub use crate::print::*; +pub use log::{debug, info, trace, warn}; + +pub use alloc::{boxed::Box, format, string::*, vec, vec::*}; diff --git a/ableos/src/print.rs b/ableos/src/print.rs index 8b1378917..8d1443d08 100644 --- a/ableos/src/print.rs +++ b/ableos/src/print.rs @@ -1 +1,51 @@ - +// TODO: refactor this file +// TODO: make STDOUT redirect to a socket owned +// by the process named "stdout" +pub struct Stdout; +use core::fmt::{Arguments, Error}; +impl Stdout { + pub fn write_fmt(&mut self, arg: Arguments<'_>) /*-> Result<(), Error> */ + { + let _ = core::fmt::Write::write_fmt(self, arg); + // Ok(()) + } +} +impl core::fmt::Write for Stdout { + #[cfg(target_arch = "aarch64")] + fn write_str(&mut self, s: &str) -> Result<(), Error> { + // Don't actually print anything yet lmao + Ok(()) + } + #[cfg(target_arch = "x86_64")] + fn write_str(&mut self, s: &str) -> Result<(), Error> { + use crate::kprint; + kprint!("{}", s); + Ok(()) + } + #[cfg(target_arch = "riscv64")] + fn write_str(&mut self, s: &str) -> Result<(), Error> { + Ok(()) + } + fn write_char(&mut self, c: char) -> core::fmt::Result { + self.write_str(c.encode_utf8(&mut [0; 4])) + } + fn write_fmt(mut self: &mut Self, args: Arguments<'_>) -> core::fmt::Result { + core::fmt::write(&mut self, args) + } +} +#[macro_export] +macro_rules! print { + () => { + ::core::writeln!($crate::print::Stdout, "") + }; + ($($tt:tt)*) => { + ::core::write!($crate::print::Stdout, $($tt)*) + }; +} +#[macro_export] +macro_rules! println { + ($($tt:tt)*) => { + ::core::writeln!($crate::print::Stdout, $($tt)*) + // panic![]; + }; +} diff --git a/ableos/src/proto_filetable/file.rs b/ableos/src/proto_filetable/file.rs index 4e0f0beac..eb3889ed0 100644 --- a/ableos/src/proto_filetable/file.rs +++ b/ableos/src/proto_filetable/file.rs @@ -1,7 +1,5 @@ use core::fmt; -use alloc::{string::String, vec, vec::Vec}; - #[derive(Debug, PartialEq, Clone)] pub struct PathRep { pub location: FileLocations, diff --git a/ableos/src/proto_filetable/mod.rs b/ableos/src/proto_filetable/mod.rs index 51103af3c..030c3a50c 100644 --- a/ableos/src/proto_filetable/mod.rs +++ b/ableos/src/proto_filetable/mod.rs @@ -15,11 +15,6 @@ //! The file table is not thread safe. //! The file table is not persistent. -use alloc::{ - string::{String, ToString}, - vec::Vec, -}; - use hashbrown::HashMap; pub mod contain; diff --git a/ableos/src/relib/clparse/mod.rs b/ableos/src/relib/clparse/mod.rs index c71a1886e..818d27b83 100644 --- a/ableos/src/relib/clparse/mod.rs +++ b/ableos/src/relib/clparse/mod.rs @@ -1,9 +1,3 @@ -use alloc::{ - string::{String, ToString}, - vec, - vec::Vec, -}; - /* clparse * A simple command line parser for ableOS diff --git a/ableos/src/relib/encoding/bin.rs b/ableos/src/relib/encoding/bin.rs index 6743bb60c..ad3cb1436 100644 --- a/ableos/src/relib/encoding/bin.rs +++ b/ableos/src/relib/encoding/bin.rs @@ -1,6 +1,3 @@ -use alloc::{boxed::Box}; - - pub struct BinCodeWriter { pub stream: Box, } diff --git a/ableos/src/relib/encoding/rle.rs b/ableos/src/relib/encoding/rle.rs index ef9f767c0..fcd4e8ce3 100644 --- a/ableos/src/relib/encoding/rle.rs +++ b/ableos/src/relib/encoding/rle.rs @@ -1,6 +1,3 @@ -use alloc::vec; -use alloc::vec::Vec; - pub fn encode(bytes: &[u8]) -> Vec { let mut encoding; diff --git a/ableos/src/relib/network/socket.rs b/ableos/src/relib/network/socket.rs index 414e0b5ec..9e35600ea 100644 --- a/ableos/src/relib/network/socket.rs +++ b/ableos/src/relib/network/socket.rs @@ -1,7 +1,3 @@ -use alloc::string::String; -use alloc::vec; -use alloc::vec::Vec; - pub type Stream = Vec; #[derive(Debug)] diff --git a/ableos/src/relib/time/mod.rs b/ableos/src/relib/time/mod.rs index b87e3284e..b4327e156 100644 --- a/ableos/src/relib/time/mod.rs +++ b/ableos/src/relib/time/mod.rs @@ -1,20 +1,20 @@ pub struct Time { - pub year: u16, - pub month: u16, - pub day: u16, - pub hour: u16, - pub minutes: u16, - pub seconds: u16, - pub microseconds: u32, + pub year: u16, + pub month: u16, + pub day: u16, + pub hour: u16, + pub minutes: u16, + pub seconds: u16, + pub microseconds: u32, } impl fmt::Display for Time { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!( - f, - "{:?}/{:?}/{:?} {:02}:{:02}:{:02}", - self.year, self.month, self.day, self.hour, self.minutes, self.seconds - ) - } + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!( + f, + "{:?}/{:?}/{:?} {:02}:{:02}:{:02}", + self.year, self.month, self.day, self.hour, self.minutes, self.seconds + ) + } } pub mod kilotime; use core::fmt; diff --git a/ableos/src/rhai_shell/mod.rs b/ableos/src/rhai_shell/mod.rs new file mode 100644 index 000000000..cf7773fac --- /dev/null +++ b/ableos/src/rhai_shell/mod.rs @@ -0,0 +1,122 @@ +pub fn rhai_shell() { + let engine = engine_construction(); + let mut scope = rhai::Scope::new(); + + let mut buf = String::new(); + print!("> "); + + loop { + match x86_64::instructions::interrupts::without_interrupts(|| KEYBUFF.lock().pop()) { + Some('\n') => { + match engine.eval_with_scope::(&mut scope, &buf) { + Ok(o) => println!("{o}"), + Err(e) => println!("Eval error: {e}"), + }; + + buf.clear(); + print!("> "); + } + Some('\u{0008}') => { + buf.pop(); + } + Some(chr) => buf.push(chr), + None => (), + } + } +} +lazy_static::lazy_static!( + pub static ref KEYBUFF: spin::Mutex> = spin::Mutex::new( + Vec::new()) + ; +); + +use rhai::Engine; +use x86_64::instructions::interrupts::{disable, enable}; + +use crate::wasm_jumploader::interp; +use crate::{ + arch::{shutdown, sloop}, + systeminfo::{KERNEL_VERSION, RELEASE_TYPE}, + KERNEL_STATE, +}; +use kernel::TICK; + +pub fn afetch() { + let kstate = KERNEL_STATE.lock(); + use core::sync::atomic::Ordering::*; + + disable(); + let tick_time = TICK.load(Relaxed); + + println!( + "OS: AbleOS +Host: {} +Kernel: AKern-{}-v{} +Uptime: {}", + kstate.hostname, RELEASE_TYPE, KERNEL_VERSION, tick_time + ); + enable(); + drop(kstate); +} +pub fn set_hostname(name: String) { + let mut kstate = KERNEL_STATE.lock(); + kstate.hostname = name; +} + +fn engine_construction() -> Engine { + let mut engine = rhai::Engine::new(); + + engine.on_print(|x| println!("{}", x)); + + engine.on_debug(|x, src, pos| { + let src = src.unwrap_or("unknown"); + println!("DEBUG: {} at {:?}: {}", src, pos, x); + debug!("{} at {:?}: {}", src, pos, x); + }); + + engine.register_fn("afetch", afetch); + engine.register_fn("set_hostname", set_hostname); + engine.register_fn("shutdown", shutdown); + engine.register_fn("peek", peek_memory); + engine.register_fn("poke", poke_memory); + engine.register_fn("sloop", sloop); + engine.register_fn("wasm", interp); + engine.register_fn("log_dump", log_dump); + + engine +} + +/// Examine a memory pointer +pub fn peek_memory(ptr: i64) -> u8 { + let ptr: usize = ptr as usize; + println!(">:("); + unsafe { *(ptr as *const u8) } +} + +pub fn poke_memory(ptr: i64, val: u8) { + let ptr: usize = ptr as usize; + unsafe { *(ptr as *mut u8) = val } +} + +pub fn log_dump() { + use crate::network::socket::SimpleSock; + use crate::relib::network::socket::Socket; + let log_socket_id = SimpleSock::grab_socket("Logger".to_string()); + match log_socket_id { + Some(mut log_socket_id) => { + let log = log_socket_id.peek(); + + match log { + crate::network::socket::SocketReturns::ReadOk(ok) => { + for x in ok.iter() { + print!("{}", *x as char); + } + } + + crate::network::socket::SocketReturns::ReadIndexOutOfBounds => todo!(), + crate::network::socket::SocketReturns::WriteOk => todo!(), + } + } + None => warn!("No socket found for Logger"), + } +} diff --git a/ableos/src/scheduler/capabilities.rs b/ableos/src/scheduler/capabilities.rs index 7536d3d1d..a490f50b7 100644 --- a/ableos/src/scheduler/capabilities.rs +++ b/ableos/src/scheduler/capabilities.rs @@ -1,4 +1,4 @@ -use alloc::vec::Vec; +#![allow(missing_docs)] pub type SoundCardID = u8; pub type DeviceID = u8; diff --git a/ableos/src/scheduler/mod.rs b/ableos/src/scheduler/mod.rs index 54bc61fad..9449181eb 100644 --- a/ableos/src/scheduler/mod.rs +++ b/ableos/src/scheduler/mod.rs @@ -1,4 +1,4 @@ -#![warn(missing_docs)] +// #![warn(missing_docs)] //! The standard ableOS scheduler named //! @@ -6,8 +6,6 @@ //! The scheduler is also responsible for choosing the priority of a process. //! The scheduler is responsible for choosing which process to execute next. -use alloc::{string::ToString, vec::Vec}; - pub mod capabilities; pub mod proc; diff --git a/ableos/src/scheduler/new_sched.rs b/ableos/src/scheduler/new_sched.rs index dbd246c7e..4a39a93df 100644 --- a/ableos/src/scheduler/new_sched.rs +++ b/ableos/src/scheduler/new_sched.rs @@ -1,10 +1,8 @@ -use crate::kmain::generate_process_pass; -use alloc::{string::ToString, vec::Vec}; - -use super::{ - capabilities::Capabilities, - proc::{Process, PID}, - Priority, +use crate::{ + kmain::generate_process_pass, + scheduler::capabilities::Capabilities, + scheduler::proc::{Process, PID}, + scheduler::Priority, }; /// Add additional wake conditions to the list pub enum WakeCondition { diff --git a/ableos/src/scheduler/proc.rs b/ableos/src/scheduler/proc.rs index 1d3955a2f..ee135a812 100644 --- a/ableos/src/scheduler/proc.rs +++ b/ableos/src/scheduler/proc.rs @@ -1,7 +1,5 @@ //! Process definition and general utilities surrounding them -use alloc::string::String; - use super::{capabilities::Capabilities, Priority}; /// Process Identification diff --git a/ableos/src/scratchpad.rs b/ableos/src/scratchpad.rs index 325771bd6..f6f812638 100644 --- a/ableos/src/scratchpad.rs +++ b/ableos/src/scratchpad.rs @@ -1,108 +1,37 @@ -use alloc::{format, vec::Vec}; +use acpi::AcpiTables; + +use crate::rhai_shell::rhai_shell; /// Experimental scratchpad for testing. pub fn scratchpad() { - /* - let mut dev_list = Vec::new(); - - let bus_scan; - unsafe { - bus_scan = pci::scan_bus(&PciIO {}, pci::CSpaceAccessMethod::IO); - } - for dev in bus_scan { - dev_list.push(dev); - } - - let device_table = &mut *DEVICE_TABLE.lock(); - - for x in dev_list { - let device_name = format!("{:?}-{}", DeviceClass::from_u8(x.id.class), x.id.device_id); - - device_table - .devices - .insert(device_name.clone(), Device::Pci(x)); - } - */ - /* - for (key, _value) in device_table.devices.iter() { - debug!("{}", key); - } - */ - // interp(); - - // rhai_shell(); + pci_fun(); + rhai_shell(); } -/* -pub struct PciIO {} -impl PortOps for PciIO { - unsafe fn read8(&self, port: u16) -> u8 { - cpuio::inb(port as u16) - } +pub fn pci_fun() {} - unsafe fn read16(&self, port: u16) -> u16 { - cpuio::inw(port as u16) - } - - unsafe fn read32(&self, port: u16) -> u32 { - cpuio::inl(port as u16) - } - - unsafe fn write8(&self, port: u16, val: u8) { - cpuio::outb(val, port as u16); - } - - unsafe fn write16(&self, port: u16, val: u16) { - cpuio::outw(val, port as u16); - } - - unsafe fn write32(&self, port: u16, val: u32) { - cpuio::outl(val, port as u16); +pub fn acpi() { + let acpi_handler = AcpiStruct {}; + let _table; + unsafe { + _table = AcpiTables::search_for_rsdp_bios(acpi_handler); } } -*/ -/* -/// An experimental process message format -pub struct ProcessMessage { - pub to_pid: PID, - pub from_pid: PID, - pub message: [u8; 2048], - pub sender_time: SecondsTime, -} -// -// use libwasm::syscalls::time_calls::SecondsTime; - -impl ProcessMessage { - pub fn new(to_pid: PID, from_pid: PID, message: [u8; 2048]) -> Self { - ProcessMessage { - to_pid, - from_pid, - message, - sender_time: SecondsTime { - seconds: 0, - milliseconds: 0, - }, - } +// TODO: move to a better place +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct AcpiStruct {} +impl acpi::AcpiHandler for AcpiStruct { + unsafe fn map_physical_region( + &self, + physical_address: usize, + size: usize, + ) -> acpi::PhysicalMapping { + info!("PHYS ADDR: {:?}", physical_address); + info!("Size: {:?}", size); + todo!("map_physical_region"); + } + fn unmap_physical_region(_region: &acpi::PhysicalMapping) { + todo!("unmap_physical_region"); } } -*/ - -pub fn rhai_shell() { - let mut engine = rhai::Engine::new(); - - let ret = engine.eval::("1 + 2"); - - match ret { - // Ok(x) => println!("{}", x), - // Err(e) => println!("{}", e), - _ => (), - } - - loop {} -} -lazy_static::lazy_static!( - pub static ref KEYBUFF: spin::Mutex> = spin::Mutex::new( - Vec::new()) - ; -); diff --git a/ableos/src/tests.rs b/ableos/src/tests.rs index bbfca8daa..07ce4401c 100644 --- a/ableos/src/tests.rs +++ b/ableos/src/tests.rs @@ -1,8 +1,3 @@ -use alloc::{ - format, - string::{String, ToString}, - vec, -}; use picorand::PicoRandGenerate; use rkyv::{ser::serializers::AllocSerializer, Deserialize}; use shadeable::pixel_format::from_vga_16; @@ -10,13 +5,14 @@ use vga::colors::Color16; use y_compositor_protocol::Version; use crate::{ - kmain::{BOOT_CONF, TICK}, + kmain::KERNEL_CONF, network::socket::{SimpleSock, Socket, SocketReturns}, - num_to_vga16, vga_e, VgaBuffer, SCREEN_BUFFER, + num_to_vga16, VgaBuffer, SCREEN_BUFFER, }; +use kernel::TICK; pub fn run_tests() { - if BOOT_CONF.run_tests { + if KERNEL_CONF.tests.run_tests { // quick and dirty testing framework screen_writer_test(); socket_test(); @@ -25,11 +21,11 @@ pub fn run_tests() { socket_test_rng(); } - if BOOT_CONF.run_demos { + if KERNEL_CONF.tests.run_demos { graphics_api_demo(); } - if BOOT_CONF.run_shader_tests { + if KERNEL_CONF.tests.run_shader_tests { shader_tests(); } } diff --git a/ableos/src/utils.rs b/ableos/src/utils.rs index 5ec7612f2..d8de1fa03 100644 --- a/ableos/src/utils.rs +++ b/ableos/src/utils.rs @@ -2,7 +2,7 @@ //! //! //! - +#[inline] pub fn type_of(_: &T) -> &str { core::any::type_name::() } diff --git a/ableos/src/vga_e.rs b/ableos/src/vga_e.rs index fb21b8ac4..440be286d 100644 --- a/ableos/src/vga_e.rs +++ b/ableos/src/vga_e.rs @@ -1,13 +1,6 @@ -use shadeable::pixel_format::Rgba64; - -use crate::SCREEN_BUFFER; - -use { - ab_glyph::{Font, FontRef, Glyph}, - vga::{ - colors::Color16, - writers::{Graphics640x480x16, GraphicsWriter}, - }, +use vga::{ + colors::Color16, + writers::{Graphics640x480x16, GraphicsWriter}, }; lazy_static::lazy_static! { @@ -20,28 +13,27 @@ lazy_static::lazy_static! { pub static ref VGAE_BUFF_OFFSET_Y: spin::Mutex = spin::Mutex::new(0); } - /// Converts a number to ... i forgor 💀 pub fn num_to_vga16(num: u8) -> Color16 { - use Color16::*; - match num { - 0 => Black, - 1 => Blue, - 2 => Green, - 3 => Cyan, - 4 => Red, - 5 => Magenta, - 6 => Brown, - 7 => LightGrey, - 8 => DarkGrey, - 9 => LightBlue, - 10 => LightGreen, - 11 => LightCyan, - 12 => LightRed, - 13 => Pink, - 14 => Yellow, - 15 => White, - // NOTE: Leasve the in - _ => Color16::Pink, - } + use Color16::*; + match num { + 0 => Black, + 1 => Blue, + 2 => Green, + 3 => Cyan, + 4 => Red, + 5 => Magenta, + 6 => Brown, + 7 => LightGrey, + 8 => DarkGrey, + 9 => LightBlue, + 10 => LightGreen, + 11 => LightCyan, + 12 => LightRed, + 13 => Pink, + 14 => Yellow, + 15 => White, + // NOTE: Leasve the in + _ => Color16::Pink, + } } diff --git a/ableos/src/wasm/mod.rs b/ableos/src/wasm/mod.rs index 58c4ca0c9..9d77b9f2c 100644 --- a/ableos/src/wasm/mod.rs +++ b/ableos/src/wasm/mod.rs @@ -1,5 +1,3 @@ -use alloc::vec::Vec; - /// `NULL a s m` as an array of 4 bytes pub const WASM_BINARY_MAGIC: [u8; 4] = [0x00, 0x61, 0x73, 0x6d]; /// `1 0 0 0` as an array of 4 bytes diff --git a/ableos/src/wasm_jumploader/host_functions.rs b/ableos/src/wasm_jumploader/host_functions.rs index 25cfa2ec3..52140c339 100644 --- a/ableos/src/wasm_jumploader/host_functions.rs +++ b/ableos/src/wasm_jumploader/host_functions.rs @@ -1,4 +1,3 @@ -use alloc::format; use wasmi::{ Error, Externals, FuncInstance, FuncRef, ModuleImportResolver, RuntimeArgs, RuntimeValue, Signature, Trap, ValueType, @@ -7,6 +6,8 @@ use wasmi::{ pub struct HostExternals {} const ADD_FUNC_INDEX: usize = 0; +const SEND_SIGNAL_INDEX: usize = 1; +const GET_TIME_INDEX: usize = 2; impl Externals for HostExternals { fn invoke_index( @@ -22,6 +23,25 @@ impl Externals for HostExternals { println!("SYSCALL: {} + {} = {}", a, b, result); Ok(Some(RuntimeValue::I32(result as i32))) } + SEND_SIGNAL_INDEX => { + let pid: u32 = args.nth_checked(0)?; + let signal: u32 = args.nth_checked(1)?; + + println!("SYSCALL: send signal {} to pid {}", signal, pid); + let ret = RuntimeValue::I32(0); + Ok(Some(ret)) + } + + GET_TIME_INDEX => { + use core::sync::atomic::Ordering::*; + + x86_64::instructions::interrupts::disable(); + let tick_time = kernel::TICK.load(Relaxed); + x86_64::instructions::interrupts::enable(); + + let ret = RuntimeValue::I64(tick_time.try_into().unwrap()); + Ok(Some(ret)) + } _ => panic!("Unimplemented function at {}", index), } } @@ -31,6 +51,8 @@ impl HostExternals { fn check_signature(&self, index: usize, signature: &Signature) -> bool { let (params, ret_ty): (&[ValueType], Option) = match index { ADD_FUNC_INDEX => (&[ValueType::I32, ValueType::I32], Some(ValueType::I32)), + SEND_SIGNAL_INDEX => (&[ValueType::I32, ValueType::I32], Some(ValueType::I32)), + GET_TIME_INDEX => (&[], Some(ValueType::I32)), _ => return false, }; signature.params() == params && signature.return_type() == ret_ty @@ -41,6 +63,7 @@ impl ModuleImportResolver for HostExternals { fn resolve_func(&self, field_name: &str, signature: &Signature) -> Result { let index = match field_name { "add" => ADD_FUNC_INDEX, + "send_signal" => SEND_SIGNAL_INDEX, _ => { return Err(Error::Instantiation(format!( "Export {} not found", diff --git a/ableos/src/wasm_jumploader/mod.rs b/ableos/src/wasm_jumploader/mod.rs index 35b47883d..02c06a405 100644 --- a/ableos/src/wasm_jumploader/mod.rs +++ b/ableos/src/wasm_jumploader/mod.rs @@ -3,24 +3,26 @@ pub mod host_functions; extern crate wasmi; // extern crate wabt; -use alloc::vec::Vec; use genfs::{Fs, OpenOptions}; use wasmi::{ImportsBuilder, ModuleInstance}; use crate::{filesystem::FILE_SYSTEM, wasm_jumploader::host_functions::HostExternals}; pub fn interp() { - info!("Interpreting..."); + trace!("Interpreting..."); let fs = &*FILE_SYSTEM.lock(); - info!("Got filesystem"); + trace!("Got filesystem"); let file = fs - .open(b"/home/able/bins/test.wasm", OpenOptions::new().read(true)) + .open( + b"/home/able/bins/aos_wasm_stress_test.wasm", + OpenOptions::new().read(true), + ) .unwrap(); let mut wasm_binary = Vec::new(); let ret = file.read_to_end(&mut wasm_binary).unwrap(); - info!("Binary size {}", ret); + trace!("Binary size {}", ret); // Load wasm binary and prepare it for instantiation. let module = wasmi::Module::from_buffer(&wasm_binary).expect("failed to load wasm"); diff --git a/kernel/.cargo/config.toml b/kernel/.cargo/config.toml new file mode 100644 index 000000000..027749376 --- /dev/null +++ b/kernel/.cargo/config.toml @@ -0,0 +1,2 @@ +[build] +target = "./json_targets/x86_64-ableos.json" diff --git a/kernel/Cargo.lock b/kernel/Cargo.lock new file mode 100644 index 000000000..b2f29bf89 --- /dev/null +++ b/kernel/Cargo.lock @@ -0,0 +1,22 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "kernel" +version = "0.1.2" +dependencies = [ + "lazy_static", + "versioning", +] + +[[package]] +name = "lazy_static" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" + +[[package]] +name = "versioning" +version = "0.1.2" +source = "git+https://git.ablecorp.us/able/versioning#ef472283e6e7a2e395ee56434087b3a6fad53ff2" diff --git a/kernel/Cargo.toml b/kernel/Cargo.toml new file mode 100644 index 000000000..7c1c003dc --- /dev/null +++ b/kernel/Cargo.toml @@ -0,0 +1,15 @@ +[package] +edition = "2021" +name = "kernel" +version = "0.1.2" + + +[dependencies] +log = "0.4.14" + +[dependencies.lazy_static] +version = "1.4.0" +default-features = false + +[dependencies.versioning] +git = "https://git.ablecorp.us/able/versioning" \ No newline at end of file diff --git a/kernel/src/device_interface/block/mod.rs b/kernel/src/device_interface/block/mod.rs new file mode 100644 index 000000000..9d0f028e5 --- /dev/null +++ b/kernel/src/device_interface/block/mod.rs @@ -0,0 +1 @@ +//! diff --git a/ableos/src/driver_traits/character_device.rs b/kernel/src/device_interface/character/mod.rs similarity index 67% rename from ableos/src/driver_traits/character_device.rs rename to kernel/src/device_interface/character/mod.rs index d128c72f8..443d12a52 100644 --- a/ableos/src/driver_traits/character_device.rs +++ b/kernel/src/device_interface/character/mod.rs @@ -1,3 +1,6 @@ +//! + +/// Character device interface. pub trait CharacterDevice { /// Returns true if the device can be read from. fn can_read(&self) -> bool; @@ -7,4 +10,8 @@ pub trait CharacterDevice { fn read_char(&mut self) -> Option; /// Writes a single character to the device and returns true if the write was successful fn write_char(&mut self, c: char) -> bool; + /// Reset the device to its initial state + fn reset(&mut self); + /// initializes the device, returns true if successful + fn initialize(&mut self) -> bool; } diff --git a/kernel/src/device_interface/mod.rs b/kernel/src/device_interface/mod.rs new file mode 100644 index 000000000..7fe7faaf8 --- /dev/null +++ b/kernel/src/device_interface/mod.rs @@ -0,0 +1,4 @@ +//! Platform Agnostic Device + +pub mod block; +pub mod character; diff --git a/kernel/src/lib.rs b/kernel/src/lib.rs new file mode 100644 index 000000000..7ed790e91 --- /dev/null +++ b/kernel/src/lib.rs @@ -0,0 +1,35 @@ +#![deny(missing_docs)] +#![no_std] +#![feature(prelude_import)] + +//! The ableOS kernel. + +pub mod device_interface; +pub mod messaging; +pub mod panic; +pub mod proccess; +pub mod time; + +use core::sync::atomic::{AtomicU64, Ordering::Relaxed}; + +use versioning::Version; + +/// called by arch specific timers to tick up all kernel related functions +pub fn tick() { + let mut data = TICK.load(Relaxed); + data = data.wrapping_add(1); + + TICK.store(data, Relaxed) +} + +lazy_static::lazy_static! { + /// The number of ticks since the first CPU was started + pub static ref TICK: AtomicU64 = AtomicU64::new(0); +} + +/// +pub const KERNEL_VERSION: Version = Version { + major: 0, + minor: 1, + patch: 2, +}; diff --git a/kernel/src/messaging.rs b/kernel/src/messaging.rs new file mode 100644 index 000000000..068919ff7 --- /dev/null +++ b/kernel/src/messaging.rs @@ -0,0 +1,67 @@ +//! Interprocess communication. + +use crate::{proccess::PID, time::Time}; + +/// 128 Bytes +pub type Tiny = [u8; 128]; + +/// 1 KiB +pub type Small = [u8; 1024]; + +/// 65.536 KiB +pub type Medium = [u8; 65536]; + +/// 1MiB +pub type Large = [u8; 1048576]; + +/// 16MiB +pub type Huge = [u8; 16777216]; + +/// An internal message to be held in a process message +pub enum Message { + /// A Tiny message + /// + /// The message is 128 bytes long + Tiny(Tiny), + /// A Small message + /// + /// The message is 1 KiB long + Small(Small), + /// A Medium message + /// + /// The message is 65.536 KiB long + Medium(Medium), + /// A Large message + /// + /// The message is 1 MiB long + Large(Large), + /// A Huge message + /// + /// The message is 16 MiB long + Huge(Huge), +} + +/// A message that can be sent between processes +pub struct ProcessMessage { + /// The sender of the message + pub to_pid: PID, + /// The receiver of the message + pub from_pid: PID, + /// The message + pub message: Message, + /// The time the message was sent + pub sender_time: Time, + /// The time the message was received + pub receiver_time: Time, +} + +#[derive(Debug)] +/// An enum of all possible errors that can occur when sending a message +pub enum MessagingError { + /// The message is too large to be sent + MessageTooLarge, + /// The reciever of the message is not valid + ProcessNonExistant, + /// The message Queue is full + TooManyMessages, +} diff --git a/kernel/src/panic.rs b/kernel/src/panic.rs new file mode 100644 index 000000000..74602f662 --- /dev/null +++ b/kernel/src/panic.rs @@ -0,0 +1,12 @@ +//! +use core::panic::PanicInfo; + +// #[macro_use] +// use log; + +#[panic_handler] +fn panic_handler(_info: &PanicInfo) -> ! { + // error!("{}", _info); + + loop {} +} diff --git a/kernel/src/proccess.rs b/kernel/src/proccess.rs new file mode 100644 index 000000000..7077cbd30 --- /dev/null +++ b/kernel/src/proccess.rs @@ -0,0 +1,4 @@ +//! Platform agnostic process + +/// A process ID +pub type PID = u64; diff --git a/kernel/src/time.rs b/kernel/src/time.rs new file mode 100644 index 000000000..f4f1ed939 --- /dev/null +++ b/kernel/src/time.rs @@ -0,0 +1,10 @@ +//! Time + +/// An internal structure that is used to keep track of the time +pub struct Time { + /// The number of seconds since the kernel was started + pub seconds: u64, + + /// The number of nanoseconds since the kernel was started + pub nanoseconds: u32, +} diff --git a/shadeable/src/engine_internals.rs b/shadeable/src/engine_internals.rs index 1013c8738..960a25451 100644 --- a/shadeable/src/engine_internals.rs +++ b/shadeable/src/engine_internals.rs @@ -1,5 +1,5 @@ use crate::pixel_format::{get_a, get_b, get_g, get_r, set_a, set_b, set_g, set_r}; -use crate::pixel_format::{new_rgba64, rgba_div, Rgba64}; +use crate::pixel_format::{rgba_div, Rgba64}; use log::{debug, info}; use rhai::Engine; @@ -7,13 +7,13 @@ use rhai::Engine; pub fn engine_startup() -> Engine { let mut engine = Engine::new(); - // engine.on_print(|x| info!("PRINTED FROM SHADER: {}", x)); + engine.on_print(|x| info!("PRINTED FROM SHADER: {}", x)); // Any function or closure that takes a '&str', an 'Option<&str>' and a 'Position' argument // can be used to override 'debug'. engine.on_debug(|x, src, pos| { let src = src.unwrap_or("unknown"); - // debug!("SHADER DEBUG of {} at {:?}: {}", src, pos, x) + debug!("SHADER DEBUG of {} at {:?}: {}", src, pos, x); }); engine diff --git a/shadeable/src/pixel_format.rs b/shadeable/src/pixel_format.rs index f3b3d0335..8c4bf8bbd 100644 --- a/shadeable/src/pixel_format.rs +++ b/shadeable/src/pixel_format.rs @@ -69,101 +69,101 @@ impl From for ChannelValue { /* pub fn into_vga_16(rgba_64: Rgba64) -> Color16 { - use ChannelValue::*; - use Color16::*; - match ( - get_r(rgba_64).into(), - get_g(rgba_64).into(), - get_b(rgba_64).into(), - ) { - (Dark, Dark, Dark) => Black, - (Dark, Dark, Low) => Black, - (Dark, Dark, Mid) => Blue, - (Dark, Dark, High) => Blue, - (Dark, Low, Dark) => Black, - (Dark, Low, Low) => Black, - (Dark, Low, Mid) => Blue, - (Dark, Low, High) => Blue, - (Dark, Mid, Dark) => Green, - (Dark, Mid, Low) => Green, - (Dark, Mid, Mid) => Cyan, - (Dark, Mid, High) => Cyan, - (Dark, High, Dark) => Green, - (Dark, High, Low) => Green, - (Dark, High, Mid) => Green, - (Dark, High, High) => Cyan, - (Low, Dark, Dark) => Black, - (Low, Dark, Low) => Black, - (Low, Dark, Mid) => Blue, - (Low, Dark, High) => Blue, - (Low, Low, Dark) => Black, - (Low, Low, Low) => DarkGrey, - (Low, Low, Mid) => LightGrey, - (Low, Low, High) => Blue, - (Low, Mid, Dark) => DarkGrey, - (Low, Mid, Low) => LightGrey, - (Low, Mid, Mid) => Cyan, - (Low, Mid, High) => Cyan, - (Low, High, Dark) => Green, - (Low, High, Low) => Green, - (Low, High, Mid) => Cyan, - (Low, High, High) => Cyan, - (Mid, Dark, Dark) => Red, - (Mid, Dark, Low) => Red, - (Mid, Dark, Mid) => Magenta, - (Mid, Dark, High) => Magenta, - (Mid, Low, Dark) => Brown, - (Mid, Low, Low) => Red, - (Mid, Low, Mid) => DarkGrey, - (Mid, Low, High) => LightBlue, - (Mid, Mid, Dark) => Brown, - (Mid, Mid, Low) => Brown, - (Mid, Mid, Mid) => LightGrey, - (Mid, Mid, High) => LightBlue, - (Mid, High, Dark) => Green, - (Mid, High, Low) => Green, - (Mid, High, Mid) => LightGreen, - (Mid, High, High) => LightCyan, - (High, Dark, Dark) => Red, - (High, Dark, _) => Magenta, - (High, Low, Dark) => Red, - (High, Low, Low) => LightRed, - (High, Low, Mid) => Pink, - (High, Low, High) => Magenta, - (High, Mid, Dark) => Yellow, - (High, Mid, Low) => Yellow, - (High, Mid, Mid) => LightRed, - (High, Mid, High) => Pink, - (High, High, Dark) => Yellow, - (High, High, Low) => White, - (High, High, Mid) => White, - (High, High, High) => White, - } + use ChannelValue::*; + use Color16::*; + match ( + get_r(rgba_64).into(), + get_g(rgba_64).into(), + get_b(rgba_64).into(), + ) { + (Dark, Dark, Dark) => Black, + (Dark, Dark, Low) => Black, + (Dark, Dark, Mid) => Blue, + (Dark, Dark, High) => Blue, + (Dark, Low, Dark) => Black, + (Dark, Low, Low) => Black, + (Dark, Low, Mid) => Blue, + (Dark, Low, High) => Blue, + (Dark, Mid, Dark) => Green, + (Dark, Mid, Low) => Green, + (Dark, Mid, Mid) => Cyan, + (Dark, Mid, High) => Cyan, + (Dark, High, Dark) => Green, + (Dark, High, Low) => Green, + (Dark, High, Mid) => Green, + (Dark, High, High) => Cyan, + (Low, Dark, Dark) => Black, + (Low, Dark, Low) => Black, + (Low, Dark, Mid) => Blue, + (Low, Dark, High) => Blue, + (Low, Low, Dark) => Black, + (Low, Low, Low) => DarkGrey, + (Low, Low, Mid) => LightGrey, + (Low, Low, High) => Blue, + (Low, Mid, Dark) => DarkGrey, + (Low, Mid, Low) => LightGrey, + (Low, Mid, Mid) => Cyan, + (Low, Mid, High) => Cyan, + (Low, High, Dark) => Green, + (Low, High, Low) => Green, + (Low, High, Mid) => Cyan, + (Low, High, High) => Cyan, + (Mid, Dark, Dark) => Red, + (Mid, Dark, Low) => Red, + (Mid, Dark, Mid) => Magenta, + (Mid, Dark, High) => Magenta, + (Mid, Low, Dark) => Brown, + (Mid, Low, Low) => Red, + (Mid, Low, Mid) => DarkGrey, + (Mid, Low, High) => LightBlue, + (Mid, Mid, Dark) => Brown, + (Mid, Mid, Low) => Brown, + (Mid, Mid, Mid) => LightGrey, + (Mid, Mid, High) => LightBlue, + (Mid, High, Dark) => Green, + (Mid, High, Low) => Green, + (Mid, High, Mid) => LightGreen, + (Mid, High, High) => LightCyan, + (High, Dark, Dark) => Red, + (High, Dark, _) => Magenta, + (High, Low, Dark) => Red, + (High, Low, Low) => LightRed, + (High, Low, Mid) => Pink, + (High, Low, High) => Magenta, + (High, Mid, Dark) => Yellow, + (High, Mid, Low) => Yellow, + (High, Mid, Mid) => LightRed, + (High, Mid, High) => Pink, + (High, High, Dark) => Yellow, + (High, High, Low) => White, + (High, High, Mid) => White, + (High, High, High) => White, + } } pub fn from_vga_16(color: Color16) -> Rgba64 { - use Color16::*; - match color { - Black => new_rgba64(0, 0, 0, 0), - DarkGrey => new_rgba64(105, 105, 105, 0), - LightGrey => new_rgba64(211, 211, 211, 0), - // - Blue => new_rgba64(0, 0, 0xff, 0), - Green => new_rgba64(0, 0xff, 0, 0), - Red => new_rgba64(0xff, 0, 0, 0), - // - Yellow => new_rgba64(0xff, 0xff, 0, 0), - Cyan => new_rgba64(0, 0xff, 0xff, 0), - Magenta => new_rgba64(0xff, 0, 0xff, 0), + use Color16::*; + match color { + Black => new_rgba64(0, 0, 0, 0), + DarkGrey => new_rgba64(105, 105, 105, 0), + LightGrey => new_rgba64(211, 211, 211, 0), + // + Blue => new_rgba64(0, 0, 0xff, 0), + Green => new_rgba64(0, 0xff, 0, 0), + Red => new_rgba64(0xff, 0, 0, 0), + // + Yellow => new_rgba64(0xff, 0xff, 0, 0), + Cyan => new_rgba64(0, 0xff, 0xff, 0), + Magenta => new_rgba64(0xff, 0, 0xff, 0), - Brown => new_rgba64(165, 42, 42, 0), - Pink => new_rgba64(0xff, 105, 180, 0), - White => new_rgba64(0xff, 0xff, 0xff, 0), + Brown => new_rgba64(165, 42, 42, 0), + Pink => new_rgba64(0xff, 105, 180, 0), + White => new_rgba64(0xff, 0xff, 0xff, 0), - LightBlue => new_rgba64(173, 216, 230, 0), - LightGreen => new_rgba64(144, 238, 144, 0), - LightCyan => new_rgba64(88, 100, 100, 0), - LightRed => new_rgba64(0xff, 204, 203, 0), - } + LightBlue => new_rgba64(173, 216, 230, 0), + LightGreen => new_rgba64(144, 238, 144, 0), + LightCyan => new_rgba64(88, 100, 100, 0), + LightRed => new_rgba64(0xff, 204, 203, 0), + } } */ diff --git a/userland/aos_wasm_stress_test/Cargo.lock b/userland/aos_wasm_stress_test/Cargo.lock index d208d6030..6b2bc0feb 100644 --- a/userland/aos_wasm_stress_test/Cargo.lock +++ b/userland/aos_wasm_stress_test/Cargo.lock @@ -12,4 +12,4 @@ dependencies = [ [[package]] name = "libwasm" version = "0.1.0" -source = "git+https://git.ablecorp.us/able/libwasm.git#502187e8734b54df3c6cae2baf2315539a3ec49b" +source = "git+https://git.ablecorp.us/able/libwasm.git#dedbb769ba01a4b75992437e52ca9a5c2bb9e0f9" diff --git a/userland/aos_wasm_stress_test/readme.md b/userland/aos_wasm_stress_test/readme.md index 03b81cc9b..3a68e32af 100644 --- a/userland/aos_wasm_stress_test/readme.md +++ b/userland/aos_wasm_stress_test/readme.md @@ -1,4 +1,4 @@ -This is a stress test and simple progrram for ableOS. +This is a stress test and simple program for ableOS. + -There should be two sub commands echo and input diff --git a/userland/aos_wasm_stress_test/src/main.rs b/userland/aos_wasm_stress_test/src/main.rs index a3fd82be1..73ee3802e 100644 --- a/userland/aos_wasm_stress_test/src/main.rs +++ b/userland/aos_wasm_stress_test/src/main.rs @@ -1,12 +1,36 @@ #![no_std] #![no_main] -#![deny(improper_ctypes)] #[no_mangle] fn start() -> i32 { let ret = unsafe { add(1, 2) }; + unsafe { + send_signal(PID(1), Signals::Quit); + } ret as i32 } -use libwasm::syscalls::add; +extern "C" { + + /// Send a signal to a process + /// + /// # Arguments + /// + /// * `pid` - The PID of the process to send the signal to + /// * `signal` - The signal to send + pub fn send_signal(pid: PID, signal: Signals) -> bool; +} + +use { + libwasm::process::{signals::Signals, PID}, + libwasm::syscalls::add, +}; + +use libwasm::*; + +#[panic_handler] +fn panic(_info: &PanicInfo) -> ! { + loop {} +} +use core::panic::PanicInfo; diff --git a/userland/root_rs/ext2.img b/userland/root_rs/ext2.img index 4927e5a85..15b29de6a 100644 Binary files a/userland/root_rs/ext2.img and b/userland/root_rs/ext2.img differ diff --git a/userland/wasm_pk_data/Cargo.lock b/userland/wasm_pk_data/Cargo.lock new file mode 100644 index 000000000..b44ca702b --- /dev/null +++ b/userland/wasm_pk_data/Cargo.lock @@ -0,0 +1,75 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "proc-macro2" +version = "1.0.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7342d5883fbccae1cc37a2353b09c87c9b0f3afd73f5fb9bba687a1f733b029" +dependencies = [ + "unicode-xid", +] + +[[package]] +name = "quote" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "864d3e96a899863136fc6e99f3d7cae289dafe43bf2c5ac19b70df7210c0a145" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "serde" +version = "1.0.136" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce31e24b01e1e524df96f1c2fdd054405f8d7376249a5110886fb4b658484789" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.136" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08597e7152fcd306f41838ed3e37be9eaeed2b61c42e2117266a554fab4662f9" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "syn" +version = "1.0.86" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a65b3f4ffa0092e9887669db0eae07941f023991ab58ea44da8fe8e2d511c6b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-xid", +] + +[[package]] +name = "toml" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31142970826733df8241ef35dc040ef98c679ab14d7c3e54d827099b3acecaa" +dependencies = [ + "serde", +] + +[[package]] +name = "unicode-xid" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" + +[[package]] +name = "wasm_pk_data" +version = "0.1.0" +dependencies = [ + "serde", + "toml", +] diff --git a/userland/wasm_pk_data/Cargo.toml b/userland/wasm_pk_data/Cargo.toml new file mode 100644 index 000000000..be3955327 --- /dev/null +++ b/userland/wasm_pk_data/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "wasm_pk_data" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +toml = "0.5" + + + + + +[dependencies.serde] +version = "1.0" +features = ["derive"] \ No newline at end of file diff --git a/userland/wasm_pk_data/assets/metadata.toml b/userland/wasm_pk_data/assets/metadata.toml new file mode 100644 index 000000000..b0d0eb1c1 --- /dev/null +++ b/userland/wasm_pk_data/assets/metadata.toml @@ -0,0 +1,3 @@ +name = "bruh" +version = [1233, 123, 123] +authors = ["John Doe", "Jane Doe"] \ No newline at end of file diff --git a/userland/wasm_pk_data/src/lib.rs b/userland/wasm_pk_data/src/lib.rs new file mode 100644 index 000000000..42adb3aef --- /dev/null +++ b/userland/wasm_pk_data/src/lib.rs @@ -0,0 +1,20 @@ +#![no_std] +extern crate alloc; +use { + alloc::{string::String, vec::Vec}, + serde::Deserialize, +}; + +#[derive(Debug, Deserialize)] +pub struct Version { + pub major: u16, + pub minor: u8, + pub patch: u8, +} + +#[derive(Debug, Deserialize)] +pub struct MetaData { + pub name: String, + pub version: Version, + pub authors: Vec, +}