1
0
Fork 0
forked from AbleOS/ableos

Merge branch 'master' into riscv

This commit is contained in:
Able 2022-03-11 14:16:15 -06:00
commit a857253314
84 changed files with 1773 additions and 1208 deletions

165
ableos/Cargo.lock generated
View file

@ -4,9 +4,9 @@ version = 3
[[package]] [[package]]
name = "ab_glyph" name = "ab_glyph"
version = "0.2.13" version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61caed9aec6daeee1ea38ccf5fb225e4f96c1eeead1b4a5c267324a63cf02326" checksum = "24606928a235e73cdef55a0c909719cadd72fce573e5713d58cb2952d8f5794c"
dependencies = [ dependencies = [
"ab_glyph_rasterizer", "ab_glyph_rasterizer",
"libm", "libm",
@ -24,7 +24,7 @@ dependencies = [
[[package]] [[package]]
name = "ableos" name = "ableos"
version = "0.1.0" version = "0.1.1"
dependencies = [ dependencies = [
"ab_glyph", "ab_glyph",
"acpi", "acpi",
@ -35,13 +35,14 @@ dependencies = [
"facepalm", "facepalm",
"genfs", "genfs",
"hashbrown 0.11.2", "hashbrown 0.11.2",
"kernel",
"lazy_static", "lazy_static",
"libwasm", "libwasm",
"linked_list_allocator", "linked_list_allocator",
"lliw", "lliw",
"log", "log",
"logos",
"pc-beeper", "pc-beeper",
"pci",
"pic8259", "pic8259",
"picorand", "picorand",
"pretty-hex", "pretty-hex",
@ -50,9 +51,9 @@ dependencies = [
"riscv", "riscv",
"rkyv", "rkyv",
"serde", "serde",
"serde_json",
"shadeable", "shadeable",
"spin 0.5.2", "spin 0.5.2",
"toml",
"uart_16550", "uart_16550",
"unicode-width", "unicode-width",
"volatile 0.2.7", "volatile 0.2.7",
@ -73,6 +74,12 @@ dependencies = [
"rsdp", "rsdp",
] ]
[[package]]
name = "ahash"
version = "0.3.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8fd72866655d1904d6b0997d0b07ba561047d070fbe29de039031c641b61217"
[[package]] [[package]]
name = "ahash" name = "ahash"
version = "0.7.6" version = "0.7.6"
@ -106,6 +113,12 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fe8f5a8a398345e52358e18ff07cc17a568fbca5c6f73873d3a62056309603" checksum = "f8fe8f5a8a398345e52358e18ff07cc17a568fbca5c6f73873d3a62056309603"
[[package]]
name = "beef"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bed554bd50246729a1ec158d08aa3235d1b69d94ad120ebe187e28894787e736"
[[package]] [[package]]
name = "bit_field" name = "bit_field"
version = "0.10.1" version = "0.10.1"
@ -120,9 +133,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]] [[package]]
name = "bootloader" name = "bootloader"
version = "0.9.21" version = "0.9.22"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a62c8f6168cd106687ee36a2b71a46c4144d73399f72814104d33094b8092fd2" checksum = "de78decc37247c7cfac5dbf3495c7298c6ac97cb355161caa7e15969c6648e6c"
[[package]] [[package]]
name = "cfg-if" name = "cfg-if"
@ -204,6 +217,12 @@ dependencies = [
"log", "log",
] ]
[[package]]
name = "fnv"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]] [[package]]
name = "genfs" name = "genfs"
version = "0.1.4" version = "0.1.4"
@ -212,15 +231,25 @@ checksum = "65b9e52a0ffd4c2f11f9f84e8885a40cb99f490971eee78bbd7ddffd6ac023d6"
[[package]] [[package]]
name = "getrandom" name = "getrandom"
version = "0.2.4" version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "418d37c8b1d42553c93648be529cb70f920d3baf8ef469b74b9638df426e0b4c" checksum = "d39cd93900197114fa1fcb7ae84ca742095eed9442088988ae74fa744e930e77"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"libc", "libc",
"wasi", "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]] [[package]]
name = "hashbrown" name = "hashbrown"
version = "0.11.2" version = "0.11.2"
@ -233,7 +262,7 @@ version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c21d40587b92fa6a6c6e3c1bdbf87d75511db5672f9c93175574b3a00df1758" checksum = "8c21d40587b92fa6a6c6e3c1bdbf87d75511db5672f9c93175574b3a00df1758"
dependencies = [ dependencies = [
"ahash", "ahash 0.7.6",
] ]
[[package]] [[package]]
@ -246,10 +275,13 @@ dependencies = [
] ]
[[package]] [[package]]
name = "itoa" name = "kernel"
version = "1.0.1" version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [
checksum = "1aab8fc367588b89dcee83ab0fd66b72b50b72fa1904d7095045ace2b0c81c35" "lazy_static",
"log",
"versioning",
]
[[package]] [[package]]
name = "lazy_static" name = "lazy_static"
@ -262,9 +294,9 @@ dependencies = [
[[package]] [[package]]
name = "libc" name = "libc"
version = "0.2.118" version = "0.2.119"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06e509672465a0504304aa87f9f176f2b2b716ed8fb105ebe5c02dc6dce96a94" checksum = "1bf2e165bb3457c8e098ea76f3e3bc9db55f87aa90d52d0e6be741470916aaa4"
[[package]] [[package]]
name = "libm" name = "libm"
@ -275,7 +307,7 @@ checksum = "33a33a362ce288760ec6a508b94caaec573ae7d3bbbd91b87aa0bad4456839db"
[[package]] [[package]]
name = "libwasm" name = "libwasm"
version = "0.1.0" 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]] [[package]]
name = "linked_list_allocator" name = "linked_list_allocator"
@ -310,6 +342,30 @@ dependencies = [
"cfg-if", "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]] [[package]]
name = "memchr" name = "memchr"
version = "2.4.1" version = "2.4.1"
@ -361,15 +417,15 @@ dependencies = [
[[package]] [[package]]
name = "once_cell" name = "once_cell"
version = "1.9.0" version = "1.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da32515d9f6e6e489d7bc9d84c71b060db7247dc035bbe44eac88cf87486d8d5" checksum = "87f3e037eac156d1775da914196f0f37741a274155e34a0b7e427c35d2a2ecb9"
[[package]] [[package]]
name = "owned_ttf_parser" name = "owned_ttf_parser"
version = "0.14.0" version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ef05f2882a8b3e7acc10c153ade2631f7bfc8ce00d2bf3fb8f4e9d2ae6ea5c3" checksum = "4fb1e509cfe7a12db2a90bfa057dfcdbc55a347f5da677c506b53dd099cfec9d"
dependencies = [ dependencies = [
"ttf-parser", "ttf-parser",
] ]
@ -388,14 +444,6 @@ dependencies = [
"x86_64", "x86_64",
] ]
[[package]]
name = "pci"
version = "0.0.1"
source = "git+https://gitlab.com/robigalia/pci#4e2fddc61825568b1d14d09fdc669389e6c43f02"
dependencies = [
"bitflags",
]
[[package]] [[package]]
name = "pic8259" name = "pic8259"
version = "0.10.2" version = "0.10.2"
@ -478,9 +526,9 @@ dependencies = [
[[package]] [[package]]
name = "regex" name = "regex"
version = "1.5.4" version = "1.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d07a8629359eb56f1e2fb1652bb04212c072a87ba68546a04065d525673ac461" checksum = "1a11647b6b25ff05a515cb92c365cec08801e83423a235b51e231e1808747286"
dependencies = [ dependencies = [
"aho-corasick", "aho-corasick",
"memchr", "memchr",
@ -499,7 +547,7 @@ version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49c94fda0280985896ed6d8bf0b43bbb5a7f0e39ccc8728ac907ddb4f06dae94" checksum = "49c94fda0280985896ed6d8bf0b43bbb5a7f0e39ccc8728ac907ddb4f06dae94"
dependencies = [ dependencies = [
"ahash", "ahash 0.7.6",
"core-error", "core-error",
"instant", "instant",
"libm", "libm",
@ -544,9 +592,9 @@ dependencies = [
[[package]] [[package]]
name = "rkyv" name = "rkyv"
version = "0.7.32" version = "0.7.35"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e3791595bf1ee951356964271bea7dafd1e1730e8be812f44a31afc38fa7bba" checksum = "2cdcf5caf69bcc87b1e3f5427b4f21a32fdd53c2847687bdf9861abb1cdaa0d8"
dependencies = [ dependencies = [
"hashbrown 0.12.0", "hashbrown 0.12.0",
"ptr_meta", "ptr_meta",
@ -556,9 +604,9 @@ dependencies = [
[[package]] [[package]]
name = "rkyv_derive" name = "rkyv_derive"
version = "0.7.32" version = "0.7.35"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca655472e721430bfb5c995a5602278e089c329cde96a0a53e1f711e3ba39c55" checksum = "a6cf557da1f81b8c7e889c59c9c3abaf6978f7feb156b9579e4f8bf6d7a2bada"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@ -580,12 +628,6 @@ dependencies = [
"log", "log",
] ]
[[package]]
name = "ryu"
version = "1.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73b4b750c782965c211b42f022f59af1fbceabdd026623714f104152f1ec149f"
[[package]] [[package]]
name = "scopeguard" name = "scopeguard"
version = "1.1.0" version = "1.1.0"
@ -618,17 +660,6 @@ dependencies = [
"syn", "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]] [[package]]
name = "shadeable" name = "shadeable"
version = "0.1.0" version = "0.1.0"
@ -646,9 +677,9 @@ checksum = "f2dd574626839106c320a323308629dcb1acfc96e32a8cba364ddc61ac23ee83"
[[package]] [[package]]
name = "smartstring" name = "smartstring"
version = "0.2.9" version = "0.2.10"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "31aa6a31c0c2b21327ce875f7e8952322acfcfd0c27569a6e18a647281352c9b" checksum = "e714dff2b33f2321fdcd475b71cec79781a692d846f37f415fb395a1d2bcd48e"
dependencies = [ dependencies = [
"static_assertions", "static_assertions",
] ]
@ -703,11 +734,20 @@ dependencies = [
"crunchy", "crunchy",
] ]
[[package]]
name = "toml"
version = "0.5.6"
source = "git+https://github.com/diondokter/toml-rs#c4161aa70202b3992dbec79b76e7a8659713b604"
dependencies = [
"hashbrown 0.7.2",
"serde",
]
[[package]] [[package]]
name = "ttf-parser" name = "ttf-parser"
version = "0.14.0" version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ccbe8381883510b6a2d8f1e32905bddd178c11caef8083086d0c0c9ab0ac281" checksum = "c74c96594835e10fa545e2a51e8709f30b173a092bfd6036ef2cec53376244f3"
[[package]] [[package]]
name = "uart_16550" name = "uart_16550"
@ -731,12 +771,23 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3"
[[package]]
name = "utf8-ranges"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4ae116fef2b7fea257ed6440d3cfcff7f190865f170cdad00bb6465bf18ecba"
[[package]] [[package]]
name = "version_check" name = "version_check"
version = "0.9.4" version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
[[package]]
name = "versioning"
version = "0.1.2"
source = "git+https://git.ablecorp.us/able/versioning#ef472283e6e7a2e395ee56434087b3a6fad53ff2"
[[package]] [[package]]
name = "volatile" name = "volatile"
version = "0.2.7" version = "0.2.7"

View file

@ -1,7 +1,7 @@
[package] [package]
edition = "2021" edition = "2021"
name = "ableos" 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 # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[profile.release] [profile.release]
@ -9,6 +9,9 @@ panic = "abort"
[package.metadata.bootimage] [package.metadata.bootimage]
run-args = [ run-args = [
"--nodefaults",
"-cpu", "-cpu",
"Broadwell-v3", "Broadwell-v3",
@ -17,27 +20,24 @@ run-args = [
"-smp", "-smp",
"cores=2", "cores=2",
# An example gpu used with ableOS
"-device",
"virtio-gpu",
# An example disk used with ableOS "-device", #"ati-vga",
"-device", "cirrus-vga",
"virtio-blk-pci,drive=drive0,id=virtblk0,num-queues=4",
# "-device",
# "virtio-blk-pci,drive=drive0,id=virtblk0,num-queues=4",
# A simple example of a boot image # A simple example of a boot image
"-drive", # "-drive",
"file=disk.qcow2,if=none,id=drive0", # "file=disk.qcow2,if=none,id=drive0",
# "-device",
# "virtio-rng",
# "-qmp",
# "unix:../qmp-sock,server,nowait"
"-device",
"virtio-rng",
"-qmp",
"unix:../qmp-sock,server,nowait"
] ]
test-args = [ test-args = [
@ -48,7 +48,10 @@ test-args = [
] ]
[dependencies] [dependencies]
linked_list_allocator = "0.9.0"
linked_list_allocator = "0.9.0"
lliw = "0.2.0" lliw = "0.2.0"
# qoi_rs = "*" # qoi_rs = "*"
spin = "0.5.2" spin = "0.5.2"
@ -65,15 +68,14 @@ genfs = "0.1.0"
# pc-beeper = "0.1.0" # pc-beeper = "0.1.0"
rhai = "1.5" 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"} libwasm = {git="https://git.ablecorp.us:443/able/libwasm.git"}
acpi = "4.1.0" acpi = "4.1.0"
[dependencies.logos]
# [dependencies.ockam] version = "0.12.0"
# version = "0.46.0" default-features = false
# no-default-features = false features = ["export_derive"]
# features = ["alloc"]
[dependencies.rdrand] [dependencies.rdrand]
@ -81,16 +83,15 @@ version = "0.8.1"
default-features = false default-features = false
[dependencies.kernel]
path = "../kernel"
[dependencies.serde] [dependencies.serde]
version = "*" version = "*"
default-features = false default-features = false
features = ["derive", "alloc"] features = ["derive", "alloc"]
[dependencies.serde_json]
version = "*"
default-features = false
features = ["alloc"]
[dependencies.hashbrown] [dependencies.hashbrown]
version = "0.11.2" version = "0.11.2"
@ -113,6 +114,15 @@ git = "https://git.ablecorp.us:443/able/y-compositor-protocol.git"
[dependencies.ext2] [dependencies.ext2]
git = "https://git.ablecorp.us:443/able/ext2-rs.git" 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] [dependencies.shadeable]
path = "../shadeable" path = "../shadeable"

12
ableos/assets/kernel.toml Normal file
View file

@ -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

View file

@ -1,7 +0,0 @@
{
"logging_level": "Trace",
"logger_padding": 10,
"run_tests": false,
"run_demos": false,
"run_shader_tests": false
}

View file

@ -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
}

View file

@ -1,4 +1,3 @@
use alloc::string::{String, ToString};
use hashbrown::HashMap; use hashbrown::HashMap;
lazy_static::lazy_static! { lazy_static::lazy_static! {

View file

@ -9,6 +9,11 @@ pub struct AAloc;
unsafe impl GlobalAlloc for AAloc { unsafe impl GlobalAlloc for AAloc {
unsafe fn alloc(&self, _layout: Layout) -> *mut u8 { unsafe fn alloc(&self, _layout: Layout) -> *mut u8 {
println!("Allocating memory");
println!("{}", _layout.size());
println!("{}", _layout.align());
null_mut() null_mut()
} }

View file

@ -8,13 +8,7 @@ pub const HEAP_MULTIPLIER: usize = 100000;
pub const HEAP_BASE: usize = 100; pub const HEAP_BASE: usize = 100;
pub const HEAP_SIZE: usize = HEAP_BASE * HEAP_MULTIPLIER; 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; use linked_list_allocator::LockedHeap;
#[global_allocator] #[global_allocator]
@ -22,5 +16,7 @@ pub static ALLOCATOR: LockedHeap = LockedHeap::empty();
#[alloc_error_handler] #[alloc_error_handler]
fn alloc_error_handler(layout: alloc::alloc::Layout) -> ! { fn alloc_error_handler(layout: alloc::alloc::Layout) -> ! {
// error!("allocation error: {:?}", layout);
panic!("allocation error: {:?}", layout) panic!("allocation error: {:?}", layout)
} }

View file

@ -1,5 +1,5 @@
use alloc::alloc::{GlobalAlloc, Layout}; use alloc::alloc::{GlobalAlloc, Layout};
// use core::alloc::{GlobalAlloc, Layout};
use crate::allocator::{HEAP_SIZE, HEAP_START}; use crate::allocator::{HEAP_SIZE, HEAP_START};
use core::ptr::null_mut; use core::ptr::null_mut;
use x86_64::{ use x86_64::{

View file

@ -2,19 +2,19 @@ use lazy_static::lazy_static;
use spin::Mutex; use spin::Mutex;
use uart_16550::SerialPort; use uart_16550::SerialPort;
lazy_static! { lazy_static! {
pub static ref SERIAL1: Mutex<SerialPort> = { pub static ref SERIAL1: Mutex<SerialPort> = {
let mut serial_port = unsafe { SerialPort::new(0x3F8) }; let mut serial_port = unsafe { SerialPort::new(0x3F8) };
serial_port.init(); serial_port.init();
Mutex::new(serial_port) Mutex::new(serial_port)
}; };
} }
#[doc(hidden)] #[doc(hidden)]
pub fn _print(args: ::core::fmt::Arguments) { pub fn _print(args: ::core::fmt::Arguments) {
use core::fmt::Write; use core::fmt::Write;
SERIAL1 SERIAL1
.lock() .lock()
.write_fmt(args) .write_fmt(args)
.expect("Printing to serial failed"); .expect("Printing to serial failed");
} }
/// Prints to the host through the serial interface. /// Prints to the host through the serial interface.
#[macro_export] #[macro_export]

View file

@ -5,6 +5,12 @@ use super::{gdt, interrupts};
/// x86_64 initialization /// x86_64 initialization
pub fn init() { 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(); let result = logger::init();
match result { match result {
Ok(_) => {} Ok(_) => {}

View file

@ -1,9 +1,11 @@
use crate::{ use crate::{
arch::{drivers::vga::WRITER, gdt}, arch::{drivers::vga::WRITER, gdt},
kernel_state::KERNEL_STATE, kernel_state::KERNEL_STATE,
print, println, KEYBUFF, print, println,
rhai_shell::KEYBUFF,
}; };
use cpuio::outb;
use lazy_static::lazy_static; use lazy_static::lazy_static;
use pic8259::ChainedPics; use pic8259::ChainedPics;
use spin; use spin;
@ -19,6 +21,8 @@ pub static PICS: spin::Mutex<ChainedPics> =
pub enum InterruptIndex { pub enum InterruptIndex {
Timer = PIC_1_OFFSET, Timer = PIC_1_OFFSET,
Keyboard, Keyboard,
// SecondInterrupt = PIC_2_OFFSET,
Cmos = 0x70,
} }
impl InterruptIndex { impl InterruptIndex {
fn as_u8(self) -> u8 { fn as_u8(self) -> u8 {
@ -37,10 +41,18 @@ lazy_static! {
idt.breakpoint.set_handler_fn(breakpoint_handler); idt.breakpoint.set_handler_fn(breakpoint_handler);
unsafe { unsafe {
idt.double_fault.set_handler_fn(double_fault_handler) 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::Timer.as_usize()].set_handler_fn(timer_interrupt_handler);
idt[InterruptIndex::Keyboard.as_usize()] .set_handler_fn(keyboard_interrupt_handler); idt[InterruptIndex::Keyboard.as_usize()] .set_handler_fn(keyboard_interrupt_handler);
idt[6].set_handler_fn(floppy_disk_interrupt_handler);
idt idt
}; };
} }
@ -55,7 +67,7 @@ extern "x86-interrupt" fn double_fault_handler(
panic!("EXCEPTION: DOUBLE FAULT\n{:#?}", stack_frame); panic!("EXCEPTION: DOUBLE FAULT\n{:#?}", stack_frame);
} }
extern "x86-interrupt" fn timer_interrupt_handler(_stack_frame: InterruptStackFrame) { extern "x86-interrupt" fn timer_interrupt_handler(_stack_frame: InterruptStackFrame) {
crate::kmain::tick(); kernel::tick();
unsafe { unsafe {
PICS.lock() PICS.lock()
.notify_end_of_interrupt(InterruptIndex::Timer.as_u8()); .notify_end_of_interrupt(InterruptIndex::Timer.as_u8());
@ -90,6 +102,7 @@ extern "x86-interrupt" fn keyboard_interrupt_handler(_stack_frame: InterruptStac
// Backspace // Backspace
8 => { 8 => {
WRITER.lock().backspace(); WRITER.lock().backspace();
KEYBUFF.lock().push(8_u8 as _);
// print!(" "); // print!(" ");
// WRITER.lock().backspace(); // WRITER.lock().backspace();
} }
@ -126,16 +139,17 @@ extern "x86-interrupt" fn keyboard_interrupt_handler(_stack_frame: InterruptStac
} }
} }
/* extern "x86-interrupt" fn floppy_disk_interrupt_handler(_stack_frame: InterruptStackFrame) {
extern "x86-interrupt" fn page_fault_handler( println!("EXCEPTION: FLOPPY DISK");
stack_frame: InterruptStackFrame, }
error_code: PageFaultErrorCode,
) { fn set_pit_frequency(freq: u32) {
use x86_64::registers::control::Cr2; let divisor: u16 = (1193180 / freq).try_into().unwrap();
println!["Exception: Page Fault"];
println!["Address: {:?}", Cr2::read()]; unsafe {
println!["Error Code: {:?}", error_code]; outb(0x36, 0x43);
println!["{:#?}", stack_frame];
sloop(); outb((divisor & 0xFF) as u8, 0x40);
outb((divisor >> 8) as u8, 0x40);
}
} }
*/

View file

@ -1,112 +1,112 @@
use bootloader::bootinfo::{MemoryMap, MemoryRegionType}; use bootloader::bootinfo::{MemoryMap, MemoryRegionType};
use x86_64::{ use x86_64::{
structures::paging::{ structures::paging::{
FrameAllocator, Mapper, OffsetPageTable, Page, PageTable, PhysFrame, Size4KiB, FrameAllocator, Mapper, OffsetPageTable, Page, PageTable, PhysFrame, Size4KiB,
}, },
PhysAddr, VirtAddr, PhysAddr, VirtAddr,
}; };
pub unsafe fn init(physical_memory_offset: VirtAddr) -> OffsetPageTable<'static> { pub unsafe fn init(physical_memory_offset: VirtAddr) -> OffsetPageTable<'static> {
let level_4_table = active_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) OffsetPageTable::new(level_4_table, physical_memory_offset)
} }
unsafe fn active_level_4_table(physical_memory_offset: VirtAddr) -> &'static mut PageTable { 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 phys = level_4_table_frame.start_address();
let virt = physical_memory_offset + phys.as_u64(); let virt = physical_memory_offset + phys.as_u64();
let page_table_ptr: *mut PageTable = virt.as_mut_ptr(); let page_table_ptr: *mut PageTable = virt.as_mut_ptr();
// THIS IS UNSAFE // THIS IS UNSAFE
&mut *page_table_ptr &mut *page_table_ptr
} }
fn translate_addr_inner(addr: VirtAddr, physical_memory_offset: VirtAddr) -> Option<PhysAddr> { fn translate_addr_inner(addr: VirtAddr, physical_memory_offset: VirtAddr) -> Option<PhysAddr> {
use x86_64::registers::control::Cr3; use x86_64::registers::control::Cr3;
use x86_64::structures::paging::page_table::FrameError; 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 = [ let table_indexes = [
addr.p4_index(), addr.p4_index(),
addr.p3_index(), addr.p3_index(),
addr.p2_index(), addr.p2_index(),
addr.p1_index(), addr.p1_index(),
]; ];
let mut frame = level_4_table_frame; let mut frame = level_4_table_frame;
for &index in &table_indexes { for &index in &table_indexes {
// convert the frame into a page table reference // convert the frame into a page table reference
let virt = physical_memory_offset + frame.start_address().as_u64(); let virt = physical_memory_offset + frame.start_address().as_u64();
let table_ptr: *const PageTable = virt.as_ptr(); let table_ptr: *const PageTable = virt.as_ptr();
let table = unsafe { &*table_ptr }; let table = unsafe { &*table_ptr };
let entry = &table[index]; let entry = &table[index];
frame = match entry.frame() { frame = match entry.frame() {
Ok(frame) => frame, Ok(frame) => frame,
Err(FrameError::FrameNotPresent) => return None, Err(FrameError::FrameNotPresent) => return None,
Err(FrameError::HugeFrame) => panic!["huge pages not supported"], 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<PhysAddr> { pub unsafe fn translate_addr(addr: VirtAddr, physical_memory_offset: VirtAddr) -> Option<PhysAddr> {
translate_addr_inner(addr, physical_memory_offset) translate_addr_inner(addr, physical_memory_offset)
} }
pub fn create_example_mapping( pub fn create_example_mapping(
page: Page, page: Page,
mapper: &mut OffsetPageTable, mapper: &mut OffsetPageTable,
frame_allocator: &mut impl FrameAllocator<Size4KiB>, frame_allocator: &mut impl FrameAllocator<Size4KiB>,
) { ) {
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 frame = PhysFrame::containing_address(PhysAddr::new(0xb8000));
let flags = Flags::PRESENT | Flags::WRITABLE; let flags = Flags::PRESENT | Flags::WRITABLE;
let map_to_result = unsafe { mapper.map_to(page, frame, flags, frame_allocator) }; let map_to_result = unsafe { mapper.map_to(page, frame, flags, frame_allocator) };
map_to_result.expect("map_to failed").flush(); map_to_result.expect("map_to failed").flush();
} }
pub struct EmptyFrameAllocator; pub struct EmptyFrameAllocator;
unsafe impl FrameAllocator<Size4KiB> for EmptyFrameAllocator { unsafe impl FrameAllocator<Size4KiB> for EmptyFrameAllocator {
fn allocate_frame(&mut self) -> Option<PhysFrame<Size4KiB>> { fn allocate_frame(&mut self) -> Option<PhysFrame<Size4KiB>> {
None None
} }
} }
pub struct BootInfoFrameAllocator { pub struct BootInfoFrameAllocator {
memory_map: &'static MemoryMap, memory_map: &'static MemoryMap,
next: usize, next: usize,
} }
impl BootInfoFrameAllocator { impl BootInfoFrameAllocator {
pub unsafe fn init(memory_map: &'static MemoryMap) -> Self { pub unsafe fn init(memory_map: &'static MemoryMap) -> Self {
Self { Self {
memory_map, memory_map,
next: 0, next: 0,
} }
} }
fn usable_frames(&self) -> impl Iterator<Item = PhysFrame> { fn usable_frames(&self) -> impl Iterator<Item = PhysFrame> {
let regions = self.memory_map.iter(); let regions = self.memory_map.iter();
let usable_regions = regions.filter(|r| r.region_type == MemoryRegionType::Usable); 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 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)); let frame_address = addr_range.flat_map(|r| r.step_by(4096));
frame_address.map(|addr| PhysFrame::containing_address(PhysAddr::new(addr))) frame_address.map(|addr| PhysFrame::containing_address(PhysAddr::new(addr)))
} }
} }
unsafe impl FrameAllocator<Size4KiB> for BootInfoFrameAllocator { unsafe impl FrameAllocator<Size4KiB> for BootInfoFrameAllocator {
fn allocate_frame(&mut self) -> Option<PhysFrame<Size4KiB>> { fn allocate_frame(&mut self) -> Option<PhysFrame<Size4KiB>> {
let frame = self.usable_frames().nth(self.next); let frame = self.usable_frames().nth(self.next);
self.next += 1; self.next += 1;
frame frame
} }
} }

View file

@ -1,5 +1,4 @@
use log::LevelFilter; use log::LevelFilter;
// use rkyv::{Deserialize, Serialize};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[derive(Serialize, Debug, Deserialize)] #[derive(Serialize, Debug, Deserialize)]
@ -19,29 +18,21 @@ pub enum LogLevel {
} }
#[derive(Serialize, Debug, Deserialize)] #[derive(Serialize, Debug, Deserialize)]
pub struct BootConfig { pub struct KernelConfig {
pub logging_level: LogLevel, pub boot: BootConfig,
pub logger_padding: usize, pub logging: LoggingConfig,
pub run_tests: bool, pub tests: TestsConfig,
pub run_demos: bool,
pub run_shader_tests: bool,
} }
impl BootConfig { impl KernelConfig {
pub fn new() -> Self { pub fn new() -> Self {
let data = include_str!("../assets/kernel_config.json"); let p: KernelConfig = toml::from_str(include_str!("../assets/kernel.toml")).unwrap();
// 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);
p p
} }
pub fn log_level(&self) -> LevelFilter { pub fn log_level(&self) -> LevelFilter {
use LevelFilter::*; use LevelFilter::*;
match self.logging_level { match self.logging.level {
LogLevel::Off => Off, LogLevel::Off => Off,
LogLevel::Error => Error, LogLevel::Error => Error,
LogLevel::Warn => Warn, 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<String>,
}

View file

@ -1,6 +1,4 @@
use alloc::string::String; use kernel::device_interface::character::CharacterDevice;
use crate::character_device::CharacterDevice;
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@ -22,4 +20,12 @@ impl CharacterDevice for DevNull {
fn write_char(&mut self, _: char) -> bool { fn write_char(&mut self, _: char) -> bool {
true true
} }
fn reset(&mut self) {
todo!()
}
fn initialize(&mut self) -> bool {
todo!()
}
} }

View file

@ -1,4 +1,4 @@
use crate::character_device::CharacterDevice; use kernel::device_interface::character::CharacterDevice;
#[derive(Debug)] #[derive(Debug)]
pub struct DevUnicode { pub struct DevUnicode {
@ -29,6 +29,15 @@ impl CharacterDevice for DevUnicode {
true 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 { fn add1_char(c: char) -> char {

View file

@ -1,4 +1,4 @@
use crate::character_device::CharacterDevice; use kernel::device_interface::character::CharacterDevice;
#[derive(Debug)] #[derive(Debug)]
pub struct DevZero; pub struct DevZero;
@ -19,4 +19,10 @@ impl CharacterDevice for DevZero {
fn write_char(&mut self, _: char) -> bool { fn write_char(&mut self, _: char) -> bool {
true true
} }
fn reset(&mut self) {}
fn initialize(&mut self) -> bool {
true
}
} }

View file

@ -1,3 +1,5 @@
pub mod dev_null; pub mod dev_null;
pub mod dev_unicode; pub mod dev_unicode;
pub mod dev_zero; pub mod dev_zero;
pub use kernel::device_interface::character::CharacterDevice;

15
ableos/src/devices/id.rs Normal file
View file

@ -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,
}
}

View file

@ -1,20 +1,15 @@
pub mod character_devs; pub mod character_devs;
pub mod id;
pub mod pci_inner; pub mod pci_inner;
use alloc::{
boxed::Box,
string::{String, ToString},
};
use hashbrown::HashMap; 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. // FIXME: This is a hack to hold a device.
// #[derive(Debug)] // #[derive(Debug)]
pub enum Device { pub enum Device {
Character(Box<dyn CharacterDevice>), Character(Box<dyn CharacterDevice>),
Pci(PCIDevice),
} }
unsafe impl Sync for Device {} unsafe impl Sync for Device {}
unsafe impl Send for Device {} unsafe impl Send for Device {}

View file

@ -1,56 +1,55 @@
//! map the DeviceClass via <https://pci-ids.ucw.cz/read/PD> //! map the DeviceClass via <https://pci-ids.ucw.cz/read/PD>
#[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, #[allow(dead_code)]
GenericSystemPeripheral = 0x08, fn scan_pci_bus() {}
InputDevice = 0x09,
DockingStation = 0x0a,
Processor = 0x0b,
SerialBusController = 0x0c,
WirelessController = 0x0d,
IntelligentController = 0x0e,
SatelliteCommunicationController = 0x0f,
EncryptionController = 0x10,
SignalProcessingController = 0x11,
// 14 pub enum Vendors {
// 15 ThreeDfxInteractiveInc = 0x121a,
// 16 ThreeDLabs = 0x3d3d,
Coprocessor = 40, AllianceSemiconductorCorp = 0x1142,
// 64 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 struct PciDevice {
pub fn from_u8(val: u8) -> DeviceClass { pub vendor: Vendors,
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,
}
}
} }

View file

@ -1,4 +1,2 @@
pub mod graphics; pub mod graphics;
pub mod serial; pub mod serial;
pub mod character_device;

View file

@ -1,5 +1,3 @@
/*
// TODO improve tokenizer/parser // TODO improve tokenizer/parser
pub fn colorify(eval: &str) { pub fn colorify(eval: &str) {
let y = eval.split("$"); 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,
*/ #[regex("[a-zA-Z!@#$%^&*\">()\n ]+", parse_text, priority = 2)]
pub fn colorify(eval: &str) {} 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<Token>) -> Option<String> {
let slice = lex.slice();
Some(String::from(slice))
}

View file

@ -1,7 +1,5 @@
use core::time::Duration; use core::time::Duration;
use alloc::vec::Vec;
// pub struct Duration {} // pub struct Duration {}
pub struct AtomicU32(u32); pub struct AtomicU32(u32);

View file

@ -1,4 +1,3 @@
#![feature(asm)]
#![cfg_attr( #![cfg_attr(
not(any(target_arch = "x86_64", target_arch = "x86")), not(any(target_arch = "x86_64", target_arch = "x86")),
allow(dead_code) allow(dead_code)

View file

@ -1,34 +1,34 @@
// Can be standardized // Can be standardized
// NOTE: Move this to relib // NOTE: Move this to relib
pub struct SemanticVersion { pub struct SemanticVersion {
pub major: u8, pub major: u8,
pub minor: u8, pub minor: u8,
pub patch: u8, pub patch: u8,
} }
impl core::fmt::Display for SemanticVersion { impl core::fmt::Display for SemanticVersion {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
write!(f, "v{}.{}.{}", self.major, self.minor, self.patch) write!(f, "v{}.{}.{}", self.major, self.minor, self.patch)
} }
} }
// NOTE: Move to somewhere else // NOTE: Move to somewhere else
lazy_static! { lazy_static! {
pub static ref KINFO: KernelInfo = KernelInfo { pub static ref KINFO: KernelInfo = KernelInfo {
kernel_version: SemanticVersion { kernel_version: SemanticVersion {
major: 0, major: 0,
minor: 0, minor: 0,
patch: 0, patch: 0,
}, },
memory: SystemMemory { used: 0, total: 0 } memory: SystemMemory { used: 0, total: 0 }
}; };
} }
/// simple info you would want to know in a neofetch like program /// simple info you would want to know in a neofetch like program
pub struct KernelInfo { pub struct KernelInfo {
// os: String, // os: String,
// host: String, // host: String,
pub kernel_version: SemanticVersion, pub kernel_version: SemanticVersion,
// cpu: String, // cpu: String,
// gpu: String, // gpu: String,
pub memory: SystemMemory, pub memory: SystemMemory,
} }
use super::systeminfo::SystemMemory; use super::systeminfo::SystemMemory;
use lazy_static::lazy_static; use lazy_static::lazy_static;

View file

@ -1,10 +1,10 @@
pub trait Server { pub trait Server {
/// Initialize the server and return a number /// Initialize the server and return a number
fn initialize() -> u32; fn initialize() -> u32;
/// kill the server /// kill the server
fn kill() -> bool; fn kill() -> bool;
// put data in the servers outbox // put data in the servers outbox
fn send(); fn send();
// put data in the servers inbox and notify it // put data in the servers inbox and notify it
fn recieve(); fn recieve();
} }

View file

@ -1,3 +1,3 @@
//! //!
pub mod compositor;
pub mod window; pub mod window;
pub mod compositor;

View file

@ -1,8 +1,5 @@
use crate::driver_traits::graphics::Point; use crate::driver_traits::graphics::Point;
use alloc::string::String;
use alloc::vec::Vec;
pub struct MenuOption { pub struct MenuOption {
symbol: char, symbol: char,
} }

View file

@ -1,13 +1,10 @@
use { use ext2::{
alloc::{format, string::String, vec::Vec}, fs::{
ext2::{ sync::{Inode, Synced},
fs::{ Ext2,
sync::{Inode, Synced},
Ext2,
},
sector::{SectorSize, Size1024},
volume::Volume,
}, },
sector::{SectorSize, Size1024},
volume::Volume,
}; };
fn load_fs() -> Synced<Ext2<Size1024, Vec<u8>>> { fn load_fs() -> Synced<Ext2<Size1024, Vec<u8>>> {

View file

@ -1,6 +1,6 @@
// use crate::vga_e::VGAE; // use crate::vga_e::VGAE;
use ab_glyph::{Font, FontRef, Glyph}; use ab_glyph::{Font, FontRef, Glyph};
use alloc::{boxed::Box, vec, vec::Vec};
use shadeable::{evaluate_shader, pixel_format::Rgba64}; use shadeable::{evaluate_shader, pixel_format::Rgba64};
use spin; use spin;
// use vga::{colors::Color16, writers::GraphicsWriter}; // use vga::{colors::Color16, writers::GraphicsWriter};
@ -126,8 +126,7 @@ impl ScreenBuffer {
// TODO force clear // TODO force clear
pub fn force_redraw(&mut self) { 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 /// Draw a glyph on the screen at the given position

View file

@ -1,4 +1,3 @@
use alloc::string::{String, ToString};
use lazy_static::lazy_static; use lazy_static::lazy_static;
lazy_static! { lazy_static! {
@ -7,7 +6,7 @@ lazy_static! {
} }
pub struct KernelInternalState { pub struct KernelInternalState {
hostname: String, pub hostname: String,
should_shutdown: bool, should_shutdown: bool,
} }

View file

@ -1,16 +1,16 @@
use crate::{ 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. // Do not edit this file directly. Instead, create a `Keyboard` and modify that.
pub struct CustomLayout { pub struct CustomLayout {
mapping: [LayoutEntry; 256], mapping: [LayoutEntry; 256],
} }
impl Default for CustomLayout { impl Default for CustomLayout {
fn default() -> Self { fn default() -> Self {
Self::new_us104key() Self::new_us104key()
} }
} }
#[rustfmt::skip] #[rustfmt::skip]
impl CustomLayout { impl CustomLayout {
@ -101,76 +101,76 @@ impl CustomLayout {
} }
} }
impl KeyboardLayout for CustomLayout { impl KeyboardLayout for CustomLayout {
fn map_keycode( fn map_keycode(
&self, &self,
keycode: KeyCode, keycode: KeyCode,
modifiers: &Modifiers, modifiers: &Modifiers,
handle_ctrl: HandleControl, handle_ctrl: HandleControl,
) -> DecodedKey { ) -> DecodedKey {
let map_to_unicode = handle_ctrl == HandleControl::MapLettersToUnicode; let map_to_unicode = handle_ctrl == HandleControl::MapLettersToUnicode;
let spot = &self.mapping[keycode as usize]; let spot = &self.mapping[keycode as usize];
if let Some(k) = if map_to_unicode && modifiers.is_ctrl() { if let Some(k) = if map_to_unicode && modifiers.is_ctrl() {
match spot.kind { match spot.kind {
LayoutEntryKind::Regular => spot.raw_unicode, LayoutEntryKind::Regular => spot.raw_unicode,
LayoutEntryKind::Numlockable => None, LayoutEntryKind::Numlockable => None,
LayoutEntryKind::Capslockable => spot.raw_unicode, 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
}
} }
LayoutEntryKind::Capslockable => { } else if modifiers.alt_gr {
if modifiers.is_caps() { match spot.kind {
spot.locked_shifted LayoutEntryKind::Regular => spot.altgr,
} else { LayoutEntryKind::Numlockable => None,
spot.shifted LayoutEntryKind::Capslockable => spot.altgr,
}
} }
} } else if modifiers.is_shifted() {
} else { match spot.kind {
match spot.kind { LayoutEntryKind::Regular => spot.shifted,
LayoutEntryKind::Regular => spot.unshifted, LayoutEntryKind::Numlockable => {
LayoutEntryKind::Numlockable => { if modifiers.numlock {
if modifiers.numlock { spot.locked_shifted
spot.locked } else {
} else { spot.shifted
spot.unshifted }
} }
LayoutEntryKind::Capslockable => {
if modifiers.is_caps() {
spot.locked_shifted
} else {
spot.shifted
}
}
} }
LayoutEntryKind::Capslockable => { } else {
if modifiers.is_caps() { match spot.kind {
spot.locked LayoutEntryKind::Regular => spot.unshifted,
} else { LayoutEntryKind::Numlockable => {
spot.unshifted if modifiers.numlock {
} spot.locked
} else {
spot.unshifted
}
}
LayoutEntryKind::Capslockable => {
if modifiers.is_caps() {
spot.locked
} else {
spot.unshifted
}
}
} }
} } {
} { k
k } else {
} else { DecodedKey::RawKey(keycode as u8)
DecodedKey::RawKey(keycode as u8) }
} }
}
} }
// Note(elfein) Not super hard to get right, but still- DO NOT TOUCH // Note(elfein) Not super hard to get right, but still- DO NOT TOUCH
impl CustomLayout { impl CustomLayout {
// See how hard this is to get right? // See how hard this is to get right?
// See the complexity of all the methods? // See the complexity of all the methods?
// Yeah- if you don't know what you're doing, ask before you touch! // Yeah- if you don't know what you're doing, ask before you touch!
pub fn set(&mut self, pos: KeyCode, entry: LayoutEntry) { pub fn set(&mut self, pos: KeyCode, entry: LayoutEntry) {
self.mapping[pos as usize] = entry; self.mapping[pos as usize] = entry;
} }
} }

View file

@ -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 { pub struct CustomScancodeSet {
single_byte: [Option<KeyCode>; 256], single_byte: [Option<KeyCode>; 256],
extended: [Option<KeyCode>; 256], extended: [Option<KeyCode>; 256],
} }
impl Default for CustomScancodeSet { impl Default for CustomScancodeSet {
fn default() -> Self { fn default() -> Self {
Self::scancode_set1() Self::scancode_set1()
} }
} }
impl CustomScancodeSet { impl CustomScancodeSet {
pub fn scancode_set1() -> Self { pub fn scancode_set1() -> Self {
let mut scancode_set = Self { let mut scancode_set = Self {
single_byte: [None; 256], single_byte: [None; 256],
extended: [None; 256], extended: [None; 256],
}; };
scancode_set.single_byte[0x01] = Some(KeyCode::Escape); // 01 scancode_set.single_byte[0x01] = Some(KeyCode::Escape); // 01
scancode_set.single_byte[0x02] = Some(KeyCode::Key1); // 02 scancode_set.single_byte[0x02] = Some(KeyCode::Key1); // 02
scancode_set.single_byte[0x03] = Some(KeyCode::Key2); // 03 scancode_set.single_byte[0x03] = Some(KeyCode::Key2); // 03
scancode_set.single_byte[0x04] = Some(KeyCode::Key3); // 04 scancode_set.single_byte[0x04] = Some(KeyCode::Key3); // 04
scancode_set.single_byte[0x05] = Some(KeyCode::Key4); // 05 scancode_set.single_byte[0x05] = Some(KeyCode::Key4); // 05
scancode_set.single_byte[0x06] = Some(KeyCode::Key5); // 06 scancode_set.single_byte[0x06] = Some(KeyCode::Key5); // 06
scancode_set.single_byte[0x07] = Some(KeyCode::Key6); // 07 scancode_set.single_byte[0x07] = Some(KeyCode::Key6); // 07
scancode_set.single_byte[0x08] = Some(KeyCode::Key7); // 08 scancode_set.single_byte[0x08] = Some(KeyCode::Key7); // 08
scancode_set.single_byte[0x09] = Some(KeyCode::Key8); // 09 scancode_set.single_byte[0x09] = Some(KeyCode::Key8); // 09
scancode_set.single_byte[0x0A] = Some(KeyCode::Key9); // 0A scancode_set.single_byte[0x0A] = Some(KeyCode::Key9); // 0A
scancode_set.single_byte[0x0B] = Some(KeyCode::Key0); // 0B scancode_set.single_byte[0x0B] = Some(KeyCode::Key0); // 0B
scancode_set.single_byte[0x0C] = Some(KeyCode::Minus); // 0C scancode_set.single_byte[0x0C] = Some(KeyCode::Minus); // 0C
scancode_set.single_byte[0x0D] = Some(KeyCode::Equals); // 0D scancode_set.single_byte[0x0D] = Some(KeyCode::Equals); // 0D
scancode_set.single_byte[0x0E] = Some(KeyCode::Backspace); // 0E scancode_set.single_byte[0x0E] = Some(KeyCode::Backspace); // 0E
scancode_set.single_byte[0x0F] = Some(KeyCode::Tab); // 0F scancode_set.single_byte[0x0F] = Some(KeyCode::Tab); // 0F
scancode_set.single_byte[0x10] = Some(KeyCode::Q); // 10 scancode_set.single_byte[0x10] = Some(KeyCode::Q); // 10
scancode_set.single_byte[0x11] = Some(KeyCode::W); // 11 scancode_set.single_byte[0x11] = Some(KeyCode::W); // 11
scancode_set.single_byte[0x12] = Some(KeyCode::E); // 12 scancode_set.single_byte[0x12] = Some(KeyCode::E); // 12
scancode_set.single_byte[0x13] = Some(KeyCode::R); // 13 scancode_set.single_byte[0x13] = Some(KeyCode::R); // 13
scancode_set.single_byte[0x14] = Some(KeyCode::T); // 14 scancode_set.single_byte[0x14] = Some(KeyCode::T); // 14
scancode_set.single_byte[0x15] = Some(KeyCode::Y); // 15 scancode_set.single_byte[0x15] = Some(KeyCode::Y); // 15
scancode_set.single_byte[0x16] = Some(KeyCode::U); // 16 scancode_set.single_byte[0x16] = Some(KeyCode::U); // 16
scancode_set.single_byte[0x17] = Some(KeyCode::I); // 17 scancode_set.single_byte[0x17] = Some(KeyCode::I); // 17
scancode_set.single_byte[0x18] = Some(KeyCode::O); // 18 scancode_set.single_byte[0x18] = Some(KeyCode::O); // 18
scancode_set.single_byte[0x19] = Some(KeyCode::P); // 19 scancode_set.single_byte[0x19] = Some(KeyCode::P); // 19
scancode_set.single_byte[0x1A] = Some(KeyCode::BracketSquareLeft); // 1A scancode_set.single_byte[0x1A] = Some(KeyCode::BracketSquareLeft); // 1A
scancode_set.single_byte[0x1B] = Some(KeyCode::BracketSquareRight); // 1B scancode_set.single_byte[0x1B] = Some(KeyCode::BracketSquareRight); // 1B
scancode_set.single_byte[0x1C] = Some(KeyCode::Enter); // 1C scancode_set.single_byte[0x1C] = Some(KeyCode::Enter); // 1C
scancode_set.single_byte[0x1D] = Some(KeyCode::ControlLeft); // 1D scancode_set.single_byte[0x1D] = Some(KeyCode::ControlLeft); // 1D
scancode_set.single_byte[0x1E] = Some(KeyCode::A); // 1E scancode_set.single_byte[0x1E] = Some(KeyCode::A); // 1E
scancode_set.single_byte[0x1F] = Some(KeyCode::S); // 1F scancode_set.single_byte[0x1F] = Some(KeyCode::S); // 1F
scancode_set.single_byte[0x20] = Some(KeyCode::D); // 20 scancode_set.single_byte[0x20] = Some(KeyCode::D); // 20
scancode_set.single_byte[0x21] = Some(KeyCode::F); // 21 scancode_set.single_byte[0x21] = Some(KeyCode::F); // 21
scancode_set.single_byte[0x22] = Some(KeyCode::G); // 22 scancode_set.single_byte[0x22] = Some(KeyCode::G); // 22
scancode_set.single_byte[0x23] = Some(KeyCode::H); // 23 scancode_set.single_byte[0x23] = Some(KeyCode::H); // 23
scancode_set.single_byte[0x24] = Some(KeyCode::J); // 24 scancode_set.single_byte[0x24] = Some(KeyCode::J); // 24
scancode_set.single_byte[0x25] = Some(KeyCode::K); // 25 scancode_set.single_byte[0x25] = Some(KeyCode::K); // 25
scancode_set.single_byte[0x26] = Some(KeyCode::L); // 26 scancode_set.single_byte[0x26] = Some(KeyCode::L); // 26
scancode_set.single_byte[0x27] = Some(KeyCode::SemiColon); // 27 scancode_set.single_byte[0x27] = Some(KeyCode::SemiColon); // 27
scancode_set.single_byte[0x28] = Some(KeyCode::Quote); // 28 scancode_set.single_byte[0x28] = Some(KeyCode::Quote); // 28
scancode_set.single_byte[0x29] = Some(KeyCode::BackTick); // 29 scancode_set.single_byte[0x29] = Some(KeyCode::BackTick); // 29
scancode_set.single_byte[0x2A] = Some(KeyCode::ShiftLeft); // 2A scancode_set.single_byte[0x2A] = Some(KeyCode::ShiftLeft); // 2A
scancode_set.single_byte[0x2B] = Some(KeyCode::BackSlash); // 2B scancode_set.single_byte[0x2B] = Some(KeyCode::BackSlash); // 2B
scancode_set.single_byte[0x2C] = Some(KeyCode::Z); // 2C scancode_set.single_byte[0x2C] = Some(KeyCode::Z); // 2C
scancode_set.single_byte[0x2D] = Some(KeyCode::X); // 2D scancode_set.single_byte[0x2D] = Some(KeyCode::X); // 2D
scancode_set.single_byte[0x2E] = Some(KeyCode::C); // 2E scancode_set.single_byte[0x2E] = Some(KeyCode::C); // 2E
scancode_set.single_byte[0x2F] = Some(KeyCode::V); // 2F scancode_set.single_byte[0x2F] = Some(KeyCode::V); // 2F
scancode_set.single_byte[0x30] = Some(KeyCode::B); // 30 scancode_set.single_byte[0x30] = Some(KeyCode::B); // 30
scancode_set.single_byte[0x31] = Some(KeyCode::N); // 31 scancode_set.single_byte[0x31] = Some(KeyCode::N); // 31
scancode_set.single_byte[0x32] = Some(KeyCode::M); // 32 scancode_set.single_byte[0x32] = Some(KeyCode::M); // 32
scancode_set.single_byte[0x33] = Some(KeyCode::Comma); // 33 scancode_set.single_byte[0x33] = Some(KeyCode::Comma); // 33
scancode_set.single_byte[0x34] = Some(KeyCode::Fullstop); // 34 scancode_set.single_byte[0x34] = Some(KeyCode::Fullstop); // 34
scancode_set.single_byte[0x35] = Some(KeyCode::Slash); // 35 scancode_set.single_byte[0x35] = Some(KeyCode::Slash); // 35
scancode_set.single_byte[0x36] = Some(KeyCode::ShiftRight); // 36 scancode_set.single_byte[0x36] = Some(KeyCode::ShiftRight); // 36
scancode_set.single_byte[0x37] = Some(KeyCode::NumpadStar); // 37 scancode_set.single_byte[0x37] = Some(KeyCode::NumpadStar); // 37
scancode_set.single_byte[0x38] = Some(KeyCode::AltLeft); // 38 scancode_set.single_byte[0x38] = Some(KeyCode::AltLeft); // 38
scancode_set.single_byte[0x39] = Some(KeyCode::Spacebar); // 39 scancode_set.single_byte[0x39] = Some(KeyCode::Spacebar); // 39
scancode_set.single_byte[0x3A] = Some(KeyCode::CapsLock); // 3A scancode_set.single_byte[0x3A] = Some(KeyCode::CapsLock); // 3A
scancode_set.single_byte[0x3B] = Some(KeyCode::F1); // 3B scancode_set.single_byte[0x3B] = Some(KeyCode::F1); // 3B
scancode_set.single_byte[0x3C] = Some(KeyCode::F2); // 3C scancode_set.single_byte[0x3C] = Some(KeyCode::F2); // 3C
scancode_set.single_byte[0x3D] = Some(KeyCode::F3); // 3D scancode_set.single_byte[0x3D] = Some(KeyCode::F3); // 3D
scancode_set.single_byte[0x3E] = Some(KeyCode::F4); // 3E scancode_set.single_byte[0x3E] = Some(KeyCode::F4); // 3E
scancode_set.single_byte[0x3F] = Some(KeyCode::F5); // 3F scancode_set.single_byte[0x3F] = Some(KeyCode::F5); // 3F
scancode_set.single_byte[0x40] = Some(KeyCode::F6); // 40 scancode_set.single_byte[0x40] = Some(KeyCode::F6); // 40
scancode_set.single_byte[0x41] = Some(KeyCode::F7); // 41 scancode_set.single_byte[0x41] = Some(KeyCode::F7); // 41
scancode_set.single_byte[0x42] = Some(KeyCode::F8); // 42 scancode_set.single_byte[0x42] = Some(KeyCode::F8); // 42
scancode_set.single_byte[0x43] = Some(KeyCode::F9); // 43 scancode_set.single_byte[0x43] = Some(KeyCode::F9); // 43
scancode_set.single_byte[0x44] = Some(KeyCode::F10); // 44 scancode_set.single_byte[0x44] = Some(KeyCode::F10); // 44
scancode_set.single_byte[0x45] = Some(KeyCode::NumpadLock); // 45 scancode_set.single_byte[0x45] = Some(KeyCode::NumpadLock); // 45
scancode_set.single_byte[0x46] = Some(KeyCode::ScrollLock); // 46 scancode_set.single_byte[0x46] = Some(KeyCode::ScrollLock); // 46
scancode_set.single_byte[0x47] = Some(KeyCode::Numpad7); // 47 scancode_set.single_byte[0x47] = Some(KeyCode::Numpad7); // 47
scancode_set.single_byte[0x48] = Some(KeyCode::Numpad8); // 48 scancode_set.single_byte[0x48] = Some(KeyCode::Numpad8); // 48
scancode_set.single_byte[0x49] = Some(KeyCode::Numpad9); // 49 scancode_set.single_byte[0x49] = Some(KeyCode::Numpad9); // 49
scancode_set.single_byte[0x4A] = Some(KeyCode::NumpadMinus); // 4A scancode_set.single_byte[0x4A] = Some(KeyCode::NumpadMinus); // 4A
scancode_set.single_byte[0x4B] = Some(KeyCode::Numpad4); // 4B scancode_set.single_byte[0x4B] = Some(KeyCode::Numpad4); // 4B
scancode_set.single_byte[0x4C] = Some(KeyCode::Numpad5); // 4C scancode_set.single_byte[0x4C] = Some(KeyCode::Numpad5); // 4C
scancode_set.single_byte[0x4D] = Some(KeyCode::Numpad6); // 4D scancode_set.single_byte[0x4D] = Some(KeyCode::Numpad6); // 4D
scancode_set.single_byte[0x4E] = Some(KeyCode::NumpadPlus); // 4E scancode_set.single_byte[0x4E] = Some(KeyCode::NumpadPlus); // 4E
scancode_set.single_byte[0x4F] = Some(KeyCode::Numpad1); // 4F scancode_set.single_byte[0x4F] = Some(KeyCode::Numpad1); // 4F
scancode_set.single_byte[0x50] = Some(KeyCode::Numpad2); // 50 scancode_set.single_byte[0x50] = Some(KeyCode::Numpad2); // 50
scancode_set.single_byte[0x51] = Some(KeyCode::Numpad3); // 51 scancode_set.single_byte[0x51] = Some(KeyCode::Numpad3); // 51
scancode_set.single_byte[0x52] = Some(KeyCode::Numpad0); // 52 scancode_set.single_byte[0x52] = Some(KeyCode::Numpad0); // 52
scancode_set.single_byte[0x53] = Some(KeyCode::NumpadPeriod); // 53 scancode_set.single_byte[0x53] = Some(KeyCode::NumpadPeriod); // 53
// 0x54 // 0x54
// 0x55 // 0x55
// 0x56 // 0x56
scancode_set.single_byte[0x57] = Some(KeyCode::F11); // 57 scancode_set.single_byte[0x57] = Some(KeyCode::F11); // 57
scancode_set.single_byte[0x58] = Some(KeyCode::F12); // 58 scancode_set.single_byte[0x58] = Some(KeyCode::F12); // 58
for i in 0x81..=0xD8 { for i in 0x81..=0xD8 {
scancode_set.single_byte[i] = scancode_set.single_byte[i - 0x80]; scancode_set.single_byte[i] = scancode_set.single_byte[i - 0x80];
} }
scancode_set.extended[0x10] = Some(KeyCode::PrevTrack); // E010 scancode_set.extended[0x10] = Some(KeyCode::PrevTrack); // E010
//0x11 //0x11
//0x12 //0x12
//0x13 //0x13
//0x14 //0x14
//0x15 //0x15
//0x16 //0x16
//0x17 //0x17
//0x18 //0x18
scancode_set.extended[0x19] = Some(KeyCode::NextTrack); // E019 scancode_set.extended[0x19] = Some(KeyCode::NextTrack); // E019
//0x1A //0x1A
//0x1B //0x1B
scancode_set.extended[0x1C] = Some(KeyCode::NumpadEnter); // E01C scancode_set.extended[0x1C] = Some(KeyCode::NumpadEnter); // E01C
scancode_set.extended[0x1D] = Some(KeyCode::ControlRight); // E01D scancode_set.extended[0x1D] = Some(KeyCode::ControlRight); // E01D
//0x1E //0x1E
//0x1F //0x1F
scancode_set.extended[0x20] = Some(KeyCode::Mute); // E020 scancode_set.extended[0x20] = Some(KeyCode::Mute); // E020
scancode_set.extended[0x21] = Some(KeyCode::Calculator); // E021 scancode_set.extended[0x21] = Some(KeyCode::Calculator); // E021
scancode_set.extended[0x22] = Some(KeyCode::Play); // E022 scancode_set.extended[0x22] = Some(KeyCode::Play); // E022
//0x23 //0x23
scancode_set.extended[0x24] = Some(KeyCode::Stop); // E024 scancode_set.extended[0x24] = Some(KeyCode::Stop); // E024
//0x25 //0x25
//0x26 //0x26
//0x27 //0x27
//0x28 //0x28
//0x29 //0x29
//0x2A //0x2A
//0x2B //0x2B
//0x2C //0x2C
//0x2D //0x2D
scancode_set.extended[0x2E] = Some(KeyCode::VolumeDown); // E02E scancode_set.extended[0x2E] = Some(KeyCode::VolumeDown); // E02E
//0x2F //0x2F
scancode_set.extended[0x30] = Some(KeyCode::VolumeUp); // E030 scancode_set.extended[0x30] = Some(KeyCode::VolumeUp); // E030
//0x31 //0x31
scancode_set.extended[0x32] = Some(KeyCode::WWWHome); // E032 scancode_set.extended[0x32] = Some(KeyCode::WWWHome); // E032
//0x33 //0x33
//0x34 //0x34
scancode_set.extended[0x35] = Some(KeyCode::NumpadSlash); // E035 scancode_set.extended[0x35] = Some(KeyCode::NumpadSlash); // E035
//0x36 //0x36
//0x37 //0x37
scancode_set.extended[0x38] = Some(KeyCode::AltRight); // E038 scancode_set.extended[0x38] = Some(KeyCode::AltRight); // E038
//0x39 //0x39
//0x3A //0x3A
//0x3B //0x3B
//0x3C //0x3C
//0x3D //0x3D
//0x3E //0x3E
//0x3F //0x3F
//0x40 //0x40
//0x41 //0x41
//0x42 //0x42
//0x43 //0x43
//0x44 //0x44
//0x45 //0x45
//0x46 //0x46
scancode_set.extended[0x47] = Some(KeyCode::Home); // E047 scancode_set.extended[0x47] = Some(KeyCode::Home); // E047
scancode_set.extended[0x48] = Some(KeyCode::ArrowUp); // E048 scancode_set.extended[0x48] = Some(KeyCode::ArrowUp); // E048
scancode_set.extended[0x49] = Some(KeyCode::PageUp); // E049 scancode_set.extended[0x49] = Some(KeyCode::PageUp); // E049
//0x4A //0x4A
scancode_set.extended[0x4B] = Some(KeyCode::ArrowLeft); // E04B scancode_set.extended[0x4B] = Some(KeyCode::ArrowLeft); // E04B
//0x4C //0x4C
scancode_set.extended[0x4D] = Some(KeyCode::ArrowRight); // E04D scancode_set.extended[0x4D] = Some(KeyCode::ArrowRight); // E04D
//0x4E //0x4E
scancode_set.extended[0x4F] = Some(KeyCode::End); // E04F scancode_set.extended[0x4F] = Some(KeyCode::End); // E04F
scancode_set.extended[0x50] = Some(KeyCode::ArrowDown); // E050 scancode_set.extended[0x50] = Some(KeyCode::ArrowDown); // E050
scancode_set.extended[0x51] = Some(KeyCode::PageDown); // E051 scancode_set.extended[0x51] = Some(KeyCode::PageDown); // E051
scancode_set.extended[0x52] = Some(KeyCode::Insert); // E052 scancode_set.extended[0x52] = Some(KeyCode::Insert); // E052
scancode_set.extended[0x53] = Some(KeyCode::Delete); // E053 scancode_set.extended[0x53] = Some(KeyCode::Delete); // E053
for i in 0x90..=0xED { for i in 0x90..=0xED {
scancode_set.extended[i] = scancode_set.extended[i - 0x80]; scancode_set.extended[i] = scancode_set.extended[i - 0x80];
} }
scancode_set scancode_set
} }
pub fn scancode_set2() -> Self { pub fn scancode_set2() -> Self {
Self { Self {
single_byte: [None; 256], single_byte: [None; 256],
extended: [None; 256], extended: [None; 256],
} }
} }
} }
impl ScancodeSet for CustomScancodeSet { impl ScancodeSet for CustomScancodeSet {
fn advance_state(&self, state: &mut DecodeState, code: u8) -> Result<Option<KeyEvent>, Error> { fn advance_state(&self, state: &mut DecodeState, code: u8) -> Result<Option<KeyEvent>, Error> {
match *state { match *state {
DecodeState::Start => { DecodeState::Start => {
match code { match code {
EXTENDED_KEY_CODE => { EXTENDED_KEY_CODE => {
*state = DecodeState::Extended; *state = DecodeState::Extended;
Ok(None) Ok(None)
} }
0x80..=0xFF => { 0x80..=0xFF => {
// Release codes // Release codes
Ok(Some(KeyEvent::new( Ok(Some(KeyEvent::new(
self.map_scancode(code - 0x80)?, self.map_scancode(code - 0x80)?,
KeyState::Up, KeyState::Up,
))) )))
} }
_ => { _ => {
// Normal codes // Normal codes
Ok(Some(KeyEvent::new( Ok(Some(KeyEvent::new(
self.map_scancode(code)?, self.map_scancode(code)?,
KeyState::Down, KeyState::Down,
))) )))
} }
}
} }
} DecodeState::Extended => {
DecodeState::Extended => { *state = DecodeState::Start;
*state = DecodeState::Start; match code {
match code { 0x80..=0xFF => {
0x80..=0xFF => { // Extended Release codes
// Extended Release codes Ok(Some(KeyEvent::new(
Ok(Some(KeyEvent::new( self.map_extended_scancode(code - 0x80)?,
self.map_extended_scancode(code - 0x80)?, KeyState::Up,
KeyState::Up, )))
))) }
} _ => {
_ => { // Normal release codes
// Normal release codes Ok(Some(KeyEvent::new(
Ok(Some(KeyEvent::new( self.map_extended_scancode(code)?,
self.map_extended_scancode(code)?, KeyState::Down,
KeyState::Down, )))
))) }
} }
} }
} _ => {
_ => { // Can't get in to this state
// Can't get in to this state unimplemented!();
unimplemented!(); }
} }
} }
} fn map_scancode(&self, code: u8) -> Result<KeyCode, Error> {
fn map_scancode(&self, code: u8) -> Result<KeyCode, Error> { if let Some(kc) = self.single_byte[code as usize] {
if let Some(kc) = self.single_byte[code as usize] { Ok(kc)
Ok(kc) } else {
} else { Err(Error::UnknownKeyCode)
Err(Error::UnknownKeyCode) }
} }
} fn map_extended_scancode(&self, code: u8) -> Result<KeyCode, Error> {
fn map_extended_scancode(&self, code: u8) -> Result<KeyCode, Error> { if let Some(kc) = self.extended[code as usize] {
if let Some(kc) = self.extended[code as usize] { Ok(kc)
Ok(kc) } else {
} else { Err(Error::UnknownKeyCode)
Err(Error::UnknownKeyCode) }
} }
} }
}

View file

@ -2,104 +2,102 @@ use super::DecodedKey;
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
pub enum LayoutEntryKind { pub enum LayoutEntryKind {
Regular, Regular,
Numlockable, Numlockable,
Capslockable, Capslockable,
} }
impl Default for LayoutEntryKind { impl Default for LayoutEntryKind {
fn default() -> Self { fn default() -> Self {
Self::Regular Self::Regular
} }
} }
#[derive(Debug, Clone, Copy, Default)] #[derive(Debug, Clone, Copy, Default)]
pub struct LayoutEntry { pub struct LayoutEntry {
pub kind: LayoutEntryKind, pub kind: LayoutEntryKind,
pub unshifted: Option<DecodedKey>, pub unshifted: Option<DecodedKey>,
pub shifted: Option<DecodedKey>, pub shifted: Option<DecodedKey>,
pub locked: Option<DecodedKey>, pub locked: Option<DecodedKey>,
pub locked_shifted: Option<DecodedKey>, pub locked_shifted: Option<DecodedKey>,
pub altgr: Option<DecodedKey>, pub altgr: Option<DecodedKey>,
pub raw_unicode: Option<DecodedKey>, pub raw_unicode: Option<DecodedKey>,
} }
impl LayoutEntry { impl LayoutEntry {
#[must_use] #[must_use]
pub fn regular() -> Self { pub fn regular() -> Self {
Self { Self {
kind: LayoutEntryKind::Regular, kind: LayoutEntryKind::Regular,
..Default::default() ..Default::default()
} }
} }
#[must_use] #[must_use]
pub fn numpad() -> Self { pub fn numpad() -> Self {
Self { Self {
kind: LayoutEntryKind::Numlockable, kind: LayoutEntryKind::Numlockable,
..Default::default() ..Default::default()
} }
} }
#[must_use] #[must_use]
pub fn alphabet() -> Self { pub fn alphabet() -> Self {
Self { Self {
kind: LayoutEntryKind::Capslockable, kind: LayoutEntryKind::Capslockable,
..Default::default() ..Default::default()
} }
} }
#[must_use] #[must_use]
pub fn unshifted(mut self, c: impl Into<DecodedKey>) -> Self { pub fn unshifted(mut self, c: impl Into<DecodedKey>) -> Self {
self.unshifted = Some(c.into()); self.unshifted = Some(c.into());
self self
} }
#[must_use] #[must_use]
pub fn shifted(mut self, c: impl Into<DecodedKey>) -> Self { pub fn shifted(mut self, c: impl Into<DecodedKey>) -> Self {
self.shifted = Some(c.into()); self.shifted = Some(c.into());
self self
} }
#[must_use] #[must_use]
pub fn altgr(mut self, c: impl Into<DecodedKey>) -> Self { pub fn altgr(mut self, c: impl Into<DecodedKey>) -> Self {
self.altgr = Some(c.into()); self.altgr = Some(c.into());
self self
} }
#[must_use] #[must_use]
pub fn raw_unicode(mut self, c: impl Into<DecodedKey>) -> Self { pub fn raw_unicode(mut self, c: impl Into<DecodedKey>) -> Self {
self.raw_unicode = Some(c.into()); self.raw_unicode = Some(c.into());
self self
} }
#[must_use] #[must_use]
pub fn locked(mut self, c: impl Into<DecodedKey>) -> Self { pub fn locked(mut self, c: impl Into<DecodedKey>) -> Self {
self.locked = Some(c.into()); self.locked = Some(c.into());
self self
} }
#[must_use] #[must_use]
pub fn locked_shifted(mut self, c: impl Into<DecodedKey>) -> Self { pub fn locked_shifted(mut self, c: impl Into<DecodedKey>) -> Self {
self.locked_shifted = Some(c.into()); self.locked_shifted = Some(c.into());
self self
} }
#[must_use] #[must_use]
pub fn common(self, c: impl Into<DecodedKey> + Clone) -> Self { pub fn common(self, c: impl Into<DecodedKey> + Clone) -> Self {
self self.unshifted(c.clone())
.unshifted(c.clone()) .shifted(c.clone())
.shifted(c.clone()) .locked(c.clone())
.locked(c.clone()) .locked_shifted(c)
.locked_shifted(c) }
} #[must_use]
#[must_use] pub fn low(self, c: impl Into<DecodedKey> + Clone) -> Self {
pub fn low(self, c: impl Into<DecodedKey> + Clone) -> Self { self.unshifted(c.clone()).locked_shifted(c)
self.unshifted(c.clone()).locked_shifted(c) }
} #[must_use]
#[must_use] pub fn high(self, c: impl Into<DecodedKey> + Clone) -> Self {
pub fn high(self, c: impl Into<DecodedKey> + Clone) -> Self { self.shifted(c.clone()).locked(c)
self.shifted(c.clone()).locked(c) }
} #[must_use]
#[must_use] pub fn all(self, c: impl Into<DecodedKey> + Clone) -> Self {
pub fn all(self, c: impl Into<DecodedKey> + Clone) -> Self { self.unshifted(c.clone())
self .shifted(c.clone())
.unshifted(c.clone()) .locked(c.clone())
.shifted(c.clone()) .locked_shifted(c.clone())
.locked(c.clone()) .altgr(c.clone())
.locked_shifted(c.clone()) .raw_unicode(c)
.altgr(c.clone()) }
.raw_unicode(c)
}
} }

View file

@ -1,111 +1,111 @@
#![allow(non_snake_case)] #![allow(non_snake_case)]
#[derive(Debug)] #[derive(Debug)]
pub struct Modifiers { pub struct Modifiers {
pub lshift: bool, pub lshift: bool,
pub rshift: bool, pub rshift: bool,
pub lctrl: bool, pub lctrl: bool,
pub rctrl: bool, pub rctrl: bool,
pub numlock: bool, pub numlock: bool,
pub capslock: bool, pub capslock: bool,
pub alt_gr: bool, pub alt_gr: bool,
} }
impl Modifiers { impl Modifiers {
pub fn is_shifted(&self) -> bool { pub fn is_shifted(&self) -> bool {
self.lshift | self.rshift self.lshift | self.rshift
} }
pub fn is_ctrl(&self) -> bool { pub fn is_ctrl(&self) -> bool {
self.lctrl | self.rctrl self.lctrl | self.rctrl
} }
pub fn is_caps(&self) -> bool { pub fn is_caps(&self) -> bool {
self.capslock self.capslock
} }
} }
#[derive(Debug, PartialEq, Eq, Copy, Clone)] #[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum KeyState { pub enum KeyState {
Up, Up,
Down, Down,
} }
#[derive(Debug, PartialEq, Eq, Clone)] #[derive(Debug, PartialEq, Eq, Clone)]
pub struct KeyEvent { pub struct KeyEvent {
pub code: KeyCode, pub code: KeyCode,
pub state: KeyState, pub state: KeyState,
} }
impl KeyEvent { impl KeyEvent {
pub fn new(code: KeyCode, state: KeyState) -> KeyEvent { pub fn new(code: KeyCode, state: KeyState) -> KeyEvent {
KeyEvent { code, state } KeyEvent { code, state }
} }
} }
#[derive(Debug, PartialEq, Eq, Copy, Clone)] #[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum HandleControl { pub enum HandleControl {
/// If either Ctrl key is held down, convert the letters A through Z into /// 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 /// Unicode chars U+0001 through U+001A. If the Ctrl keys are not held
/// down, letters go through normally. /// down, letters go through normally.
MapLettersToUnicode, MapLettersToUnicode,
/// Don't do anything special - send through the Ctrl key up/down events, /// Don't do anything special - send through the Ctrl key up/down events,
/// and leave the letters as letters. /// and leave the letters as letters.
Ignore, Ignore,
} }
#[derive(Debug, Copy, Clone, Eq, PartialEq)] #[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum DecodeState { pub enum DecodeState {
Start, Start,
Extended, Extended,
Release, Release,
ExtendedRelease, ExtendedRelease,
} }
/// Indicates different error conditions. /// Indicates different error conditions.
#[derive(Debug, PartialEq, Eq, Copy, Clone)] #[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum Error { pub enum Error {
BadStartBit, BadStartBit,
BadStopBit, BadStopBit,
ParityError, ParityError,
UnknownKeyCode, UnknownKeyCode,
InvalidState, InvalidState,
} }
#[derive(Debug, PartialEq, Eq, Copy, Clone)] #[derive(Debug, PartialEq, Eq, Copy, Clone)]
#[repr(u8)] #[repr(u8)]
pub enum DecodedKeyKind { pub enum DecodedKeyKind {
RawKey = 0, RawKey = 0,
Unicode = 1, Unicode = 1,
} }
#[derive(Debug, PartialEq, Eq, Copy, Clone)] #[derive(Debug, PartialEq, Eq, Copy, Clone)]
#[repr(C)] #[repr(C)]
pub struct DecodedKey { pub struct DecodedKey {
pub kind: DecodedKeyKind, pub kind: DecodedKeyKind,
pub value: u32, pub value: u32,
} }
impl From<char> for DecodedKey { impl From<char> for DecodedKey {
fn from(ch: char) -> Self { fn from(ch: char) -> Self {
Self { Self {
kind: DecodedKeyKind::Unicode, kind: DecodedKeyKind::Unicode,
value: ch as u32, value: ch as u32,
} }
} }
} }
impl From<KeyCode> for DecodedKey { impl From<KeyCode> for DecodedKey {
fn from(kc: KeyCode) -> Self { fn from(kc: KeyCode) -> Self {
Self { Self {
kind: DecodedKeyKind::RawKey, kind: DecodedKeyKind::RawKey,
value: kc as u32, value: kc as u32,
} }
} }
} }
impl DecodedKey { impl DecodedKey {
pub const ZERO: Self = Self { pub const ZERO: Self = Self {
kind: DecodedKeyKind::Unicode, kind: DecodedKeyKind::Unicode,
value: 0, value: 0,
}; };
pub fn Unicode(ch: char) -> Self { pub fn Unicode(ch: char) -> Self {
Self { Self {
kind: DecodedKeyKind::Unicode, kind: DecodedKeyKind::Unicode,
value: ch.into(), value: ch.into(),
} }
} }
pub fn RawKey(byte: u8) -> Self { pub fn RawKey(byte: u8) -> Self {
Self { Self {
kind: DecodedKeyKind::RawKey, kind: DecodedKeyKind::RawKey,
value: byte.into(), value: byte.into(),
} }
} }
} }
macro_rules! keycode_enum { macro_rules! keycode_enum {
(@get_last $Variant:ident) => { (@get_last $Variant:ident) => {

View file

@ -1,7 +1,5 @@
#![allow(clippy::empty_loop)] #![allow(clippy::empty_loop)]
use crate::scheduler::SCHEDULER;
// use acpi::AcpiTables; // use acpi::AcpiTables;
// use x86_64::instructions::interrupts::{disable, enable}; // use x86_64::instructions::interrupts::{disable, enable};
@ -10,11 +8,7 @@ use crate::scheduler::SCHEDULER;
use { use {
crate::{ crate::{
arch::{init, sloop}, arch::{init, sloop},
boot_conf,
boot_conf::BootConfig,
// capabilities::FileAccess,
experiments::systeminfo::{KERNEL_VERSION, RELEASE_TYPE},
// file::PathRep,
relib::network::socket::{SimpleSock, Socket}, relib::network::socket::{SimpleSock, Socket},
// scheduler::SCHEDULER, // scheduler::SCHEDULER,
// VgaBuffer, // VgaBuffer,
@ -23,30 +17,25 @@ use {
// SCHEDULER, // SCHEDULER,
SCREEN_BUFFER, SCREEN_BUFFER,
}, },
alloc::{
format,
string::{String, ToString},
vec,
},
core::sync::atomic::{AtomicU64, Ordering::*},
facepalm::start_facepalm, facepalm::start_facepalm,
lazy_static::lazy_static, lazy_static::lazy_static,
log::*,
// shadeable::pixel_format::from_vga_16,
// vga::colors::Color16,
}; };
lazy_static! { lazy_static! {
// TODO: Change this structure to allow for multiple cores loaded // TODO: Change this structure to allow for multiple cores loaded
pub static ref TICK: AtomicU64 = AtomicU64::new(0); pub static ref KERNEL_CONF: KernelConfig = KernelConfig::new();
pub static ref BOOT_CONF: BootConfig = boot_conf::BootConfig::new();
} }
/// The main entry point of the kernel /// The main entry point of the kernel
#[no_mangle] #[no_mangle]
pub fn kernel_main() -> ! { pub fn kernel_main() -> ! {
init::init(); 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(); let mut scheduler = SCHEDULER.lock();
/* /*
@ -73,33 +62,41 @@ pub fn kernel_main() -> ! {
// use crate::proto_filetable::file::FileLocations; // use crate::proto_filetable::file::FileLocations;
/* /*
if false { if false {
let mut sock_print_id = SimpleSock::new(); let mut sock_print_id = SimpleSock::new();
sock_print_id.register_protocol("Screen Printer".to_string()); sock_print_id.register_protocol("Screen Printer".to_string());
sock_print_id.write(format!("🐑").into()); sock_print_id.write(format!("🐑").into());
let mut mode = SCREEN_BUFFER.lock(); let mut mode = SCREEN_BUFFER.lock();
mode.force_redraw(); mode.force_redraw();
for current in (*String::from_utf8_lossy(&sock_print_id.peek().unwrap())).chars() { 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.draw_char(0, 0, current, from_vga_16(Color16::Red));
}
// mode.copy_to_buffer();
} }
// mode.copy_to_buffer(); <<<<<<< HEAD
} */
*/
/* /*
// TODO: create a scratchpad module // TODO: create a scratchpad module
if false { if false {
// Currently not implemented // Currently not implemented
let acpi_handler = AcpiStruct {}; let acpi_handler = AcpiStruct {};
let mut table; let mut table;
unsafe { unsafe {
table = AcpiTables::search_for_rsdp_bios(acpi_handler); table = AcpiTables::search_for_rsdp_bios(acpi_handler);
}
} }
}
=======
mode.copy_to_buffer();
}
*/ start_facepalm();
scratchpad();
>>>>>>> master
*/
// start_facepalm(); // start_facepalm();
// scratchpad(); // scratchpad();
@ -126,19 +123,6 @@ pub fn kernel_main() -> ! {
sloop() 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() { pub fn cpu_socket_startup() {
let mut cpu_info_socket = SimpleSock::new(); let mut cpu_info_socket = SimpleSock::new();
cpu_info_socket.register_protocol("CPU_INFO".to_string()); cpu_info_socket.register_protocol("CPU_INFO".to_string());
@ -184,7 +168,7 @@ impl acpi::AcpiHandler for AcpiStruct {
todo!("map_physical_region"); todo!("map_physical_region");
} }
fn unmap_physical_region<T>(region: &acpi::PhysicalMapping<Self, T>) { fn unmap_physical_region<T>(_region: &acpi::PhysicalMapping<Self, T>) {
todo!("unmap_physical_region"); todo!("unmap_physical_region");
} }
} }

View file

@ -12,7 +12,8 @@
exclusive_range_pattern, exclusive_range_pattern,
lang_items, lang_items,
naked_functions, naked_functions,
slice_pattern slice_pattern,
prelude_import
)] )]
/// Contains architecture specific code for aarch64. /// Contains architecture specific code for aarch64.
@ -32,8 +33,10 @@ pub mod arch;
#[macro_use] #[macro_use]
pub mod print; pub mod print;
// pub mod devices; pub mod devices;
// pub mod wasm_jumploader; pub mod port_io;
pub mod rhai_shell;
pub mod wasm_jumploader;
#[macro_use] #[macro_use]
pub extern crate log; pub extern crate log;
@ -42,7 +45,6 @@ pub extern crate log;
// Modules // // Modules //
///////////// /////////////
pub mod allocator; pub mod allocator;
pub mod boot_conf;
pub mod driver_traits; pub mod driver_traits;
pub mod experiments; pub mod experiments;
pub mod graphics; pub mod graphics;
@ -50,8 +52,7 @@ pub mod kernel_state;
pub mod keyboard; pub mod keyboard;
pub mod kmain; pub mod kmain;
pub mod logger; pub mod logger;
pub mod panic; pub mod proto_filetable;
// pub mod proto_filetable;
pub mod relib; pub mod relib;
pub mod scheduler; pub mod scheduler;
mod unicode_utils; mod unicode_utils;
@ -66,34 +67,40 @@ pub extern crate externc_libm as libm;
// Re-exports /// // Re-exports ///
//////////////// ////////////////
pub use allocator::*; pub use allocator::*;
pub use boot_conf::*;
pub use driver_traits::*; pub use driver_traits::*;
pub use experiments::*; pub use experiments::*;
pub use graphics::*; pub use graphics::*;
pub use kernel_state::*; pub use kernel_state::*;
pub use keyboard::*; pub use keyboard::*;
pub use logger::*; pub use logger::*;
pub use panic::*; pub use proto_filetable::*;
// pub use proto_filetable::*;
pub use relib::*; pub use relib::*;
// pub use scheduler::*; // pub use scheduler::*;
pub use utils::*; pub use utils::*;
// pub use vga_e::*; // pub use vga_e::*;
pub use wasm::*; pub use wasm::*;
pub mod boot_conf;
//////////////////
pub mod virtio; pub mod virtio;
pub use virtio::*; pub use virtio::*;
// pub mod alias_table; // pub mod alias_table;
// pub use alias_table::*; // pub use alias_table::*;
/*
pub mod tests; pub mod tests;
pub use tests::*; pub use tests::*;
pub mod syscalls;
pub use syscalls::*;
*/
pub mod scratchpad; pub mod scratchpad;
pub use 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::*;

View file

@ -1,17 +1,12 @@
use core::sync::atomic::Ordering; use core::sync::atomic::Ordering;
use crate::kmain::TICK; use crate::network::socket::{SimpleSock, Socket};
// use crate::println; use crate::serial_println;
use alloc::format;
// use alloc::fmt; use kernel::TICK;
use lliw::{Fg, Reset}; use lliw::{Fg, Reset};
pub use log::{debug, info, trace, warn};
use log::{Level, Metadata, Record}; use log::{Level, Metadata, Record};
// use crate::arch::drivers::timer::TIMER_INTERRUPT_HERTZ;
pub const TIMER_INTERRUPT_HERTZ: f64 = 100.0;
struct SimpleLogger; struct SimpleLogger;
// TODO: Rebuild this to take advantage of sockets // TODO: Rebuild this to take advantage of sockets
// DETAIL: Log to a socket instead of the screen // DETAIL: Log to a socket instead of the screen
@ -26,7 +21,7 @@ impl log::Log for SimpleLogger {
let color; let color;
let time = TICK.load(Ordering::Relaxed) as f64; let time = TICK.load(Ordering::Relaxed) as f64;
let time_float = time / TIMER_INTERRUPT_HERTZ; let time_float = time;
match record.level() { match record.level() {
log::Level::Error => color = (Fg::Red, "$RED$"), 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::Debug => color = (Fg::Blue, "$BLUE$"),
log::Level::Trace => color = (Fg::Yellow, "$YELLOW$"), 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, color.0,
record.level(), record.level(),
@ -45,6 +47,14 @@ impl log::Log for SimpleLogger {
Reset, Reset,
record.args() 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 /// Clear the log buffer

View file

@ -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!");
}

16
ableos/src/port_io.rs Normal file
View file

@ -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) }
}

View file

@ -0,0 +1 @@
pub mod rust_2021;

View file

@ -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::*};

View file

@ -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![];
};
}

View file

@ -1,7 +1,5 @@
use core::fmt; use core::fmt;
use alloc::{string::String, vec, vec::Vec};
#[derive(Debug, PartialEq, Clone)] #[derive(Debug, PartialEq, Clone)]
pub struct PathRep { pub struct PathRep {
pub location: FileLocations, pub location: FileLocations,

View file

@ -15,11 +15,6 @@
//! The file table is not thread safe. //! The file table is not thread safe.
//! The file table is not persistent. //! The file table is not persistent.
use alloc::{
string::{String, ToString},
vec::Vec,
};
use hashbrown::HashMap; use hashbrown::HashMap;
pub mod contain; pub mod contain;

View file

@ -1,9 +1,3 @@
use alloc::{
string::{String, ToString},
vec,
vec::Vec,
};
/* /*
clparse clparse
* A simple command line parser for ableOS * A simple command line parser for ableOS

View file

@ -1,6 +1,3 @@
use alloc::{boxed::Box};
pub struct BinCodeWriter { pub struct BinCodeWriter {
pub stream: Box<u8>, pub stream: Box<u8>,
} }

View file

@ -1,6 +1,3 @@
use alloc::vec;
use alloc::vec::Vec;
pub fn encode(bytes: &[u8]) -> Vec<u8> { pub fn encode(bytes: &[u8]) -> Vec<u8> {
let mut encoding; let mut encoding;

View file

@ -1,7 +1,3 @@
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
pub type Stream = Vec<u8>; pub type Stream = Vec<u8>;
#[derive(Debug)] #[derive(Debug)]

View file

@ -1,20 +1,20 @@
pub struct Time { pub struct Time {
pub year: u16, pub year: u16,
pub month: u16, pub month: u16,
pub day: u16, pub day: u16,
pub hour: u16, pub hour: u16,
pub minutes: u16, pub minutes: u16,
pub seconds: u16, pub seconds: u16,
pub microseconds: u32, pub microseconds: u32,
} }
impl fmt::Display for Time { impl fmt::Display for Time {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!( write!(
f, f,
"{:?}/{:?}/{:?} {:02}:{:02}:{:02}", "{:?}/{:?}/{:?} {:02}:{:02}:{:02}",
self.year, self.month, self.day, self.hour, self.minutes, self.seconds self.year, self.month, self.day, self.hour, self.minutes, self.seconds
) )
} }
} }
pub mod kilotime; pub mod kilotime;
use core::fmt; use core::fmt;

View file

@ -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::<rhai::Dynamic>(&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<Vec<char>> = 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"),
}
}

View file

@ -1,4 +1,4 @@
use alloc::vec::Vec; #![allow(missing_docs)]
pub type SoundCardID = u8; pub type SoundCardID = u8;
pub type DeviceID = u8; pub type DeviceID = u8;

View file

@ -1,4 +1,4 @@
#![warn(missing_docs)] // #![warn(missing_docs)]
//! The standard ableOS scheduler named //! The standard ableOS scheduler named
//! //!
@ -6,8 +6,6 @@
//! The scheduler is also responsible for choosing the priority of a process. //! The scheduler is also responsible for choosing the priority of a process.
//! The scheduler is responsible for choosing which process to execute next. //! The scheduler is responsible for choosing which process to execute next.
use alloc::{string::ToString, vec::Vec};
pub mod capabilities; pub mod capabilities;
pub mod proc; pub mod proc;

View file

@ -1,10 +1,8 @@
use crate::kmain::generate_process_pass; use crate::{
use alloc::{string::ToString, vec::Vec}; kmain::generate_process_pass,
scheduler::capabilities::Capabilities,
use super::{ scheduler::proc::{Process, PID},
capabilities::Capabilities, scheduler::Priority,
proc::{Process, PID},
Priority,
}; };
/// Add additional wake conditions to the list /// Add additional wake conditions to the list
pub enum WakeCondition { pub enum WakeCondition {

View file

@ -1,7 +1,5 @@
//! Process definition and general utilities surrounding them //! Process definition and general utilities surrounding them
use alloc::string::String;
use super::{capabilities::Capabilities, Priority}; use super::{capabilities::Capabilities, Priority};
/// Process Identification /// Process Identification

View file

@ -1,108 +1,37 @@
use alloc::{format, vec::Vec}; use acpi::AcpiTables;
use crate::rhai_shell::rhai_shell;
/// Experimental scratchpad for testing. /// Experimental scratchpad for testing.
pub fn scratchpad() { pub fn scratchpad() {
/* pci_fun();
let mut dev_list = Vec::new(); rhai_shell();
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();
} }
/*
pub struct PciIO {}
impl PortOps for PciIO { pub fn pci_fun() {}
unsafe fn read8(&self, port: u16) -> u8 {
cpuio::inb(port as u16)
}
unsafe fn read16(&self, port: u16) -> u16 { pub fn acpi() {
cpuio::inw(port as u16) let acpi_handler = AcpiStruct {};
} let _table;
unsafe {
unsafe fn read32(&self, port: u16) -> u32 { _table = AcpiTables::search_for_rsdp_bios(acpi_handler);
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);
} }
} }
*/
/*
/// An experimental process message format
pub struct ProcessMessage {
pub to_pid: PID,
pub from_pid: PID,
pub message: [u8; 2048],
pub sender_time: SecondsTime, // TODO: move to a better place
} #[derive(Clone, Copy, Debug, PartialEq, Eq)]
// pub struct AcpiStruct {}
// use libwasm::syscalls::time_calls::SecondsTime; impl acpi::AcpiHandler for AcpiStruct {
unsafe fn map_physical_region<T>(
impl ProcessMessage { &self,
pub fn new(to_pid: PID, from_pid: PID, message: [u8; 2048]) -> Self { physical_address: usize,
ProcessMessage { size: usize,
to_pid, ) -> acpi::PhysicalMapping<Self, T> {
from_pid, info!("PHYS ADDR: {:?}", physical_address);
message, info!("Size: {:?}", size);
sender_time: SecondsTime { todo!("map_physical_region");
seconds: 0, }
milliseconds: 0, fn unmap_physical_region<T>(_region: &acpi::PhysicalMapping<Self, T>) {
}, todo!("unmap_physical_region");
}
} }
} }
*/
pub fn rhai_shell() {
let mut engine = rhai::Engine::new();
let ret = engine.eval::<i64>("1 + 2");
match ret {
// Ok(x) => println!("{}", x),
// Err(e) => println!("{}", e),
_ => (),
}
loop {}
}
lazy_static::lazy_static!(
pub static ref KEYBUFF: spin::Mutex<Vec<char>> = spin::Mutex::new(
Vec::new())
;
);

View file

@ -1,8 +1,3 @@
use alloc::{
format,
string::{String, ToString},
vec,
};
use picorand::PicoRandGenerate; use picorand::PicoRandGenerate;
use rkyv::{ser::serializers::AllocSerializer, Deserialize}; use rkyv::{ser::serializers::AllocSerializer, Deserialize};
use shadeable::pixel_format::from_vga_16; use shadeable::pixel_format::from_vga_16;
@ -10,13 +5,14 @@ use vga::colors::Color16;
use y_compositor_protocol::Version; use y_compositor_protocol::Version;
use crate::{ use crate::{
kmain::{BOOT_CONF, TICK}, kmain::KERNEL_CONF,
network::socket::{SimpleSock, Socket, SocketReturns}, 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() { pub fn run_tests() {
if BOOT_CONF.run_tests { if KERNEL_CONF.tests.run_tests {
// quick and dirty testing framework // quick and dirty testing framework
screen_writer_test(); screen_writer_test();
socket_test(); socket_test();
@ -25,11 +21,11 @@ pub fn run_tests() {
socket_test_rng(); socket_test_rng();
} }
if BOOT_CONF.run_demos { if KERNEL_CONF.tests.run_demos {
graphics_api_demo(); graphics_api_demo();
} }
if BOOT_CONF.run_shader_tests { if KERNEL_CONF.tests.run_shader_tests {
shader_tests(); shader_tests();
} }
} }

View file

@ -2,7 +2,7 @@
//! //!
//! //!
//! //!
#[inline]
pub fn type_of<T>(_: &T) -> &str { pub fn type_of<T>(_: &T) -> &str {
core::any::type_name::<T>() core::any::type_name::<T>()
} }

View file

@ -1,13 +1,6 @@
use shadeable::pixel_format::Rgba64; use vga::{
colors::Color16,
use crate::SCREEN_BUFFER; writers::{Graphics640x480x16, GraphicsWriter},
use {
ab_glyph::{Font, FontRef, Glyph},
vga::{
colors::Color16,
writers::{Graphics640x480x16, GraphicsWriter},
},
}; };
lazy_static::lazy_static! { lazy_static::lazy_static! {
@ -20,28 +13,27 @@ lazy_static::lazy_static! {
pub static ref VGAE_BUFF_OFFSET_Y: spin::Mutex<u8> = spin::Mutex::new(0); pub static ref VGAE_BUFF_OFFSET_Y: spin::Mutex<u8> = spin::Mutex::new(0);
} }
/// Converts a number to ... i forgor 💀 /// Converts a number to ... i forgor 💀
pub fn num_to_vga16(num: u8) -> Color16 { pub fn num_to_vga16(num: u8) -> Color16 {
use Color16::*; use Color16::*;
match num { match num {
0 => Black, 0 => Black,
1 => Blue, 1 => Blue,
2 => Green, 2 => Green,
3 => Cyan, 3 => Cyan,
4 => Red, 4 => Red,
5 => Magenta, 5 => Magenta,
6 => Brown, 6 => Brown,
7 => LightGrey, 7 => LightGrey,
8 => DarkGrey, 8 => DarkGrey,
9 => LightBlue, 9 => LightBlue,
10 => LightGreen, 10 => LightGreen,
11 => LightCyan, 11 => LightCyan,
12 => LightRed, 12 => LightRed,
13 => Pink, 13 => Pink,
14 => Yellow, 14 => Yellow,
15 => White, 15 => White,
// NOTE: Leasve the in // NOTE: Leasve the in
_ => Color16::Pink, _ => Color16::Pink,
} }
} }

View file

@ -1,5 +1,3 @@
use alloc::vec::Vec;
/// `NULL a s m` as an array of 4 bytes /// `NULL a s m` as an array of 4 bytes
pub const WASM_BINARY_MAGIC: [u8; 4] = [0x00, 0x61, 0x73, 0x6d]; pub const WASM_BINARY_MAGIC: [u8; 4] = [0x00, 0x61, 0x73, 0x6d];
/// `1 0 0 0` as an array of 4 bytes /// `1 0 0 0` as an array of 4 bytes

View file

@ -1,4 +1,3 @@
use alloc::format;
use wasmi::{ use wasmi::{
Error, Externals, FuncInstance, FuncRef, ModuleImportResolver, RuntimeArgs, RuntimeValue, Error, Externals, FuncInstance, FuncRef, ModuleImportResolver, RuntimeArgs, RuntimeValue,
Signature, Trap, ValueType, Signature, Trap, ValueType,
@ -7,6 +6,8 @@ use wasmi::{
pub struct HostExternals {} pub struct HostExternals {}
const ADD_FUNC_INDEX: usize = 0; const ADD_FUNC_INDEX: usize = 0;
const SEND_SIGNAL_INDEX: usize = 1;
const GET_TIME_INDEX: usize = 2;
impl Externals for HostExternals { impl Externals for HostExternals {
fn invoke_index( fn invoke_index(
@ -22,6 +23,25 @@ impl Externals for HostExternals {
println!("SYSCALL: {} + {} = {}", a, b, result); println!("SYSCALL: {} + {} = {}", a, b, result);
Ok(Some(RuntimeValue::I32(result as i32))) 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), _ => panic!("Unimplemented function at {}", index),
} }
} }
@ -31,6 +51,8 @@ impl HostExternals {
fn check_signature(&self, index: usize, signature: &Signature) -> bool { fn check_signature(&self, index: usize, signature: &Signature) -> bool {
let (params, ret_ty): (&[ValueType], Option<ValueType>) = match index { let (params, ret_ty): (&[ValueType], Option<ValueType>) = match index {
ADD_FUNC_INDEX => (&[ValueType::I32, ValueType::I32], Some(ValueType::I32)), 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, _ => return false,
}; };
signature.params() == params && signature.return_type() == ret_ty 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<FuncRef, Error> { fn resolve_func(&self, field_name: &str, signature: &Signature) -> Result<FuncRef, Error> {
let index = match field_name { let index = match field_name {
"add" => ADD_FUNC_INDEX, "add" => ADD_FUNC_INDEX,
"send_signal" => SEND_SIGNAL_INDEX,
_ => { _ => {
return Err(Error::Instantiation(format!( return Err(Error::Instantiation(format!(
"Export {} not found", "Export {} not found",

View file

@ -3,24 +3,26 @@ pub mod host_functions;
extern crate wasmi; extern crate wasmi;
// extern crate wabt; // extern crate wabt;
use alloc::vec::Vec;
use genfs::{Fs, OpenOptions}; use genfs::{Fs, OpenOptions};
use wasmi::{ImportsBuilder, ModuleInstance}; use wasmi::{ImportsBuilder, ModuleInstance};
use crate::{filesystem::FILE_SYSTEM, wasm_jumploader::host_functions::HostExternals}; use crate::{filesystem::FILE_SYSTEM, wasm_jumploader::host_functions::HostExternals};
pub fn interp() { pub fn interp() {
info!("Interpreting..."); trace!("Interpreting...");
let fs = &*FILE_SYSTEM.lock(); let fs = &*FILE_SYSTEM.lock();
info!("Got filesystem"); trace!("Got filesystem");
let file = fs 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(); .unwrap();
let mut wasm_binary = Vec::new(); let mut wasm_binary = Vec::new();
let ret = file.read_to_end(&mut wasm_binary).unwrap(); 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. // Load wasm binary and prepare it for instantiation.
let module = wasmi::Module::from_buffer(&wasm_binary).expect("failed to load wasm"); let module = wasmi::Module::from_buffer(&wasm_binary).expect("failed to load wasm");

View file

@ -0,0 +1,2 @@
[build]
target = "./json_targets/x86_64-ableos.json"

22
kernel/Cargo.lock generated Normal file
View file

@ -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"

15
kernel/Cargo.toml Normal file
View file

@ -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"

View file

@ -0,0 +1 @@
//!

View file

@ -1,3 +1,6 @@
//!
/// Character device interface.
pub trait CharacterDevice { pub trait CharacterDevice {
/// Returns true if the device can be read from. /// Returns true if the device can be read from.
fn can_read(&self) -> bool; fn can_read(&self) -> bool;
@ -7,4 +10,8 @@ pub trait CharacterDevice {
fn read_char(&mut self) -> Option<char>; fn read_char(&mut self) -> Option<char>;
/// Writes a single character to the device and returns true if the write was successful /// Writes a single character to the device and returns true if the write was successful
fn write_char(&mut self, c: char) -> bool; 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;
} }

View file

@ -0,0 +1,4 @@
//! Platform Agnostic Device
pub mod block;
pub mod character;

35
kernel/src/lib.rs Normal file
View file

@ -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,
};

67
kernel/src/messaging.rs Normal file
View file

@ -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,
}

12
kernel/src/panic.rs Normal file
View file

@ -0,0 +1,12 @@
//!
use core::panic::PanicInfo;
// #[macro_use]
// use log;
#[panic_handler]
fn panic_handler(_info: &PanicInfo) -> ! {
// error!("{}", _info);
loop {}
}

4
kernel/src/proccess.rs Normal file
View file

@ -0,0 +1,4 @@
//! Platform agnostic process
/// A process ID
pub type PID = u64;

10
kernel/src/time.rs Normal file
View file

@ -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,
}

View file

@ -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::{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 log::{debug, info};
use rhai::Engine; use rhai::Engine;
@ -7,13 +7,13 @@ use rhai::Engine;
pub fn engine_startup() -> Engine { pub fn engine_startup() -> Engine {
let mut engine = Engine::new(); 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 // Any function or closure that takes a '&str', an 'Option<&str>' and a 'Position' argument
// can be used to override 'debug'. // can be used to override 'debug'.
engine.on_debug(|x, src, pos| { engine.on_debug(|x, src, pos| {
let src = src.unwrap_or("unknown"); let src = src.unwrap_or("unknown");
// debug!("SHADER DEBUG of {} at {:?}: {}", src, pos, x) debug!("SHADER DEBUG of {} at {:?}: {}", src, pos, x);
}); });
engine engine

View file

@ -69,101 +69,101 @@ impl From<u8> for ChannelValue {
/* /*
pub fn into_vga_16(rgba_64: Rgba64) -> Color16 { pub fn into_vga_16(rgba_64: Rgba64) -> Color16 {
use ChannelValue::*; use ChannelValue::*;
use Color16::*; use Color16::*;
match ( match (
get_r(rgba_64).into(), get_r(rgba_64).into(),
get_g(rgba_64).into(), get_g(rgba_64).into(),
get_b(rgba_64).into(), get_b(rgba_64).into(),
) { ) {
(Dark, Dark, Dark) => Black, (Dark, Dark, Dark) => Black,
(Dark, Dark, Low) => Black, (Dark, Dark, Low) => Black,
(Dark, Dark, Mid) => Blue, (Dark, Dark, Mid) => Blue,
(Dark, Dark, High) => Blue, (Dark, Dark, High) => Blue,
(Dark, Low, Dark) => Black, (Dark, Low, Dark) => Black,
(Dark, Low, Low) => Black, (Dark, Low, Low) => Black,
(Dark, Low, Mid) => Blue, (Dark, Low, Mid) => Blue,
(Dark, Low, High) => Blue, (Dark, Low, High) => Blue,
(Dark, Mid, Dark) => Green, (Dark, Mid, Dark) => Green,
(Dark, Mid, Low) => Green, (Dark, Mid, Low) => Green,
(Dark, Mid, Mid) => Cyan, (Dark, Mid, Mid) => Cyan,
(Dark, Mid, High) => Cyan, (Dark, Mid, High) => Cyan,
(Dark, High, Dark) => Green, (Dark, High, Dark) => Green,
(Dark, High, Low) => Green, (Dark, High, Low) => Green,
(Dark, High, Mid) => Green, (Dark, High, Mid) => Green,
(Dark, High, High) => Cyan, (Dark, High, High) => Cyan,
(Low, Dark, Dark) => Black, (Low, Dark, Dark) => Black,
(Low, Dark, Low) => Black, (Low, Dark, Low) => Black,
(Low, Dark, Mid) => Blue, (Low, Dark, Mid) => Blue,
(Low, Dark, High) => Blue, (Low, Dark, High) => Blue,
(Low, Low, Dark) => Black, (Low, Low, Dark) => Black,
(Low, Low, Low) => DarkGrey, (Low, Low, Low) => DarkGrey,
(Low, Low, Mid) => LightGrey, (Low, Low, Mid) => LightGrey,
(Low, Low, High) => Blue, (Low, Low, High) => Blue,
(Low, Mid, Dark) => DarkGrey, (Low, Mid, Dark) => DarkGrey,
(Low, Mid, Low) => LightGrey, (Low, Mid, Low) => LightGrey,
(Low, Mid, Mid) => Cyan, (Low, Mid, Mid) => Cyan,
(Low, Mid, High) => Cyan, (Low, Mid, High) => Cyan,
(Low, High, Dark) => Green, (Low, High, Dark) => Green,
(Low, High, Low) => Green, (Low, High, Low) => Green,
(Low, High, Mid) => Cyan, (Low, High, Mid) => Cyan,
(Low, High, High) => Cyan, (Low, High, High) => Cyan,
(Mid, Dark, Dark) => Red, (Mid, Dark, Dark) => Red,
(Mid, Dark, Low) => Red, (Mid, Dark, Low) => Red,
(Mid, Dark, Mid) => Magenta, (Mid, Dark, Mid) => Magenta,
(Mid, Dark, High) => Magenta, (Mid, Dark, High) => Magenta,
(Mid, Low, Dark) => Brown, (Mid, Low, Dark) => Brown,
(Mid, Low, Low) => Red, (Mid, Low, Low) => Red,
(Mid, Low, Mid) => DarkGrey, (Mid, Low, Mid) => DarkGrey,
(Mid, Low, High) => LightBlue, (Mid, Low, High) => LightBlue,
(Mid, Mid, Dark) => Brown, (Mid, Mid, Dark) => Brown,
(Mid, Mid, Low) => Brown, (Mid, Mid, Low) => Brown,
(Mid, Mid, Mid) => LightGrey, (Mid, Mid, Mid) => LightGrey,
(Mid, Mid, High) => LightBlue, (Mid, Mid, High) => LightBlue,
(Mid, High, Dark) => Green, (Mid, High, Dark) => Green,
(Mid, High, Low) => Green, (Mid, High, Low) => Green,
(Mid, High, Mid) => LightGreen, (Mid, High, Mid) => LightGreen,
(Mid, High, High) => LightCyan, (Mid, High, High) => LightCyan,
(High, Dark, Dark) => Red, (High, Dark, Dark) => Red,
(High, Dark, _) => Magenta, (High, Dark, _) => Magenta,
(High, Low, Dark) => Red, (High, Low, Dark) => Red,
(High, Low, Low) => LightRed, (High, Low, Low) => LightRed,
(High, Low, Mid) => Pink, (High, Low, Mid) => Pink,
(High, Low, High) => Magenta, (High, Low, High) => Magenta,
(High, Mid, Dark) => Yellow, (High, Mid, Dark) => Yellow,
(High, Mid, Low) => Yellow, (High, Mid, Low) => Yellow,
(High, Mid, Mid) => LightRed, (High, Mid, Mid) => LightRed,
(High, Mid, High) => Pink, (High, Mid, High) => Pink,
(High, High, Dark) => Yellow, (High, High, Dark) => Yellow,
(High, High, Low) => White, (High, High, Low) => White,
(High, High, Mid) => White, (High, High, Mid) => White,
(High, High, High) => White, (High, High, High) => White,
} }
} }
pub fn from_vga_16(color: Color16) -> Rgba64 { pub fn from_vga_16(color: Color16) -> Rgba64 {
use Color16::*; use Color16::*;
match color { match color {
Black => new_rgba64(0, 0, 0, 0), Black => new_rgba64(0, 0, 0, 0),
DarkGrey => new_rgba64(105, 105, 105, 0), DarkGrey => new_rgba64(105, 105, 105, 0),
LightGrey => new_rgba64(211, 211, 211, 0), LightGrey => new_rgba64(211, 211, 211, 0),
// //
Blue => new_rgba64(0, 0, 0xff, 0), Blue => new_rgba64(0, 0, 0xff, 0),
Green => new_rgba64(0, 0xff, 0, 0), Green => new_rgba64(0, 0xff, 0, 0),
Red => new_rgba64(0xff, 0, 0, 0), Red => new_rgba64(0xff, 0, 0, 0),
// //
Yellow => new_rgba64(0xff, 0xff, 0, 0), Yellow => new_rgba64(0xff, 0xff, 0, 0),
Cyan => new_rgba64(0, 0xff, 0xff, 0), Cyan => new_rgba64(0, 0xff, 0xff, 0),
Magenta => new_rgba64(0xff, 0, 0xff, 0), Magenta => new_rgba64(0xff, 0, 0xff, 0),
Brown => new_rgba64(165, 42, 42, 0), Brown => new_rgba64(165, 42, 42, 0),
Pink => new_rgba64(0xff, 105, 180, 0), Pink => new_rgba64(0xff, 105, 180, 0),
White => new_rgba64(0xff, 0xff, 0xff, 0), White => new_rgba64(0xff, 0xff, 0xff, 0),
LightBlue => new_rgba64(173, 216, 230, 0), LightBlue => new_rgba64(173, 216, 230, 0),
LightGreen => new_rgba64(144, 238, 144, 0), LightGreen => new_rgba64(144, 238, 144, 0),
LightCyan => new_rgba64(88, 100, 100, 0), LightCyan => new_rgba64(88, 100, 100, 0),
LightRed => new_rgba64(0xff, 204, 203, 0), LightRed => new_rgba64(0xff, 204, 203, 0),
} }
} }
*/ */

View file

@ -12,4 +12,4 @@ dependencies = [
[[package]] [[package]]
name = "libwasm" name = "libwasm"
version = "0.1.0" version = "0.1.0"
source = "git+https://git.ablecorp.us/able/libwasm.git#502187e8734b54df3c6cae2baf2315539a3ec49b" source = "git+https://git.ablecorp.us/able/libwasm.git#dedbb769ba01a4b75992437e52ca9a5c2bb9e0f9"

View file

@ -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

View file

@ -1,12 +1,36 @@
#![no_std] #![no_std]
#![no_main] #![no_main]
#![deny(improper_ctypes)]
#[no_mangle] #[no_mangle]
fn start() -> i32 { fn start() -> i32 {
let ret = unsafe { add(1, 2) }; let ret = unsafe { add(1, 2) };
unsafe {
send_signal(PID(1), Signals::Quit);
}
ret as i32 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;

Binary file not shown.

75
userland/wasm_pk_data/Cargo.lock generated Normal file
View file

@ -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",
]

View file

@ -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"]

View file

@ -0,0 +1,3 @@
name = "bruh"
version = [1233, 123, 123]
authors = ["John Doe", "Jane Doe"]

View file

@ -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<String>,
}