Compare commits
19 Commits
huge_refactor
..
dev
| Author | SHA1 | Date | |
|---|---|---|---|
| ecdc76b068 | |||
| 8ee4af1a48 | |||
| 03c07cb5c4 | |||
| ef70bcf51e | |||
| 2fb1741100 | |||
| af995d1d76 | |||
| 014ec5310c | |||
| d53661b9a0 | |||
| 8704b5d249 | |||
| 2186b829aa | |||
| f502104a6e | |||
| 48dcde0c02 | |||
| 6e913b15d7 | |||
| 0a5269eeb0 | |||
| a0f5ce8797 | |||
| 2d3bc56962 | |||
| 5703032f87 | |||
| 3966e697da | |||
| e8237f4610 |
Generated
+1
@@ -6,6 +6,7 @@
|
||||
<sourceFolder url="file://$MODULE_DIR$/lib_example/src" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/libk/src" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/libm/src" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/kernel_fonts/src" isTestSource="false" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/target" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
|
||||
Generated
+5
@@ -0,0 +1,5 @@
|
||||
<component name="ProjectCodeStyleConfiguration">
|
||||
<state>
|
||||
<option name="PREFERRED_PROJECT_CODE_STYLE" value="Default" />
|
||||
</state>
|
||||
</component>
|
||||
Vendored
-1
@@ -6,6 +6,5 @@
|
||||
"editor.formatOnSave": true
|
||||
},
|
||||
"rust-analyzer.check.command": "clippy",
|
||||
"rust-analyzer.procMacro.attributes.enable": true,
|
||||
"rust-analyzer.cargo.buildScripts.enable": true
|
||||
}
|
||||
Generated
+45
-2
@@ -22,9 +22,9 @@ checksum = "8f68f53c83ab957f72c32642f3868eec03eb974d1fb82e453128456482613d36"
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.2.16"
|
||||
version = "1.2.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "be714c154be609ec7f5dad223a33bf1482fff90472de28f7362806e6d4832b8c"
|
||||
checksum = "c736e259eea577f443d5c86c304f9f4ae0295c43f3ba05c21f1d66b5f06001af"
|
||||
dependencies = [
|
||||
"shlex",
|
||||
]
|
||||
@@ -35,10 +35,20 @@ version = "0.8.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1137cd7e7fc0fb5d3c5a8678be38ec56e819125d8d7907411fe24ccb943faca8"
|
||||
dependencies = [
|
||||
"crossbeam-epoch",
|
||||
"crossbeam-queue",
|
||||
"crossbeam-utils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-epoch"
|
||||
version = "0.9.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e"
|
||||
dependencies = [
|
||||
"crossbeam-utils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-queue"
|
||||
version = "0.3.12"
|
||||
@@ -89,6 +99,12 @@ dependencies = [
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "elf"
|
||||
version = "0.7.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4445909572dbd556c457c849c4ca58623d84b27c8fff1e74b0b4227d8b90d17b"
|
||||
|
||||
[[package]]
|
||||
name = "fnv"
|
||||
version = "1.0.7"
|
||||
@@ -101,9 +117,12 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"crossbeam",
|
||||
"elf",
|
||||
"futures-util",
|
||||
"gimli",
|
||||
"libm",
|
||||
"limine",
|
||||
"linked_list_allocator",
|
||||
"pc-keyboard",
|
||||
"pic8259",
|
||||
"spin",
|
||||
@@ -134,6 +153,12 @@ dependencies = [
|
||||
"pin-utils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gimli"
|
||||
version = "0.31.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f"
|
||||
|
||||
[[package]]
|
||||
name = "ident_case"
|
||||
version = "1.0.1"
|
||||
@@ -159,6 +184,15 @@ dependencies = [
|
||||
"bitflags",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "linked_list_allocator"
|
||||
version = "0.10.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9afa463f5405ee81cdb9cc2baf37e08ec7e4c8209442b5d72c04cfb2cd6e6286"
|
||||
dependencies = [
|
||||
"spinning_top",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lock_api"
|
||||
version = "0.4.12"
|
||||
@@ -241,6 +275,15 @@ dependencies = [
|
||||
"lock_api",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "spinning_top"
|
||||
version = "0.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5b9eb1a2f4c41445a3a0ff9abc5221c5fcd28e1f13cd7c0397706f9ac938ddb0"
|
||||
dependencies = [
|
||||
"lock_api",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "strsim"
|
||||
version = "0.11.1"
|
||||
|
||||
+11
-10
@@ -6,17 +6,18 @@
|
||||
> - [ ] figure out how to run QEMU in the test environment
|
||||
> - [ ] write a script to run tests
|
||||
> - [ ] a release should only be published if all tests pass
|
||||
>
|
||||
> [!todo] HAL (Hardware Abstraction Layer)
|
||||
> - [ ] use either traits or cfg attributes to support more than just x86_64
|
||||
> - [ ] prefer writing cross platform code (I am aware I made the problem slightly worse by merging libk with the kernel sources)
|
||||
>
|
||||
|
||||
> [!todo] Memory
|
||||
> - [ ] make sure page tables are correct. we're still getting the annoying page fault errors for the APIC
|
||||
> - [ ] page allocator
|
||||
> - [ ] e
|
||||
|
||||
> [!todo] Allocator
|
||||
> - [ ] learn about several allocator designs and decide on the optimal one
|
||||
> - [ ] implementation
|
||||
> - [ ] implement an allocate method
|
||||
> - [ ] implement a deallocate method
|
||||
> - [ ] set the global allocator
|
||||
> - [x] learn about several allocator designs and decide on the optimal one
|
||||
> - [x] implementation
|
||||
> - [x] implement an allocate method
|
||||
> - [x] implement a deallocate method
|
||||
> - [x] set the global allocator
|
||||
> - [ ] testing
|
||||
> - [ ] write unit tests
|
||||
> - [ ] many allocations
|
||||
|
||||
+6
-4
@@ -6,19 +6,21 @@ authors.workspace = true
|
||||
|
||||
[dependencies]
|
||||
limine = "0.3.1"
|
||||
# libk = { path = "../libk" }
|
||||
x86_64 = "0.15.2"
|
||||
spin = "0.9.8"
|
||||
pic8259 = "0.11.0"
|
||||
pc-keyboard = "0.8.0"
|
||||
libm = { version = "0.1.0", path = "../libm" }
|
||||
libm = { path = "../libm" }
|
||||
crossbeam = { version = "0.8.4", default-features = false, features = [
|
||||
# "alloc",
|
||||
"alloc",
|
||||
"crossbeam-queue",
|
||||
] }
|
||||
futures-util = { version = "0.3.31", default-features = false, features = [
|
||||
# "alloc",
|
||||
"alloc",
|
||||
] }
|
||||
linked_list_allocator = { version = "0.10.5", features = ["use_spin"] }
|
||||
gimli = { version = "0.31.1", default-features = false, features = ["read"] }
|
||||
elf = { version = "0.7.4", default-features = false, features = ["nightly"] }
|
||||
|
||||
[build-dependencies]
|
||||
cc = "1.2.14"
|
||||
|
||||
+1
-2
@@ -62,9 +62,8 @@ SECTIONS
|
||||
*(COMMON)
|
||||
} :data
|
||||
|
||||
/* Discard .note.* and .eh_frame* since they may cause issues on some hosts. */
|
||||
/* Discard .note.* and ~~.eh_frame*~~ since they may cause issues on some hosts. */
|
||||
/DISCARD/ : {
|
||||
*(.eh_frame*)
|
||||
*(.note .note.*)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
#![expect(unused)]
|
||||
use core::arch::x86_64::__cpuid;
|
||||
|
||||
use spin::Lazy;
|
||||
// use libk::drivers::memory::{FRAME_ALLOCATOR, FoundryOSFrameAllocator,
|
||||
// OFFSET_PAGE_TABLE};
|
||||
use x86_64::{
|
||||
PhysAddr, VirtAddr,
|
||||
structures::paging::{Page, PageTableFlags, PhysFrame, Size4KiB},
|
||||
};
|
||||
|
||||
// use crate::serial_print;
|
||||
|
||||
use super::{cpu::msr::*, memmap::PHYSICAL_MEMORY_OFFSET};
|
||||
|
||||
const IA32_APIC_BASE_MSR: u32 = 0x1b;
|
||||
const IA32_APIC_BASE_MSR_BSP: u64 = 0x100;
|
||||
const IA32_APIC_BASE_MSR_ENABLE: u64 = 0x800;
|
||||
const IA32_APIC_BASE_MSR_DISABLE: u64 = !IA32_APIC_BASE_MSR_ENABLE;
|
||||
|
||||
const CPUID_FEAT_EDX_APIC: u64 = 1 << 9; // the cpuid instruction will return this flag if it supports APIC
|
||||
|
||||
static APIC_VIRTUAL_ADDRESS: Lazy<VirtAddr> = Lazy::new(|| {
|
||||
let apic_base = get_apic_base();
|
||||
|
||||
unsafe { phys_to_virt(apic_base) }
|
||||
});
|
||||
|
||||
fn set_apic_base_enable(apic: PhysAddr) {
|
||||
let rax = (apic.as_u64() & 0xfffff0000) | IA32_APIC_BASE_MSR_ENABLE;
|
||||
cpu_set_msr(IA32_APIC_BASE_MSR, rax);
|
||||
}
|
||||
|
||||
fn set_apic_base_disable(apic: PhysAddr) {
|
||||
let rax = (apic.as_u64() & 0xfffff0000) & IA32_APIC_BASE_MSR_DISABLE;
|
||||
cpu_set_msr(IA32_APIC_BASE_MSR, rax);
|
||||
}
|
||||
|
||||
fn get_apic_base() -> PhysAddr {
|
||||
let mut value: u64 = 0;
|
||||
cpu_get_msr(IA32_APIC_BASE_MSR, &mut value);
|
||||
PhysAddr::new(value & 0xfffff0000)
|
||||
}
|
||||
|
||||
fn write_apic_register(apic_base: &VirtAddr, reg: u8, value: u32) {
|
||||
let apic_base = apic_base.as_u64();
|
||||
let reg_addr = (apic_base & 0xFFFFF0000) + reg as u64;
|
||||
unsafe { *(reg_addr as *mut u32) = value };
|
||||
}
|
||||
|
||||
const fn read_apic_register(apic_base: &VirtAddr, reg: u8) -> u32 {
|
||||
let apic_base = apic_base.as_u64();
|
||||
|
||||
// serial_print!("got apic base");
|
||||
|
||||
let reg_addr = (apic_base & 0xFFFFF0000) + reg as u64;
|
||||
unsafe { *(reg_addr as *const u32) }
|
||||
}
|
||||
|
||||
pub fn check_apic() -> bool {
|
||||
let res = unsafe { __cpuid(1) };
|
||||
res.edx as u64 & CPUID_FEAT_EDX_APIC != 0
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
unsafe fn phys_to_virt(phys: PhysAddr) -> VirtAddr {
|
||||
let phys = phys.as_u64();
|
||||
phys.checked_add(*PHYSICAL_MEMORY_OFFSET)
|
||||
.map_or_else(|| panic!(" overflow"), VirtAddr::new)
|
||||
}
|
||||
|
||||
pub fn enable_apic() {
|
||||
// let mut mapper = OFFSET_PAGE_TABLE.get().unwrap().lock();
|
||||
// let mut frame_allocator = FRAME_ALLOCATOR.get().unwrap().lock();
|
||||
|
||||
let apic_phys_addr = get_apic_base();
|
||||
set_apic_base_enable(apic_phys_addr);
|
||||
// map virt address of apic
|
||||
|
||||
let apic_virt = unsafe { phys_to_virt(apic_phys_addr) };
|
||||
let page: Page<Size4KiB> = Page::containing_address(apic_virt);
|
||||
let frame: PhysFrame<Size4KiB> = PhysFrame::containing_address(apic_phys_addr);
|
||||
let flags: PageTableFlags = PageTableFlags::PRESENT | PageTableFlags::WRITABLE;
|
||||
|
||||
/* unsafe {
|
||||
match mapper.map_to(page, frame, flags, &mut *frame_allocator) {
|
||||
Ok(_) => {}
|
||||
Err(why) => panic!("failed to map apic: {:?}", why),
|
||||
}
|
||||
}
|
||||
*/
|
||||
// // FIXME: this causes a page fault
|
||||
// // TODO: map to virtual memor
|
||||
|
||||
let reg = read_apic_register(&APIC_VIRTUAL_ADDRESS, 0xF0);
|
||||
|
||||
// serial_print!("ok2");
|
||||
|
||||
write_apic_register(&apic_virt, 0xF0, reg | 0x100);
|
||||
}
|
||||
|
||||
pub struct Apic {}
|
||||
|
||||
pub enum ApicVector {}
|
||||
@@ -0,0 +1,100 @@
|
||||
#![expect(unused)]
|
||||
|
||||
use core::arch::x86_64::__cpuid;
|
||||
|
||||
use crate::arch::x86_64::memory::mapping::PHYSICAL_MEMORY_OFFSET;
|
||||
use crate::{debugln, serial_print, serial_println};
|
||||
use x86_64::{
|
||||
PhysAddr, VirtAddr,
|
||||
structures::paging::{Mapper, Page, PageTableFlags, PhysFrame, Size4KiB},
|
||||
};
|
||||
use x86_64::structures::paging::Translate;
|
||||
use crate::arch::x86_64::cpu::msr::*;
|
||||
use crate::arch::x86_64::memory::{FRAME_ALLOCATOR, OFFSET_PAGE_TABLE};
|
||||
|
||||
const IA32_APIC_BASE_MSR: u32 = 0x1b;
|
||||
const IA32_APIC_BASE_MSR_BSP: u64 = 0x100;
|
||||
const IA32_APIC_BASE_MSR_ENABLE: u64 = 0x800;
|
||||
const IA32_APIC_BASE_MSR_DISABLE: u64 = !IA32_APIC_BASE_MSR_ENABLE;
|
||||
|
||||
const CPUID_FEAT_EDX_APIC: u64 = 1 << 9; // the cpuid instruction will return this flag if it supports APIC
|
||||
|
||||
// const APIC_VIRTUAL_ADDRESS: Lazy<VirtAddr> = Lazy::new(|| {
|
||||
// let apic_base = get_apic_base();
|
||||
// let virt_addr = unsafe { phys_to_virt(apic_base) };
|
||||
|
||||
// virt_addr
|
||||
// });
|
||||
|
||||
fn set_apic_base_enable(apic: PhysAddr) {
|
||||
let rax = (apic.as_u64() & 0xfffff0000) | IA32_APIC_BASE_MSR_ENABLE;
|
||||
debugln!("apic {:?}", PhysAddr::new(rax));
|
||||
cpu_set_msr(IA32_APIC_BASE_MSR, rax);
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
fn set_apic_base_disable(apic: PhysAddr) {
|
||||
let rax = (apic.as_u64() & 0xfffff0000) & IA32_APIC_BASE_MSR_DISABLE;
|
||||
cpu_set_msr(IA32_APIC_BASE_MSR, rax);
|
||||
}
|
||||
|
||||
fn get_apic_base() -> PhysAddr {
|
||||
let mut value: u64 = 0;
|
||||
cpu_get_msr(IA32_APIC_BASE_MSR, &mut value);
|
||||
|
||||
debugln!("apic base {:#x}", value);
|
||||
|
||||
PhysAddr::new(value & 0xfffff0000)
|
||||
}
|
||||
|
||||
fn write_apic_register(apic_base: &PhysAddr, reg: u64, value: u32) {
|
||||
let apic_base = apic_base.as_u64();
|
||||
let reg_addr = (apic_base & 0xFFFFF0000) + reg;
|
||||
|
||||
let virt_addr = unsafe { phys_to_virt(PhysAddr::new(reg_addr)) };
|
||||
|
||||
let phys_check = OFFSET_PAGE_TABLE.get().unwrap().lock().translate(virt_addr);
|
||||
debugln!("{:?}", phys_check);
|
||||
|
||||
unsafe { *(virt_addr.as_u64() as *mut u32) = value };
|
||||
}
|
||||
|
||||
fn read_apic_register(apic_base: &PhysAddr, reg: u64) -> u32 {
|
||||
let apic_base = apic_base.as_u64();
|
||||
let reg_addr = (apic_base & 0xFFFFF0000) + reg;
|
||||
let virt_addr = unsafe { phys_to_virt(PhysAddr::new(reg_addr)) };
|
||||
unsafe { *(virt_addr.as_u64() as *const u32) }
|
||||
}
|
||||
|
||||
pub fn check_apic() -> bool {
|
||||
let res = unsafe { __cpuid(1) };
|
||||
res.edx as u64 & CPUID_FEAT_EDX_APIC != 0
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
unsafe fn phys_to_virt(phys: PhysAddr) -> VirtAddr {
|
||||
let phys = phys.as_u64();
|
||||
phys.checked_add(*PHYSICAL_MEMORY_OFFSET)
|
||||
.map_or_else(|| panic!(" overflow"), VirtAddr::new)
|
||||
}
|
||||
|
||||
pub fn enable_apic() {
|
||||
let apic_base_physical_addr = get_apic_base();
|
||||
set_apic_base_enable(apic_base_physical_addr);
|
||||
|
||||
debugln!("{:?}", apic_base_physical_addr);
|
||||
enable_timer();
|
||||
|
||||
write_apic_register(
|
||||
&apic_base_physical_addr,
|
||||
0xF0,
|
||||
read_apic_register(&apic_base_physical_addr, 0xF0) | 0x1FF
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
pub fn enable_timer() {
|
||||
let apic_base = get_apic_base();
|
||||
let current = read_apic_register(&apic_base, 0x320);
|
||||
write_apic_register(&get_apic_base(), 0x320, (current & 0xFFFFFF00) | 0x20);
|
||||
}
|
||||
@@ -1,2 +1,3 @@
|
||||
pub mod msr;
|
||||
pub mod port;
|
||||
pub mod apic;
|
||||
mod msr;
|
||||
pub mod pic;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
#![expect(unused)]
|
||||
use core::arch::x86_64::__cpuid;
|
||||
use spin::Lazy;
|
||||
use x86_64::registers::model_specific::Msr;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#![allow(clippy::missing_safety_doc)]
|
||||
|
||||
use x86_64::instructions::port::Port;
|
||||
|
||||
const CMD_INIT: u8 = 0x11;
|
||||
@@ -41,8 +42,15 @@ pub struct ChainedPics {
|
||||
}
|
||||
|
||||
impl ChainedPics {
|
||||
/// Creates a new [`ChainedPics`].
|
||||
pub const fn new(offset1: u8, offset2: u8) -> Self {
|
||||
/// Construct a new `ChainedPics` given the base offsets of the two PICs.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// This function is unsafe because it requires you to pass valid offsets.
|
||||
/// If you pass offsets that are out of range, or if you pass offsets that
|
||||
/// conflict with one another, the resulting object will be useless and
|
||||
/// will likely cause problems for your system.
|
||||
pub const unsafe fn new(offset1: u8, offset2: u8) -> Self {
|
||||
Self {
|
||||
pics: [
|
||||
Pic {
|
||||
@@ -59,15 +67,20 @@ impl ChainedPics {
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn new_contiguous(primary_offset: u8) -> Self {
|
||||
Self::new(primary_offset, primary_offset + 8)
|
||||
}
|
||||
|
||||
/// Returns the initialize of this [`ChainedPics`].
|
||||
/// .
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// .
|
||||
pub const unsafe fn new_contiguous(primary_offset: u8) -> Self {
|
||||
unsafe { Self::new(primary_offset, primary_offset + 8) }
|
||||
}
|
||||
|
||||
/// Returns a new instance of [`ChainedPics`].
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// this is unsafe because it required writing to CPU I/O ports.
|
||||
pub unsafe fn initialize(&mut self) {
|
||||
unsafe {
|
||||
let mut wait_port: Port<u8> = Port::new(0x80);
|
||||
@@ -1,2 +0,0 @@
|
||||
pub mod pic;
|
||||
pub mod serial;
|
||||
@@ -1,16 +1,18 @@
|
||||
//! Formerly called ascii.rs, this file defines helper functions for drawing
|
||||
//! characters to the screen.
|
||||
|
||||
use core::fmt;
|
||||
use spin::{Lazy, Mutex};
|
||||
use x86_64::instructions::interrupts;
|
||||
|
||||
use super::{colour::Colour, font::Font, framebuffer::FRAMEBUFFER_WRITER};
|
||||
use crate::arch::x86_64::drivers::framebuffer::{
|
||||
colour::Colour, display::FRAMEBUFFER_WRITER,
|
||||
};
|
||||
|
||||
use crate::resources::font::{FONT_SPLEEN_8X16, Font};
|
||||
|
||||
static FONT_WIDTH: u32 = 8;
|
||||
static FONT_HEIGHT: u32 = 16;
|
||||
|
||||
pub static WRITER: Lazy<Mutex<Writer>> = Lazy::new(|| Mutex::new(Writer::new()));
|
||||
pub static WRITER: Lazy<Mutex<Writer>> =
|
||||
Lazy::new(|| Mutex::new(Writer::new()));
|
||||
|
||||
pub fn screensize_chars() -> (u32, u32) {
|
||||
let writer = WRITER.lock();
|
||||
@@ -45,7 +47,7 @@ impl Writer {
|
||||
panic!("Framebuffer writer not initialized.");
|
||||
},
|
||||
|writer| Self {
|
||||
font: &crate::DEFAULT_FONT,
|
||||
font: &FONT_SPLEEN_8X16,
|
||||
screen_width: writer.width() / 8,
|
||||
screen_height: writer.height() / 16,
|
||||
text_line: 0,
|
||||
@@ -80,7 +82,8 @@ impl Writer {
|
||||
for (row, line) in data.iter().enumerate().take(16) {
|
||||
for col in 0..8 {
|
||||
let pixel_x: u32 = self.text_col * FONT_WIDTH + col;
|
||||
let pixel_y: u32 = self.text_line * FONT_HEIGHT + row as u32;
|
||||
let pixel_y: u32 =
|
||||
self.text_line * FONT_HEIGHT + row as u32;
|
||||
|
||||
if line & (0x80 >> col) != 0 {
|
||||
// Write the foreground color
|
||||
@@ -155,7 +158,7 @@ impl Writer {
|
||||
}
|
||||
}
|
||||
|
||||
impl core::fmt::Write for Writer {
|
||||
impl fmt::Write for Writer {
|
||||
fn write_str(&mut self, s: &str) -> core::fmt::Result {
|
||||
self.write_string(s);
|
||||
Ok(())
|
||||
@@ -173,23 +176,20 @@ fn write(args: fmt::Arguments, fg: Colour, bg: Colour) {
|
||||
});
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub fn _print(args: fmt::Arguments) {
|
||||
x86_64::instructions::interrupts::without_interrupts(|| {
|
||||
interrupts::without_interrupts(|| {
|
||||
write(args, Colour::White, Colour::Black);
|
||||
})
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub fn _print_err(args: fmt::Arguments) {
|
||||
x86_64::instructions::interrupts::without_interrupts(|| {
|
||||
interrupts::without_interrupts(|| {
|
||||
write(args, Colour::Red, Colour::Black);
|
||||
})
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub fn _print_log(args: fmt::Arguments) {
|
||||
x86_64::instructions::interrupts::without_interrupts(|| {
|
||||
interrupts::without_interrupts(|| {
|
||||
write(args, Colour::Yellow, Colour::Black);
|
||||
})
|
||||
}
|
||||
@@ -216,33 +216,33 @@ pub fn reset_cursor() {
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! println_log {
|
||||
() => ($crate::print_log!("\n"));
|
||||
($($arg:tt)*) => ($crate::print_log!("{}\n", format_args!($($arg)*)));
|
||||
() => ($crate::print_log!("\n"));
|
||||
($($arg:tt)*) => ($crate::print_log!("{}\n", format_args!($($arg)*)));
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! print_log {
|
||||
($($arg:tt)*) => ($crate::graphics::writer::_print_log(format_args!($($arg)*)));
|
||||
($($arg:tt)*) => ($crate::prelude::_print_log(format_args!($($arg)*)));
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! println {
|
||||
() => ($crate::print!("\n"));
|
||||
($($arg:tt)*) => ($crate::print!("{}\n", format_args!($($arg)*)));
|
||||
() => ($crate::print!("\n"));
|
||||
($($arg:tt)*) => ($crate::print!("{}\n", format_args!($($arg)*)));
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! print {
|
||||
($($arg:tt)*) => ($crate::graphics::writer::_print(format_args!($($arg)*)));
|
||||
($($arg:tt)*) => ($crate::prelude::_print(format_args!($($arg)*)));
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! printlnerr {
|
||||
macro_rules! eprintln {
|
||||
() => ($crate::printerr!("\n"));
|
||||
($($arg:tt)*) => ($crate::printerr!("{}\n", format_args!($($arg)*)));
|
||||
($($arg:tt)*) => ($crate::eprint!("{}\n", format_args!($($arg)*)));
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! printerr {
|
||||
($($arg:tt)*) => ($crate::graphics::writer::_print_err(format_args!($($arg)*)));
|
||||
macro_rules! eprint {
|
||||
($($arg:tt)*) => ($crate::prelude::_print_err(format_args!($($arg)*)));
|
||||
}
|
||||
+11
-14
@@ -1,11 +1,8 @@
|
||||
#[repr(u32)]
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
|
||||
// Some predefined colours as well as custom colours in the proper format. This
|
||||
// assumes that the framebuffer uses 32bpp, something which we will assert on
|
||||
// initialisation.
|
||||
pub enum Colour {
|
||||
Argb(u8, u8, u8, u8),
|
||||
Rgb(u8, u8, u8),
|
||||
ARGB(u8, u8, u8, u8),
|
||||
RGB(u8, u8, u8),
|
||||
HexARGB(u32),
|
||||
Black = 0x000000FF,
|
||||
Blue = 0x0000FFFF,
|
||||
@@ -17,17 +14,17 @@ pub enum Colour {
|
||||
White = 0xFFFFFFFF,
|
||||
}
|
||||
|
||||
#[expect(
|
||||
clippy::use_self,
|
||||
reason = "Self is uglier and more verbose than `u32`"
|
||||
)]
|
||||
#[allow(clippy::use_self)]
|
||||
impl From<Colour> for u32 {
|
||||
fn from(val: Colour) -> Self {
|
||||
match val {
|
||||
Colour::Argb(a, r, g, b) => {
|
||||
(a as u32) << 24 | (r as u32) << 16 | (g as u32) << 8 | (b as u32)
|
||||
Colour::ARGB(a, r, g, b) => {
|
||||
(a as u32) << 24
|
||||
| (r as u32) << 16
|
||||
| (g as u32) << 8
|
||||
| (b as u32)
|
||||
}
|
||||
Colour::Rgb(r, g, b) => {
|
||||
Colour::RGB(r, g, b) => {
|
||||
((r as u32) << 16) | (g as u32) << 8 | (b as u32)
|
||||
}
|
||||
Colour::HexARGB(hex) => hex,
|
||||
@@ -46,10 +43,10 @@ impl From<Colour> for u32 {
|
||||
impl core::fmt::Display for Colour {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
match self {
|
||||
Self::Argb(r, g, b, a) => {
|
||||
Self::ARGB(r, g, b, a) => {
|
||||
write!(f, "RGBA(#{:x}{:x}{:x}{:x})", r, g, b, a)
|
||||
}
|
||||
Self::Rgb(r, g, b) => write!(f, "RGB(#{:x}{:x}{:x})", r, g, b),
|
||||
Self::RGB(r, g, b) => write!(f, "RGB(#{:x}{:x}{:x})", r, g, b),
|
||||
Self::HexARGB(hex) => write!(f, "Hex(#{:x})", hex),
|
||||
Self::Black => write!(f, "Black"),
|
||||
Self::Blue => write!(f, "Blue"),
|
||||
@@ -0,0 +1,107 @@
|
||||
use limine::request::FramebufferRequest;
|
||||
|
||||
#[used]
|
||||
#[unsafe(link_section = ".requests")]
|
||||
static FRAMEBUFFER_REQUEST: FramebufferRequest = FramebufferRequest::new();
|
||||
|
||||
use super::colour::Colour;
|
||||
use core::panic;
|
||||
|
||||
use limine::framebuffer::Framebuffer;
|
||||
use spin::{Lazy, Mutex};
|
||||
|
||||
pub static FRAMEBUFFER_WRITER: Lazy<Mutex<Option<FramebufferWriter>>> =
|
||||
Lazy::new(|| {
|
||||
Mutex::new(FRAMEBUFFER_REQUEST.get_response().map_or_else(
|
||||
|| {
|
||||
panic!("Framebuffer request failed");
|
||||
},
|
||||
|framebuffer_response| {
|
||||
let framebuffer =
|
||||
framebuffer_response.framebuffers().next().unwrap();
|
||||
Some(FramebufferWriter::new(framebuffer))
|
||||
},
|
||||
))
|
||||
});
|
||||
|
||||
/// The updated writer stores necessary fields from the [Framebuffer].
|
||||
/// This ensures that the contained types are Send, as Framebuffer was
|
||||
/// not marked as Send.
|
||||
///
|
||||
/// It also avoids the requirement for lifetimes.
|
||||
///
|
||||
/// Note this does not implement Writer as these functions only handle drawing
|
||||
/// pixels.
|
||||
pub struct FramebufferWriter {
|
||||
pitch: u64,
|
||||
bpp: u16,
|
||||
addr: *mut u8,
|
||||
width: u64,
|
||||
height: u64,
|
||||
}
|
||||
|
||||
unsafe impl Send for FramebufferWriter {}
|
||||
unsafe impl Sync for FramebufferWriter {}
|
||||
|
||||
impl FramebufferWriter {
|
||||
pub fn new(framebuffer: Framebuffer) -> Self {
|
||||
Self {
|
||||
pitch: framebuffer.pitch(),
|
||||
bpp: framebuffer.bpp(),
|
||||
addr: framebuffer.addr(),
|
||||
width: framebuffer.width(),
|
||||
height: framebuffer.height(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn write_pixel(&self, x: usize, y: usize, color: Colour) {
|
||||
let pitch = self.pitch as usize;
|
||||
let bpp = (self.bpp / 8) as usize;
|
||||
let pixel_offset = y * pitch + x * bpp;
|
||||
|
||||
unsafe {
|
||||
*(self.addr.add(pixel_offset) as *mut u32) = color.into();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn render_frame(&self, buffer: &[&[Colour]]) {
|
||||
// TODO: this should return errors
|
||||
for (y, &row) in buffer.iter().enumerate() {
|
||||
if y >= self.height() as usize {
|
||||
break;
|
||||
}
|
||||
for (x, pixel) in row.iter().enumerate() {
|
||||
if x >= self.width() as usize {
|
||||
break;
|
||||
}
|
||||
self.write_pixel(x, y, *pixel);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn width(&self) -> u32 {
|
||||
self.width as u32
|
||||
}
|
||||
|
||||
pub const fn height(&self) -> u32 {
|
||||
self.height as u32
|
||||
}
|
||||
|
||||
pub fn clear(&self) {
|
||||
let width = self.width as usize;
|
||||
let height = self.height as usize;
|
||||
|
||||
for y in 0..height {
|
||||
for x in 0..width {
|
||||
self.write_pixel(x, y, Colour::Black);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn screensize_px() -> (u32, u32) {
|
||||
FRAMEBUFFER_WRITER
|
||||
.lock()
|
||||
.as_mut()
|
||||
.map_or_else(|| (0, 0), |writer| (writer.width(), writer.height()))
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
pub mod colour;
|
||||
pub mod display;
|
||||
@@ -3,11 +3,12 @@ use core::{
|
||||
task::{Context, Poll},
|
||||
};
|
||||
|
||||
use crate::println;
|
||||
use crossbeam::queue::ArrayQueue;
|
||||
use futures_util::{Stream, StreamExt, task::AtomicWaker};
|
||||
use pc_keyboard::{
|
||||
DecodedKey, HandleControl, KeyCode, Keyboard, ScancodeSet1,
|
||||
layouts::{self, Uk105Key},
|
||||
layouts::Uk105Key,
|
||||
};
|
||||
use spin::{Lazy, Mutex, Once};
|
||||
|
||||
@@ -19,7 +20,7 @@ pub static KEYBOARD: Lazy<Mutex<Keyboard<Uk105Key, ScancodeSet1>>> =
|
||||
Mutex::new(Keyboard::new(
|
||||
ScancodeSet1::new(),
|
||||
// TODO: Expose an API to change the default KB layout.
|
||||
layouts::Uk105Key,
|
||||
Uk105Key,
|
||||
HandleControl::Ignore,
|
||||
))
|
||||
});
|
||||
@@ -29,13 +30,12 @@ pub static SCANCODE_STREAM: Lazy<Mutex<ScancodeStream>> =
|
||||
pub fn add_scancode(scancode: u8) {
|
||||
if let Some(queue) = KBD_QUEUE.get() {
|
||||
if queue.push(scancode).is_err() {
|
||||
// println!("WARNING: scancode queue full; dropping keyboard
|
||||
// input");
|
||||
println!("WARNING: scancode queue full; dropping keyboard input");
|
||||
} else {
|
||||
WAKER.wake();
|
||||
}
|
||||
} else {
|
||||
// println!("WARNING: scancode queue not initialized");
|
||||
println!("WARNING: scancode queue not initialized");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
pub mod ascii;
|
||||
pub mod framebuffer;
|
||||
pub mod keyboard;
|
||||
pub mod port;
|
||||
pub mod serial;
|
||||
@@ -1,13 +1,9 @@
|
||||
//! Functions for IO using ports.
|
||||
|
||||
use core::arch::asm;
|
||||
|
||||
/// Take a byte in from a port.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// This might have side effects so it is marked unsafe just in case.
|
||||
#[inline(always)]
|
||||
pub unsafe fn inb(port: u16) -> u8 {
|
||||
#[inline]
|
||||
pub fn inb(port: u16) -> u8 {
|
||||
let value: u8;
|
||||
unsafe {
|
||||
asm!(
|
||||
@@ -20,13 +16,8 @@ pub unsafe fn inb(port: u16) -> u8 {
|
||||
value
|
||||
}
|
||||
|
||||
/// Take a byte in from a port.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// This might have side effects so it is marked unsafe just in case.
|
||||
#[inline(always)]
|
||||
pub unsafe fn outb(port: u16, value: u8) {
|
||||
#[inline]
|
||||
pub fn outb(port: u16, value: u8) {
|
||||
unsafe {
|
||||
asm!(
|
||||
"out dx, al",
|
||||
@@ -1,14 +1,12 @@
|
||||
use crate::arch::x86_64::cpu::port::{inb, outb};
|
||||
use core::{
|
||||
fmt,
|
||||
sync::atomic::{AtomicUsize, Ordering},
|
||||
};
|
||||
use spin::{Lazy, Mutex};
|
||||
use x86_64::instructions::interrupts;
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! serial_print {
|
||||
($($arg:tt)*) => ($crate::arch::x86_64::dev::serial::_serial_write(format_args!($($arg)*)));
|
||||
($($arg:tt)*) => ($crate::_serial_write(format_args!($($arg)*)));
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
@@ -17,6 +15,10 @@ macro_rules! serial_println {
|
||||
($($arg:tt)*) => (serial_print!("{}\n", format_args!($($arg)*)));
|
||||
}
|
||||
|
||||
use crate::arch::x86_64::drivers::port::{inb, outb};
|
||||
|
||||
use x86_64::instructions::interrupts;
|
||||
|
||||
pub fn _serial_write(args: fmt::Arguments) {
|
||||
use core::fmt::Write;
|
||||
|
||||
@@ -75,7 +77,7 @@ impl fmt::Write for Writer {
|
||||
|
||||
impl Writer {
|
||||
unsafe fn write_success(&self) -> bool {
|
||||
unsafe { inb(PORT + 5) & 0x20 != 0 }
|
||||
inb(PORT + 5) & 0x20 != 0
|
||||
}
|
||||
|
||||
pub fn write_byte(&self, data: u8) {
|
||||
@@ -101,21 +103,21 @@ pub fn init() -> Result<(), &'static str> {
|
||||
}
|
||||
|
||||
pub fn test() -> Result<(), &'static str> {
|
||||
unsafe { outb(PORT + 1, 0x00) }; // Disable all interrupts
|
||||
unsafe { outb(PORT + 3, 0x80) }; // Enable DLAB (set baud rate divisor)
|
||||
unsafe { outb(PORT, 0x03) }; // Set divisor to 3 (lo byte) 38400 baud
|
||||
unsafe { outb(PORT + 1, 0x00) }; // (hi byte)
|
||||
unsafe { outb(PORT + 3, 0x03) }; // 8 bits, no parity, one stop bit
|
||||
unsafe { outb(PORT + 2, 0xC7) }; // Enable FIFO, clear them, with 14-bytethreshold
|
||||
unsafe { outb(PORT + 4, 0x0B) }; // IRQs enabled, RTS/DSR set
|
||||
unsafe { outb(PORT + 4, 0x1E) }; // Set in loopback mode, test the serial chip
|
||||
unsafe { outb(PORT, 0xAE) }; // Test serial chip (send byte 0xAE and check if serial returns same byte)
|
||||
outb(PORT + 1, 0x00); // Disable all interrupts
|
||||
outb(PORT + 3, 0x80); // Enable DLAB (set baud rate divisor)
|
||||
outb(PORT, 0x03); // Set divisor to 3 (lo byte) 38400 baud
|
||||
outb(PORT + 1, 0x00); // (hi byte)
|
||||
outb(PORT + 3, 0x03); // 8 bits, no parity, one stop bit
|
||||
outb(PORT + 2, 0xC7); // Enable FIFO, clear them, with 14-bytethreshold
|
||||
outb(PORT + 4, 0x0B); // IRQs enabled, RTS/DSR set
|
||||
outb(PORT + 4, 0x1E); // Set in loopback mode, test the serial chip
|
||||
outb(PORT, 0xAE); // Test serial chip (send byte 0xAE and check if serial returns same byte)
|
||||
|
||||
if unsafe { inb(PORT) } != 0xAE {
|
||||
return Err("Serial test failed");
|
||||
if inb(PORT) != 0xAE {
|
||||
return Err("serial test failed");
|
||||
}
|
||||
|
||||
unsafe { outb(PORT + 4, 0x0F) };
|
||||
outb(PORT + 4, 0x0F);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -141,7 +143,7 @@ impl Reader {
|
||||
}
|
||||
|
||||
unsafe fn read_ready(&self) -> bool {
|
||||
unsafe { inb(PORT + 5) & 1 != 0 }
|
||||
inb(PORT + 5) & 1 != 0
|
||||
}
|
||||
|
||||
pub fn read(&self) -> u8 {
|
||||
@@ -1,13 +1,14 @@
|
||||
use crate::{debug, serial_print};
|
||||
use pic8259::ChainedPics;
|
||||
use x86_64::structures::idt::{
|
||||
InterruptDescriptorTable, InterruptStackFrame, PageFaultErrorCode,
|
||||
};
|
||||
|
||||
use spin::{Lazy, Mutex};
|
||||
|
||||
use crate::print_log;
|
||||
use x86_64::registers::control::Cr2;
|
||||
use x86_64::structures::idt::{InterruptDescriptorTable, InterruptStackFrame, PageFaultErrorCode};
|
||||
use x86_64::structures::paging::mapper::MapperFlushAll;
|
||||
use x86_64::structures::paging::{FrameAllocator, Mapper, Page, PageTableFlags, Size4KiB};
|
||||
|
||||
use super::gdt;
|
||||
use crate::arch::x86_64::memory::{FRAME_ALLOCATOR, OFFSET_PAGE_TABLE};
|
||||
use crate::{println_log, serial_println};
|
||||
use spin::{Lazy, Mutex};
|
||||
|
||||
static IDT: Lazy<InterruptDescriptorTable> = Lazy::new(|| {
|
||||
let mut idt = InterruptDescriptorTable::new();
|
||||
@@ -68,18 +69,16 @@ pub fn disable_pic() {
|
||||
}
|
||||
}
|
||||
|
||||
const extern "x86-interrupt" fn breakpoint_handler(
|
||||
_stack_frame: InterruptStackFrame,
|
||||
) {
|
||||
// serial_println!("Exception: Breakpoint\n{:#?}", stack_frame);
|
||||
// println_log!("Exception: Breakpoint\n{:#?}", stack_frame);
|
||||
extern "x86-interrupt" fn breakpoint_handler(stack_frame: InterruptStackFrame) {
|
||||
serial_println!("Exception: Breakpoint\n{:#?}", stack_frame);
|
||||
println_log!("Exception: Breakpoint\n{:#?}", stack_frame);
|
||||
}
|
||||
|
||||
extern "x86-interrupt" fn general_protection_fault_handler(
|
||||
stack_frame: InterruptStackFrame,
|
||||
_error_code: u64,
|
||||
) {
|
||||
// serial_println!("Exception: General Protection Fault\n{:#?}", stack_frame);
|
||||
serial_println!("Exception: General Protection Fault\n{:#?}", stack_frame);
|
||||
panic!("Exception: General Protection Fault\n{:#?}", stack_frame);
|
||||
}
|
||||
|
||||
@@ -87,32 +86,29 @@ extern "x86-interrupt" fn double_fault_handler(
|
||||
stack_frame: InterruptStackFrame,
|
||||
_error_code: u64,
|
||||
) -> ! {
|
||||
// serial_println!("Exception: Double Fault\n{:#?}", stack_frame);
|
||||
serial_println!("Exception: Double Fault\n{:#?}", stack_frame);
|
||||
panic!("Exception: Double Fault\n{:#?}", stack_frame);
|
||||
}
|
||||
|
||||
extern "x86-interrupt" fn keyboard_interrupt_handler(
|
||||
_stack_frame: InterruptStackFrame,
|
||||
) {
|
||||
extern "x86-interrupt" fn keyboard_interrupt_handler(_stack_frame: InterruptStackFrame) {
|
||||
use pc_keyboard::{HandleControl, Keyboard, ScancodeSet1, layouts};
|
||||
// use pc_keyboard::DecodedKey;
|
||||
use spin::Mutex;
|
||||
// use x86_64::instructions::port::Port;
|
||||
use x86_64::instructions::port::Port;
|
||||
|
||||
static KEYBOARD: Lazy<Mutex<Keyboard<layouts::Uk105Key, ScancodeSet1>>> =
|
||||
Lazy::new(|| {
|
||||
Mutex::new(Keyboard::new(
|
||||
ScancodeSet1::new(),
|
||||
layouts::Uk105Key,
|
||||
HandleControl::Ignore,
|
||||
))
|
||||
});
|
||||
static KEYBOARD: Lazy<Mutex<Keyboard<layouts::Uk105Key, ScancodeSet1>>> = Lazy::new(|| {
|
||||
Mutex::new(Keyboard::new(
|
||||
ScancodeSet1::new(),
|
||||
layouts::Uk105Key,
|
||||
HandleControl::Ignore,
|
||||
))
|
||||
});
|
||||
|
||||
let _keyboard = KEYBOARD.lock();
|
||||
// let mut port = Port::new(0x60);
|
||||
let mut port = Port::new(0x60);
|
||||
|
||||
// let scancode: u8 = unsafe { port.read() };
|
||||
// libk::drivers::io::keyboard::add_scancode(scancode);
|
||||
let scancode: u8 = unsafe { port.read() };
|
||||
crate::arch::x86_64::drivers::keyboard::add_scancode(scancode);
|
||||
|
||||
unsafe {
|
||||
PICS.lock()
|
||||
@@ -120,46 +116,41 @@ extern "x86-interrupt" fn keyboard_interrupt_handler(
|
||||
}
|
||||
}
|
||||
|
||||
extern "x86-interrupt" fn timer_interrupt_handler(
|
||||
_stack_frame: InterruptStackFrame,
|
||||
) {
|
||||
x86_64::instructions::interrupts::without_interrupts(|| {
|
||||
print_log!("{:?}", _stack_frame)
|
||||
});
|
||||
|
||||
extern "x86-interrupt" fn timer_interrupt_handler(_stack_frame: InterruptStackFrame) {
|
||||
debug!("Timer Interrupt");
|
||||
unsafe {
|
||||
PICS.lock()
|
||||
.notify_end_of_interrupt(InterruptIndex::Timer.as_u8());
|
||||
}
|
||||
}
|
||||
|
||||
const extern "x86-interrupt" fn page_fault_handler(
|
||||
extern "x86-interrupt" fn page_fault_handler(
|
||||
_stack_frame: InterruptStackFrame,
|
||||
_error_code: PageFaultErrorCode,
|
||||
) {
|
||||
// serial_println!("Exception: Page Fault");
|
||||
// serial_println!("Accessed Address: {:?}", Cr2::read());
|
||||
// serial_println!("Error Code: {:?}", _error_code);
|
||||
// serial_println!("{:#?}", _stack_frame);
|
||||
serial_println!("Exception: Page Fault");
|
||||
serial_println!("Accessed Address: {:?}", Cr2::read());
|
||||
serial_println!("Error Code: {:?}", _error_code);
|
||||
serial_println!("{:#?}", _stack_frame);
|
||||
|
||||
/* if let Some(frame_allocator) = FRAME_ALLOCATOR.get() {
|
||||
let mut f = frame_allocator.lock();
|
||||
if let Some(frame_allocator) = FRAME_ALLOCATOR.get() {
|
||||
let mut f = frame_allocator.lock();
|
||||
|
||||
let frame = f.allocate_frame().unwrap();
|
||||
let flags = PageTableFlags::PRESENT | PageTableFlags::WRITABLE;
|
||||
let page: Page<Size4KiB> = Page::containing_address(Cr2::read().unwrap());
|
||||
let frame = f.allocate_frame().unwrap();
|
||||
let flags = PageTableFlags::PRESENT | PageTableFlags::WRITABLE;
|
||||
let page: Page<Size4KiB> =
|
||||
Page::containing_address(Cr2::read().unwrap());
|
||||
|
||||
unsafe {
|
||||
let mut mapper = OFFSET_PAGE_TABLE.get().unwrap().lock();
|
||||
unsafe {
|
||||
let mut mapper = OFFSET_PAGE_TABLE.get().unwrap().lock();
|
||||
|
||||
match mapper.map_to(page, frame, flags, &mut *f) {
|
||||
Ok(_) => {}
|
||||
Err(why) => panic!("failed to map page: {:?}", why),
|
||||
}
|
||||
}
|
||||
MapperFlushAll::new().flush_all();
|
||||
} else {
|
||||
panic!("failed to get frame allocator");
|
||||
}
|
||||
*/
|
||||
match mapper.map_to(page, frame, flags, &mut *f) {
|
||||
Ok(_) => {}
|
||||
Err(why) => panic!("failed to map page: {:?}", why),
|
||||
}
|
||||
}
|
||||
MapperFlushAll::new().flush_all();
|
||||
} else {
|
||||
panic!("failed to get frame allocator");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
use crate::{debugln, serial_print};
|
||||
use core::alloc::{GlobalAlloc, Layout};
|
||||
use core::ptr;
|
||||
use spin::{Mutex, MutexGuard};
|
||||
use x86_64::structures::paging::{Size4KiB, mapper::MapToError, PageTableFlags};
|
||||
use x86_64::VirtAddr;
|
||||
use crate::arch::x86_64::memory::{FRAME_ALLOCATOR, HEAP_SIZE, HEAP_VIRTUAL_SPACE};
|
||||
use crate::arch::x86_64::memory::allocation::page_alloc::FoundryOSFrameAllocator;
|
||||
use crate::arch::x86_64::memory::units::MemoryUnits;
|
||||
use crate::serial_println;
|
||||
|
||||
/// We are currently using a linked list heap allocator which uses our underlying page allocator.
|
||||
#[global_allocator]
|
||||
/// This is now Rust's global allocator, so we can use stuff requiring heap allocations.
|
||||
static ALLOCATOR: Locked<FoundryAllocator> = Locked::new(FoundryAllocator::new());
|
||||
|
||||
|
||||
/// Initializes the heap.
|
||||
///
|
||||
/// This function must be called once, before any functions that
|
||||
/// require a heap are called. It sets up the heap by allocating
|
||||
/// the necessary frames from the page allocator. The heap is
|
||||
/// then ready for use.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// This function must be called only once, and must be called before any types
|
||||
/// are constructed that require dynamic memory allocation.
|
||||
///
|
||||
/// # Parameters
|
||||
///
|
||||
/// None
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Returns a `Result` containing a `MapToError` if the heap
|
||||
/// could not be initialized, or `Ok` if the heap was
|
||||
/// initialized successfully.
|
||||
pub unsafe fn init_heap() -> Result<(), MapToError<Size4KiB>> {
|
||||
unsafe {
|
||||
// code to allocate frames is now done in the page fault interrupt handler!
|
||||
ALLOCATOR.lock().init(HEAP_VIRTUAL_SPACE, HEAP_SIZE);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Locked<T> {
|
||||
inner: Mutex<T>,
|
||||
}
|
||||
|
||||
impl<T> Locked<T> {
|
||||
pub const fn new(inner: T) -> Self {
|
||||
Self {
|
||||
inner: Mutex::new(inner),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn lock(&self) -> MutexGuard<T> {
|
||||
self.inner.lock()
|
||||
}
|
||||
}
|
||||
|
||||
const BLOCK_SIZES: &[usize] = &[8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096];
|
||||
|
||||
struct ListNode {
|
||||
next: Option<&'static mut ListNode>,
|
||||
}
|
||||
|
||||
pub struct FoundryAllocator {
|
||||
list_heads: [Option<&'static mut ListNode>; BLOCK_SIZES.len()],
|
||||
fallback: Locked<FoundryFallbackAllocator>,
|
||||
}
|
||||
|
||||
impl Default for FoundryAllocator {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl FoundryAllocator {
|
||||
pub const fn new() -> Self {
|
||||
const EMPTY: Option<&'static mut ListNode> = None;
|
||||
Self {
|
||||
list_heads: [EMPTY; BLOCK_SIZES.len()],
|
||||
fallback: Locked::new(FoundryFallbackAllocator::new()),
|
||||
}
|
||||
}
|
||||
/// Initializes the fallback allocator with the given heap start address and size.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// This function is unsafe because it does not check whether the given heap start address and size are valid.
|
||||
pub unsafe fn init(&mut self, heap_start: usize, heap_size: usize) {
|
||||
debugln!(" => Start: {:?}", VirtAddr::new(heap_start as u64));
|
||||
debugln!(" => Size: {}", MemoryUnits::from_bytes(heap_size));
|
||||
|
||||
unsafe {
|
||||
self.fallback.lock().init(heap_start, heap_size);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn fallback_alloc(&mut self, layout: Layout) -> *mut u8 {
|
||||
unsafe { self.fallback.alloc(layout) }
|
||||
}
|
||||
|
||||
fn block_size(&self, layout: &Layout) -> Option<usize> {
|
||||
let required_block_size = layout.size().max(layout.align());
|
||||
BLOCK_SIZES.iter().position(|&s| s >= required_block_size)
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl GlobalAlloc for Locked<FoundryAllocator> {
|
||||
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
||||
let mut allocator = self.lock();
|
||||
|
||||
match allocator.block_size(&layout) {
|
||||
Some(index) => {
|
||||
match allocator.list_heads[index].take() {
|
||||
Some(node) => {
|
||||
allocator.list_heads[index] = node.next.take();
|
||||
let ptr = node as *mut ListNode as *mut u8;
|
||||
ensure_mapped(VirtAddr::new(ptr as u64));
|
||||
ptr
|
||||
}
|
||||
None => {
|
||||
// no block exists in list => allocate new block
|
||||
let block_size = BLOCK_SIZES[index];
|
||||
// only works if all block sizes are a power of 2
|
||||
let block_align = block_size;
|
||||
let layout = Layout::from_size_align(block_size, block_align).unwrap();
|
||||
unsafe { allocator.fallback_alloc(layout) }
|
||||
}
|
||||
}
|
||||
}
|
||||
None => unsafe { allocator.fallback_alloc(layout) },
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
|
||||
let mut allocator = self.lock();
|
||||
match allocator.block_size(&layout) {
|
||||
Some(idx) => {
|
||||
let new_node = ListNode {
|
||||
next: allocator.list_heads[idx].take(),
|
||||
};
|
||||
|
||||
let new_ptr = ptr as *mut ListNode;
|
||||
unsafe { new_ptr.write(new_node) };
|
||||
allocator.list_heads[idx] = Some(unsafe { &mut *new_ptr });
|
||||
}
|
||||
None => {
|
||||
unsafe { allocator.fallback.dealloc(ptr, layout) };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct FallbackListNode {
|
||||
size: usize,
|
||||
next: Option<&'static mut FallbackListNode>,
|
||||
}
|
||||
|
||||
impl FallbackListNode {
|
||||
const fn new(size: usize) -> Self {
|
||||
Self { size, next: None }
|
||||
}
|
||||
|
||||
fn start_addr(&self) -> usize {
|
||||
self as *const Self as usize
|
||||
}
|
||||
|
||||
fn end_addr(&self) -> usize {
|
||||
self.start_addr() + self.size
|
||||
}
|
||||
}
|
||||
|
||||
pub struct FoundryFallbackAllocator {
|
||||
head: FallbackListNode,
|
||||
}
|
||||
|
||||
impl Default for FoundryFallbackAllocator {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl FoundryFallbackAllocator {
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
head: FallbackListNode::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Initializes the allocator with a given heap start address and size.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// This function is unsafe because it does not check whether the given heap start address and size are valid.
|
||||
pub unsafe fn init(&mut self, heap_start: usize, heap_size: usize) {
|
||||
unsafe { self.add_region(heap_start, heap_size) };
|
||||
}
|
||||
|
||||
unsafe fn add_region(&mut self, addr: usize, size: usize) {
|
||||
unsafe {
|
||||
let mut node = FallbackListNode::new(size);
|
||||
node.next = self.head.next.take();
|
||||
|
||||
let virt_addr = VirtAddr::new(addr as u64);
|
||||
ensure_mapped(virt_addr);
|
||||
|
||||
let node_ptr = addr as *mut FallbackListNode;
|
||||
node_ptr.write(node);
|
||||
self.head.next = Some(&mut *node_ptr);
|
||||
}
|
||||
}
|
||||
|
||||
fn find_region(
|
||||
&mut self,
|
||||
size: usize,
|
||||
align: usize,
|
||||
) -> Option<(&'static mut FallbackListNode, usize)> {
|
||||
let mut current = &mut self.head;
|
||||
// look for a large enough memory region in linked list
|
||||
while let Some(ref mut region) = current.next {
|
||||
if let Ok(alloc_start) = Self::alloc_from_region(region, size, align) {
|
||||
// region suitable for allocation -> remove node from list
|
||||
let next = region.next.take();
|
||||
let ret = Some((current.next.take().unwrap(), alloc_start));
|
||||
current.next = next;
|
||||
return ret;
|
||||
} else {
|
||||
// region not suitable -> continue with next region
|
||||
current = current.next.as_mut().unwrap();
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
const fn align_up(addr: usize, align: usize) -> usize {
|
||||
(addr + align - 1) & !(align - 1)
|
||||
}
|
||||
|
||||
fn size_align(layout: Layout) -> (usize, usize) {
|
||||
let layout = layout
|
||||
.align_to(align_of::<ListNode>())
|
||||
.expect("adjusting alignment failed")
|
||||
.pad_to_align();
|
||||
let size = layout.size().max(size_of::<ListNode>());
|
||||
(size, layout.align())
|
||||
}
|
||||
|
||||
fn alloc_from_region(
|
||||
region: &FallbackListNode,
|
||||
size: usize,
|
||||
align: usize,
|
||||
) -> Result<usize, ()> {
|
||||
let alloc_start = Self::align_up(region.start_addr(), align);
|
||||
let alloc_end = alloc_start.checked_add(size).ok_or(())?;
|
||||
|
||||
if alloc_end > region.end_addr() {
|
||||
return Err(());
|
||||
}
|
||||
|
||||
let excess_size = region.end_addr() - alloc_end;
|
||||
if excess_size > 0 && excess_size < size_of::<ListNode>() {
|
||||
return Err(());
|
||||
}
|
||||
|
||||
Ok(alloc_start)
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl GlobalAlloc for Locked<FoundryFallbackAllocator> {
|
||||
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
||||
let mut allocator = self.lock();
|
||||
// perform layout adjustments
|
||||
let (size, align) = FoundryFallbackAllocator::size_align(layout);
|
||||
|
||||
if let Some((region, alloc_start)) = allocator.find_region(size, align) {
|
||||
let alloc_end = alloc_start.checked_add(size).expect("overflow");
|
||||
let excess_size = region.end_addr() - alloc_end;
|
||||
if excess_size > 0 {
|
||||
unsafe { allocator.add_region(alloc_end, excess_size) };
|
||||
}
|
||||
let ptr = alloc_start as *mut u8;
|
||||
ensure_mapped(VirtAddr::new(ptr as u64));
|
||||
ptr
|
||||
} else {
|
||||
ptr::null_mut()
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
|
||||
let mut allocator = self.lock();
|
||||
|
||||
// perform layout adjustments
|
||||
let (size, _) = FoundryFallbackAllocator::size_align(layout);
|
||||
unsafe { allocator.add_region(ptr as usize, size) }
|
||||
}
|
||||
}
|
||||
|
||||
fn ensure_mapped(virt_addr: VirtAddr) {
|
||||
if ! FoundryOSFrameAllocator::is_mapped(virt_addr) {
|
||||
let mut foundry_alloc = FRAME_ALLOCATOR.get().unwrap().lock();
|
||||
foundry_alloc.allocate_page(virt_addr, PageTableFlags::PRESENT | PageTableFlags::WRITABLE).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
pub mod heap_alloc;
|
||||
pub(crate) mod page_alloc;
|
||||
pub mod stack_alloc;
|
||||
@@ -0,0 +1,89 @@
|
||||
use x86_64::structures::paging::{FrameAllocator, Mapper, Page, PageTableFlags, PhysFrame, Size4KiB, Translate};
|
||||
use limine::response::MemoryMapResponse;
|
||||
use spin::Mutex;
|
||||
use limine::memory_map::EntryType;
|
||||
use x86_64::{PhysAddr, VirtAddr};
|
||||
use x86_64::structures::paging::mapper::{MapToError, TranslateResult};
|
||||
use crate::arch::x86_64::memory::{FRAME_ALLOCATOR, OFFSET_PAGE_TABLE};
|
||||
|
||||
pub struct FoundryOSFrameAllocator {
|
||||
memory_map: &'static MemoryMapResponse,
|
||||
next: usize,
|
||||
}
|
||||
|
||||
impl FoundryOSFrameAllocator {
|
||||
/// Creates a new `FoundryOSFrameAllocator` from a memory map.
|
||||
///
|
||||
/// This function takes a reference to a `MemoryMapResponse` and initializes
|
||||
/// a `FoundryOSFrameAllocator` with it. The `next` field is set to 0,
|
||||
/// indicating that the first frame to be allocated is the first frame
|
||||
/// in the memory map.
|
||||
pub fn init(memory_map: &'static MemoryMapResponse) {
|
||||
FRAME_ALLOCATOR.call_once(|| {
|
||||
Mutex::new(Self {
|
||||
memory_map,
|
||||
next: 0,
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
pub fn count_usable_frames(&self) -> u64 {
|
||||
self.usable_frames().count() as u64
|
||||
}
|
||||
|
||||
pub fn available_memory(&self) -> u64 {
|
||||
self.memory_map
|
||||
.entries()
|
||||
.iter()
|
||||
.map(|region| region.base..region.base + region.length)
|
||||
.flat_map(|r| r.step_by(4096)).count() as u64 * 4096
|
||||
}
|
||||
|
||||
/// An iterator over all usable frames in the memory map.
|
||||
///
|
||||
/// Yields one `PhysFrame` for each available 4KiB frame in the memory map.
|
||||
///
|
||||
/// This function is used to allocate frames for the page map.
|
||||
fn usable_frames(&self) -> impl Iterator<Item = PhysFrame> + use<> {
|
||||
let regions = self.memory_map.entries().iter();
|
||||
let usable_regions = regions.filter(|region| region.entry_type == EntryType::USABLE);
|
||||
let addr_ranges = usable_regions.map(|region| region.base..region.base + region.length);
|
||||
let frame_addresses = addr_ranges.flat_map(|r| r.step_by(4096));
|
||||
frame_addresses.map(|addr| PhysFrame::from_start_address(PhysAddr::new(addr)).unwrap())
|
||||
}
|
||||
|
||||
pub(crate) fn is_mapped(virt_addr: VirtAddr) -> bool {
|
||||
let mapper = OFFSET_PAGE_TABLE.get().unwrap().lock();
|
||||
matches!(mapper.translate(virt_addr), TranslateResult::Mapped { .. })
|
||||
}
|
||||
|
||||
pub(crate) fn allocate_page(&mut self, start_addr: VirtAddr, flags: PageTableFlags) -> Result<(), MapToError<Size4KiB>> {
|
||||
let page = Page::containing_address(start_addr);
|
||||
let frame = self.allocate_frame().ok_or(MapToError::<Size4KiB>::FrameAllocationFailed)?;
|
||||
let mut mapper = OFFSET_PAGE_TABLE.get().unwrap().lock();
|
||||
|
||||
unsafe {
|
||||
mapper.map_to(page, frame, flags, self)?
|
||||
}.flush();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl FrameAllocator<Size4KiB> for FoundryOSFrameAllocator {
|
||||
/// Allocates a frame from the list of usable frames.
|
||||
///
|
||||
/// This function returns the next available `PhysFrame` from the memory
|
||||
/// map, if one exists. Once a frame is allocated, the internal counter
|
||||
/// is incremented to point to the next frame for future allocations.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// - `Some(PhysFrame)`: If a usable frame is available.
|
||||
/// - `None`: If there are no more usable frames to allocate.
|
||||
fn allocate_frame(&mut self) -> Option<PhysFrame> {
|
||||
let frame = self.usable_frames().nth(self.next);
|
||||
self.next += 1;
|
||||
frame
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
use crate::arch::x86_64::memory::STACK_VIRTUAL_SPACE;
|
||||
use x86_64::VirtAddr;
|
||||
use x86_64::structures::paging::{
|
||||
FrameAllocator, Mapper, Page, Size4KiB, mapper,
|
||||
};
|
||||
|
||||
fn reserve_stack_memory(size_in_pages: u64) -> Page {
|
||||
use core::sync::atomic::{AtomicU64, Ordering};
|
||||
static STACK_ALLOC_NEXT: AtomicU64 =
|
||||
AtomicU64::new(STACK_VIRTUAL_SPACE as u64);
|
||||
let start_addr =
|
||||
VirtAddr::new(STACK_ALLOC_NEXT.fetch_add(
|
||||
size_in_pages * Page::<Size4KiB>::SIZE,
|
||||
Ordering::Relaxed,
|
||||
));
|
||||
Page::from_start_address(start_addr)
|
||||
.expect("`STACK_ALLOC_NEXT` not page aligned")
|
||||
}
|
||||
|
||||
/// Allocates a stack in the virtual address space, mapped to physical pages.
|
||||
///
|
||||
/// This function allocates a stack in the virtual address space, mapped to
|
||||
/// physical pages. The stack is allocated as a sequence of pages, with the
|
||||
/// first page allocated as a guard page. The stack is then mapped to the
|
||||
/// allocated physical frame.
|
||||
///
|
||||
/// The function takes the size of the stack in pages, a mutable reference to a
|
||||
/// mapper, and a mutable reference to a frame allocator. It returns a `Result`
|
||||
/// containing a `StackBounds` struct, which contains the start and end virtual
|
||||
/// addresses of the allocated stack.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// This function is unsafe because it maps physical frames to virtual addresses
|
||||
/// without any protection. This can lead to bugs if the physical frames are not
|
||||
/// correctly allocated, or if the virtual addresses are not correctly aligned.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This function will panic if the allocation of the physical frame fails.
|
||||
pub unsafe fn alloc_stack(
|
||||
size_in_pages: u64,
|
||||
mapper: &mut impl Mapper<Size4KiB>,
|
||||
frame_allocator: &mut impl FrameAllocator<Size4KiB>,
|
||||
) -> Result<StackBounds, mapper::MapToError<Size4KiB>> {
|
||||
unsafe {
|
||||
use x86_64::structures::paging::PageTableFlags as Flags;
|
||||
|
||||
let guard_page = reserve_stack_memory(size_in_pages + 1);
|
||||
let stack_start = guard_page + 1;
|
||||
let stack_end = stack_start + size_in_pages;
|
||||
|
||||
for page in Page::range(stack_start, stack_end) {
|
||||
let frame = frame_allocator
|
||||
.allocate_frame()
|
||||
.ok_or(mapper::MapToError::FrameAllocationFailed)?;
|
||||
let flags = Flags::PRESENT | Flags::WRITABLE;
|
||||
mapper.map_to(page, frame, flags, frame_allocator)?.flush();
|
||||
}
|
||||
|
||||
Ok(StackBounds {
|
||||
start: stack_start.start_address(),
|
||||
end: stack_end.start_address(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct StackBounds {
|
||||
start: VirtAddr,
|
||||
end: VirtAddr,
|
||||
}
|
||||
|
||||
impl StackBounds {
|
||||
pub const fn new(start: VirtAddr, end: VirtAddr) -> Self {
|
||||
Self { start, end }
|
||||
}
|
||||
|
||||
pub const fn start(&self) -> VirtAddr {
|
||||
self.start
|
||||
}
|
||||
|
||||
pub const fn end(&self) -> VirtAddr {
|
||||
self.end
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Sets up a memory map using Limine.
|
||||
|
||||
use limine::{
|
||||
request::{HhdmRequest, KernelAddressRequest, MemoryMapRequest},
|
||||
response::MemoryMapResponse,
|
||||
@@ -15,7 +16,8 @@ static HIGHER_HALF_DIRECT_MAP_REQUEST: HhdmRequest = HhdmRequest::new();
|
||||
|
||||
#[used]
|
||||
#[unsafe(link_section = ".requests")]
|
||||
static KERNEL_ADDRESS_REQUEST: KernelAddressRequest = KernelAddressRequest::new();
|
||||
pub static KERNEL_ADDRESS_REQUEST: KernelAddressRequest =
|
||||
KernelAddressRequest::new();
|
||||
|
||||
/// ```rs
|
||||
/// let virt_addr = phys_addr + offset;
|
||||
@@ -0,0 +1,62 @@
|
||||
pub mod allocation;
|
||||
pub mod mapping;
|
||||
pub mod units;
|
||||
|
||||
use allocation::page_alloc::FoundryOSFrameAllocator;
|
||||
use spin::{Mutex, Once};
|
||||
use units::MemoryUnits::*;
|
||||
use x86_64::{
|
||||
VirtAddr,
|
||||
registers::control::Cr3,
|
||||
structures::paging::{OffsetPageTable, PageTable},
|
||||
};
|
||||
|
||||
pub const STACK_VIRTUAL_SPACE: usize = 0x5555_5555_0000; // start address of the memory space where we store allocated stacks
|
||||
pub const HEAP_VIRTUAL_SPACE: usize = 0x4444_4444_0000; // start address of heap allocated memory
|
||||
pub const HEAP_SIZE: usize = MiB(1).to_bytes();
|
||||
|
||||
pub static FRAME_ALLOCATOR: Once<Mutex<FoundryOSFrameAllocator>> = Once::new();
|
||||
pub static OFFSET_PAGE_TABLE: Once<Mutex<OffsetPageTable>> = Once::new();
|
||||
/// Returns a mutable reference to the current level 4 page table.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// The caller must ensure that the level 4 page table is not modified
|
||||
/// simultaneously. The caller must also ensure that the physical memory offset
|
||||
/// is correct, to ensure that the correct virtual address is constructed.
|
||||
unsafe fn active_l4_table(
|
||||
physical_memory_offset: VirtAddr,
|
||||
) -> &'static mut PageTable {
|
||||
let (level_4_frame, _) = Cr3::read();
|
||||
|
||||
let phys_addr = level_4_frame.start_address();
|
||||
let virt = phys_addr.as_u64() + physical_memory_offset.as_u64();
|
||||
unsafe { &mut *(virt as *mut PageTable) }
|
||||
}
|
||||
|
||||
/// Initializes the `OffsetPageTable` for the current CPU architecture.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// This function must be called only once and should be called before any
|
||||
/// memory operations are performed that rely on virtual memory management.
|
||||
/// The provided `physical_memory_offset` must be accurate to ensure correct
|
||||
/// translation of physical addresses.
|
||||
///
|
||||
/// # Parameters
|
||||
///
|
||||
/// - `physical_memory_offset`: The offset to convert physical addresses to
|
||||
/// virtual addresses in the higher-half direct map.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Returns an `OffsetPageTable` that allows for manipulation of the page
|
||||
/// tables for the current CPU architecture.
|
||||
pub fn init_page_table(physical_memory_offset: VirtAddr) {
|
||||
unsafe {
|
||||
let l4_table = active_l4_table(physical_memory_offset);
|
||||
let offset_table =
|
||||
OffsetPageTable::new(l4_table, physical_memory_offset);
|
||||
OFFSET_PAGE_TABLE.call_once(|| Mutex::new(offset_table));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
pub enum MemoryUnits {
|
||||
B(usize),
|
||||
KiB(usize),
|
||||
MiB(usize),
|
||||
GiB(usize),
|
||||
}
|
||||
|
||||
impl MemoryUnits {
|
||||
pub const fn to_bytes(&self) -> usize {
|
||||
match self {
|
||||
Self::B(b) => *b,
|
||||
Self::KiB(kib) => *kib * 1024,
|
||||
Self::MiB(mib) => *mib * 1024 * 1024,
|
||||
Self::GiB(gib) => *gib * 1024 * 1024 * 1024,
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn from_bytes(bytes: usize) -> Self {
|
||||
if bytes < 1024 {
|
||||
Self::B(bytes)
|
||||
} else if bytes < 1024 * 1024 {
|
||||
Self::KiB(bytes / 1024)
|
||||
} else if bytes < 1024 * 1024 * 1024 {
|
||||
Self::MiB(bytes / (1024 * 1024))
|
||||
} else {
|
||||
Self::GiB(bytes / (1024 * 1024 * 1024))
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn convert(&mut self) {
|
||||
match self {
|
||||
Self::B(b) if *b > 1024 => *self = Self::KiB(*b / 1024),
|
||||
Self::KiB(kib) if *kib > 1024 => *self = Self::MiB(*kib / 1024),
|
||||
Self::MiB(mib) if *mib > 1024 => *self = Self::GiB(*mib / 1024),
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl core::fmt::Display for MemoryUnits {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
match self {
|
||||
Self::B(b) => write!(f, "{} B", b),
|
||||
Self::KiB(kib) => write!(f, "{} KiB", kib),
|
||||
Self::MiB(mib) => write!(f, "{} MiB", mib),
|
||||
Self::GiB(gib) => write!(f, "{} GiB", gib),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
pub mod apic;
|
||||
pub mod cpu;
|
||||
pub mod dev;
|
||||
pub mod drivers;
|
||||
pub mod gdt;
|
||||
pub mod interrupts;
|
||||
pub mod memmap;
|
||||
pub mod memory;
|
||||
pub mod processing;
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
pub mod task;
|
||||
@@ -0,0 +1,150 @@
|
||||
//! Allows creation of asynchronous IO bound tasks.
|
||||
//!
|
||||
//! Written by @zxq5 for the most part with code from
|
||||
//! [here](https://github.com/phil-opp/blog_os/).
|
||||
|
||||
use alloc::boxed::Box;
|
||||
use alloc::collections::BTreeMap;
|
||||
use alloc::sync::Arc;
|
||||
use alloc::task::Wake;
|
||||
use core::{
|
||||
future::Future,
|
||||
pin::Pin,
|
||||
sync::atomic::AtomicU64,
|
||||
task::{Context, Poll, Waker},
|
||||
};
|
||||
use crossbeam::queue::ArrayQueue;
|
||||
use x86_64::instructions::interrupts::{self, enable_and_hlt};
|
||||
|
||||
pub struct Task {
|
||||
id: TaskId,
|
||||
future: Pin<Box<dyn Future<Output = ()>>>,
|
||||
}
|
||||
|
||||
impl Task {
|
||||
pub fn new(future: impl Future<Output = ()> + 'static) -> Self {
|
||||
Self {
|
||||
id: TaskId::new(),
|
||||
future: Box::pin(future),
|
||||
}
|
||||
}
|
||||
|
||||
fn poll(&mut self, context: &mut Context) -> Poll<()> {
|
||||
self.future.as_mut().poll(context)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
struct TaskId(u64);
|
||||
|
||||
impl TaskId {
|
||||
fn new() -> Self {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
Self(NEXT.fetch_add(1, core::sync::atomic::Ordering::Relaxed))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Executor {
|
||||
tasks: BTreeMap<TaskId, Task>,
|
||||
task_queue: Arc<ArrayQueue<TaskId>>,
|
||||
waker_cache: BTreeMap<TaskId, Waker>,
|
||||
}
|
||||
|
||||
impl Executor {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
tasks: BTreeMap::new(),
|
||||
task_queue: Arc::new(ArrayQueue::new(100)),
|
||||
waker_cache: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn spawn(&mut self, task: Task) {
|
||||
let task_id = task.id;
|
||||
if self.tasks.insert(task.id, task).is_some() {
|
||||
panic!("task with same id already in tasks");
|
||||
}
|
||||
self.task_queue.push(task_id).expect("queue full");
|
||||
}
|
||||
|
||||
fn run_ready_tasks(&mut self) {
|
||||
// destructure `self` to avoid borrow checker errors
|
||||
let Self {
|
||||
tasks,
|
||||
task_queue,
|
||||
waker_cache,
|
||||
} = self;
|
||||
|
||||
while let Some(task_id) = task_queue.pop() {
|
||||
let task = match tasks.get_mut(&task_id) {
|
||||
Some(task) => task,
|
||||
None => continue, // task no longer exists
|
||||
};
|
||||
let waker = waker_cache.entry(task_id).or_insert_with(|| {
|
||||
TaskWaker::new_waker(task_id, task_queue.clone())
|
||||
});
|
||||
let mut context = Context::from_waker(waker);
|
||||
match task.poll(&mut context) {
|
||||
Poll::Ready(()) => {
|
||||
// task done -> remove it and its cached waker
|
||||
tasks.remove(&task_id);
|
||||
waker_cache.remove(&task_id);
|
||||
}
|
||||
Poll::Pending => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run(&mut self) -> ! {
|
||||
loop {
|
||||
self.run_ready_tasks();
|
||||
self.sleep_if_idle();
|
||||
}
|
||||
}
|
||||
|
||||
fn sleep_if_idle(&self) {
|
||||
interrupts::disable();
|
||||
if self.task_queue.is_empty() {
|
||||
enable_and_hlt();
|
||||
} else {
|
||||
interrupts::enable();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Executor {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
struct TaskWaker {
|
||||
task_id: TaskId,
|
||||
task_queue: Arc<ArrayQueue<TaskId>>,
|
||||
}
|
||||
|
||||
impl TaskWaker {
|
||||
fn wake_task(&self) {
|
||||
self.task_queue.push(self.task_id).expect("task_queue full");
|
||||
}
|
||||
|
||||
fn new_waker(
|
||||
task_id: TaskId,
|
||||
task_queue: Arc<ArrayQueue<TaskId>>,
|
||||
) -> Waker {
|
||||
Waker::from(Arc::new(Self {
|
||||
task_id,
|
||||
task_queue,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
impl Wake for TaskWaker {
|
||||
fn wake(self: Arc<Self>) {
|
||||
self.wake_task();
|
||||
}
|
||||
|
||||
fn wake_by_ref(self: &Arc<Self>) {
|
||||
self.wake_task();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
#![expect(unused)]
|
||||
pub mod async_io;
|
||||
mod taskrunner;
|
||||
pub mod threading;
|
||||
@@ -0,0 +1,12 @@
|
||||
use alloc::boxed::Box;
|
||||
|
||||
pub struct Task {
|
||||
pid: usize,
|
||||
task: Box<dyn Fn() + Send + 'static>,
|
||||
}
|
||||
|
||||
impl Task {
|
||||
// pub const fn new() {}
|
||||
|
||||
pub const fn run() {}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
mod switch;
|
||||
mod deprecated;
|
||||
|
||||
use core::arch::asm;
|
||||
|
||||
#[repr(C)]
|
||||
pub struct Thread {
|
||||
id: usize,
|
||||
/// This shall be default before the program is interrupted, otherwise it will store
|
||||
/// CPU registers etc to be restored on context switch.
|
||||
ctx: ThreadContext,
|
||||
}
|
||||
|
||||
/// CPU state to be saved on context switches.
|
||||
#[repr(C)]
|
||||
#[derive(Default)]
|
||||
pub struct ThreadContext {
|
||||
/// Accumulator register.
|
||||
rax: u64,
|
||||
/// Base register.
|
||||
rbx: u64,
|
||||
/// Counter register.
|
||||
rcx: u64,
|
||||
/// Data register.
|
||||
rdx: u64,
|
||||
/// Source index register.
|
||||
rsi: u64,
|
||||
/// Destination index register.
|
||||
rdi: u64,
|
||||
/// Base pointer register.
|
||||
rbp: u64,
|
||||
/// Stack pointer register.
|
||||
rsp: u64,
|
||||
/// An extended register.
|
||||
r8: u64,
|
||||
/// An extended register.
|
||||
r9: u64,
|
||||
/// An extended register.
|
||||
r10: u64,
|
||||
/// An extended register.
|
||||
r11: u64,
|
||||
/// An extended register.
|
||||
r12: u64,
|
||||
/// An extended register.
|
||||
r13: u64,
|
||||
/// An extended register.
|
||||
r14: u64,
|
||||
/// An extended register.
|
||||
r15: u64,
|
||||
/// The instruction pointer.
|
||||
rip: u64,
|
||||
/// RFLAGS register.
|
||||
rflags: u64,
|
||||
}
|
||||
|
||||
impl ThreadContext {
|
||||
/// Saves the current registers of the CPU before a context switch
|
||||
/// to be restored later.
|
||||
///
|
||||
/// # Notes
|
||||
///
|
||||
/// This function should ONLY be called in interrupt handlers such
|
||||
/// as that of the timer. This will then save registers as required
|
||||
///
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// This function is unsafe because of the usage of inline ASM.
|
||||
#[inline(always)]
|
||||
pub unsafe fn save_registers() -> Self {
|
||||
let mut context = Self::default();
|
||||
unsafe {
|
||||
asm!(
|
||||
"mov {0}, rax",
|
||||
"mov {1}, rbx",
|
||||
"mov {2}, rcx",
|
||||
"mov {3}, rdx",
|
||||
"mov {4}, rsi",
|
||||
"mov {5}, rdi",
|
||||
"mov {6}, rbp",
|
||||
"mov {7}, rsp",
|
||||
"mov {8}, r8",
|
||||
"mov {9}, r9",
|
||||
"mov {10}, r10",
|
||||
"mov {11}, r11",
|
||||
"mov {12}, r12",
|
||||
"mov {13}, r13",
|
||||
"mov {14}, r14",
|
||||
"mov {15}, r15",
|
||||
"lea {16}, [rip]",
|
||||
"pushf",
|
||||
"pop {17}",
|
||||
out(reg) context.rax,
|
||||
out(reg) context.rbx,
|
||||
out(reg) context.rcx,
|
||||
out(reg) context.rdx,
|
||||
out(reg) context.rsi,
|
||||
out(reg) context.rdi,
|
||||
out(reg) context.rbp,
|
||||
out(reg) context.rsp,
|
||||
out(reg) context.r8,
|
||||
out(reg) context.r9,
|
||||
out(reg) context.r10,
|
||||
out(reg) context.r11,
|
||||
out(reg) context.r12,
|
||||
out(reg) context.r13,
|
||||
out(reg) context.r14,
|
||||
out(reg) context.r15,
|
||||
out(reg) context.rip,
|
||||
out(reg) context.rflags,
|
||||
);
|
||||
}
|
||||
|
||||
context
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
use crate::arch::x86_64::memory::allocation::stack_alloc::StackBounds;
|
||||
use x86_64::VirtAddr;
|
||||
|
||||
mod switch;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Thread {
|
||||
id: ThreadId,
|
||||
stack_ptr: Option<VirtAddr>,
|
||||
stack_bounds: Option<StackBounds>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct ThreadId(u64);
|
||||
|
||||
impl ThreadId {
|
||||
pub const fn as_u64(&self) -> u64 {
|
||||
self.0
|
||||
}
|
||||
|
||||
fn new() -> Self {
|
||||
use core::sync::atomic::{AtomicU64, Ordering};
|
||||
static NEXT_THREAD_ID: AtomicU64 = AtomicU64::new(1);
|
||||
Self(NEXT_THREAD_ID.fetch_add(1, Ordering::Relaxed))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
.intel_syntax noprefix
|
||||
|
||||
switch_thread:
|
||||
pushfq
|
||||
|
||||
mov rax, rsp
|
||||
mov rsp, rdi
|
||||
|
||||
mov rdi, rax
|
||||
call add_paused_thread
|
||||
|
||||
popfq
|
||||
ret
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -1,158 +0,0 @@
|
||||
//! Handles setting up the framebuffer passed to us by Limine.
|
||||
#![expect(unused)]
|
||||
use crate::DEFAULT_FONT;
|
||||
|
||||
use super::{colour::Colour, font::Font};
|
||||
|
||||
use limine::framebuffer::Framebuffer;
|
||||
use limine::request::FramebufferRequest;
|
||||
use spin::{Lazy, Mutex};
|
||||
|
||||
#[used]
|
||||
#[unsafe(link_section = ".requests")]
|
||||
/// The Limine framebuffer request.
|
||||
static FRAMEBUFFER_REQUEST: FramebufferRequest = FramebufferRequest::new();
|
||||
|
||||
/// A mutex used for writing to the framebuffer, in most cases we can abstract
|
||||
/// this behind calls to println! etc.
|
||||
pub static FRAMEBUFFER_WRITER: Lazy<Mutex<Option<FramebufferWriter>>> = Lazy::new(
|
||||
|| {
|
||||
Mutex::new(FRAMEBUFFER_REQUEST.get_response().map_or_else(
|
||||
|| {
|
||||
unreachable!("Framebuffer request failed, got None.");
|
||||
},
|
||||
|framebuffer_response| {
|
||||
let framebuffer =
|
||||
framebuffer_response.framebuffers().next()
|
||||
.expect("Expected to find at least one framebuffer in response, got zero.");
|
||||
Some(FramebufferWriter::new(framebuffer, Colour::Black))
|
||||
},
|
||||
))
|
||||
},
|
||||
);
|
||||
|
||||
/// The updated writer stores necessary fields from the [Framebuffer].
|
||||
/// This ensures that the contained types are Send, as Framebuffer was
|
||||
/// not marked as Send.
|
||||
///
|
||||
/// It also avoids the requirement for lifetimes.
|
||||
///
|
||||
/// Note this does not implement Writer as these functions only handle drawing
|
||||
/// pixels.
|
||||
pub struct FramebufferWriter {
|
||||
pitch: u64,
|
||||
/// Number of bits used per pixel, we expect 32 so this will be asserted
|
||||
/// when we initialise the framebuffer.
|
||||
bpp: u16,
|
||||
/// A raw pointer to the framebuffer.
|
||||
addr: *mut u8,
|
||||
/// The width of the screen in pixels.
|
||||
width: u64,
|
||||
/// The height of the screen in pixels.
|
||||
height: u64,
|
||||
/// The default background colour of the Framebuffer.
|
||||
background_colour: Colour,
|
||||
}
|
||||
|
||||
/// Marker trait required for sending the writer across threads, which will
|
||||
/// probably come in handy later.
|
||||
unsafe impl Send for FramebufferWriter {}
|
||||
/// Marker trait required for sharing the writer across threads, which will
|
||||
/// probably come in handy later.
|
||||
///
|
||||
/// # Note
|
||||
///
|
||||
/// We wrap this in a Mutex later so this should handle synchronising accesses.
|
||||
unsafe impl Sync for FramebufferWriter {}
|
||||
|
||||
impl FramebufferWriter {
|
||||
/// Creates a new [`FramebufferWriter`] with the specified background
|
||||
/// colour.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if the bits per pixel for the framebuffer is not 32 bits per
|
||||
/// pixel, because we didn't exactly handle other cases.
|
||||
pub fn new(framebuffer: Framebuffer, background_colour: Colour) -> Self {
|
||||
// We don't handle other cases, this should not trigger on most newer
|
||||
// hardware.
|
||||
assert!(framebuffer.bpp() == 32);
|
||||
|
||||
Self {
|
||||
pitch: framebuffer.pitch(),
|
||||
bpp: framebuffer.bpp(),
|
||||
addr: framebuffer.addr(),
|
||||
width: framebuffer.width(),
|
||||
height: framebuffer.height(),
|
||||
background_colour,
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes a pixel with `colour` to the screen at the given `(x, y)`
|
||||
/// coordinates (in pixels).
|
||||
pub fn write_pixel(&self, x: usize, y: usize, colour: Colour) {
|
||||
let pitch = self.pitch as usize;
|
||||
let bpp = (self.bpp / 8) as usize;
|
||||
let pixel_offset = y * pitch + x * bpp;
|
||||
|
||||
// Safety: We assume the pointer to the framebuffer is valid, which it likely
|
||||
// is because we copy it from the Limine request.
|
||||
unsafe {
|
||||
*(self.addr.add(pixel_offset) as *mut u32) = colour.into();
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes a 2D slice `buffer` to the screen. This should be less than the
|
||||
/// size of the screen in dimensions, but does not neccessarily fill the
|
||||
/// whole screen.
|
||||
pub fn render_frame(&self, buffer: &[&[Colour]]) {
|
||||
// TODO: this should return errors.
|
||||
for (y, &row) in buffer.iter().enumerate() {
|
||||
if y >= self.height() as usize {
|
||||
break;
|
||||
}
|
||||
for (x, pixel) in row.iter().enumerate() {
|
||||
if x >= self.width() as usize {
|
||||
break;
|
||||
}
|
||||
self.write_pixel(x, y, *pixel);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the width of the framebuffer in pixels.
|
||||
pub const fn width(&self) -> u32 {
|
||||
self.width as u32
|
||||
}
|
||||
|
||||
/// Returns the height of the framebuffer in pixels.
|
||||
pub const fn height(&self) -> u32 {
|
||||
self.height as u32
|
||||
}
|
||||
|
||||
/// Sets the new default background colour.
|
||||
pub const fn set_default_background_colour(&mut self, bg: Colour) {
|
||||
self.background_colour = bg;
|
||||
}
|
||||
|
||||
/// Clears the screen and sets the background to the default colour.
|
||||
pub fn clear(&self) {
|
||||
let width = self.width as usize;
|
||||
let height = self.height as usize;
|
||||
|
||||
for y in 0..height {
|
||||
for x in 0..width {
|
||||
// Write the background in the preferred background colour.
|
||||
self.write_pixel(x, y, self.background_colour);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the screen size in pixels or (0, 0) if something went wrong.
|
||||
pub fn screensize_px() -> (u32, u32) {
|
||||
FRAMEBUFFER_WRITER
|
||||
.lock()
|
||||
.as_mut()
|
||||
.map_or_else(|| (0, 0), |writer| (writer.width(), writer.height()))
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
pub mod colour;
|
||||
pub mod font;
|
||||
pub mod framebuffer;
|
||||
pub mod writer;
|
||||
@@ -1 +0,0 @@
|
||||
// pub mod keyboard;
|
||||
+96
-21
@@ -11,36 +11,60 @@
|
||||
rustdoc::missing_panics_doc
|
||||
)]
|
||||
|
||||
use arch::x86_64::dev::serial;
|
||||
use arch::x86_64::{gdt, interrupts};
|
||||
extern crate alloc;
|
||||
use crate::{arch::x86_64::memory::init_page_table, prelude::*};
|
||||
use arch::x86_64::memory::allocation::heap_alloc::init_heap;
|
||||
use arch::x86_64::memory::mapping;
|
||||
use core::arch::asm;
|
||||
use graphics::font::{FONT_SPLEEN_8X16, Font};
|
||||
use limine::BaseRevision;
|
||||
use std::unwind;
|
||||
use std::unwind::eh_info::ELF;
|
||||
use x86_64::VirtAddr;
|
||||
use arch::x86_64::memory::allocation::page_alloc::FoundryOSFrameAllocator;
|
||||
use crate::arch::x86_64::cpu::apic::enable_apic;
|
||||
use crate::arch::x86_64::drivers::ascii::screensize_chars;
|
||||
use crate::arch::x86_64::drivers::framebuffer::display::screensize_px;
|
||||
use crate::arch::x86_64::memory::FRAME_ALLOCATOR;
|
||||
use crate::arch::x86_64::memory::units::MemoryUnits;
|
||||
|
||||
pub mod arch;
|
||||
pub mod graphics;
|
||||
pub mod io;
|
||||
mod panic;
|
||||
pub mod resources;
|
||||
#[allow(unused)] // We aren't using much of this right now.
|
||||
pub mod std;
|
||||
pub mod util;
|
||||
|
||||
pub mod prelude {
|
||||
pub use crate::{
|
||||
eprint, eprintln, print, print_log, println, println_log, serial_print,
|
||||
serial_println,
|
||||
debug, debugln,
|
||||
std::io::{_print, _print_log, _serial_write, _print_err},
|
||||
std::debug::_debug,
|
||||
};
|
||||
}
|
||||
|
||||
/// Sets the base revision to the latest revision supported by the crate.
|
||||
/// See specification for further info.
|
||||
/// Be sure to mark all limine requests with #[used], otherwise they may be
|
||||
/// removed by the compiler.
|
||||
#[used]
|
||||
// The .requests section allows limine to find the requests faster and more safely.
|
||||
// The .requests section allows limine to find the requests faster and more
|
||||
// safely.
|
||||
#[unsafe(link_section = ".requests")]
|
||||
static BASE_REVISION: BaseRevision = BaseRevision::new();
|
||||
|
||||
/// The default font used when setting up the framebuffer code.
|
||||
pub const DEFAULT_FONT: Font = FONT_SPLEEN_8X16;
|
||||
|
||||
#[panic_handler]
|
||||
fn rust_panic(_info: &core::panic::PanicInfo) -> ! {
|
||||
println!("Kernel panic: {}", _info);
|
||||
serial_println!("Kernel panic: {}", _info);
|
||||
hcf();
|
||||
}
|
||||
|
||||
pub fn hcf() -> ! {
|
||||
loop {
|
||||
unsafe {
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
asm!("hlt");
|
||||
}
|
||||
}
|
||||
@@ -48,27 +72,78 @@ pub fn hcf() -> ! {
|
||||
|
||||
pub fn boot() -> Result<(), &'static str> {
|
||||
if !BASE_REVISION.is_supported() {
|
||||
return Err("Base Revision was not supported.");
|
||||
return Err("Base revision not supported");
|
||||
}
|
||||
|
||||
print_log!(" Setting up Serial Communication... ");
|
||||
use arch::x86_64::{gdt, interrupts};
|
||||
|
||||
if serial::init().is_err() {
|
||||
println_log!("[Not Detected]")
|
||||
let memory_map = mapping::get_memory_map();
|
||||
|
||||
print_log!(" Initialising Serial... ");
|
||||
let res = arch::x86_64::drivers::serial::init();
|
||||
serial_print!(" Initialising Serial... ");
|
||||
if res.is_err() {
|
||||
debugln!("[Not Detected]")
|
||||
} else {
|
||||
println_log!("[Success]")
|
||||
debugln!("[Success]");
|
||||
}
|
||||
|
||||
print_log!(" Setting up GDT... ");
|
||||
debugln!(" Display...");
|
||||
let dimensions = screensize_chars();
|
||||
let dimensions2 = screensize_px();
|
||||
debugln!(" => (px) : {}x{} ", dimensions2.0, dimensions2.1);
|
||||
debugln!(" => (chars) : {}x{} ", dimensions.0, dimensions.1);
|
||||
debugln!(" [Success]");
|
||||
|
||||
debug!(" Setting Up Global Descriptor Table... ");
|
||||
gdt::init();
|
||||
println_log!("[Success]");
|
||||
debugln!("[Success]");
|
||||
|
||||
interrupts::enable_pic();
|
||||
// interrupts::disable_pic();
|
||||
|
||||
print_log!(" Initialising interrupts... ");
|
||||
debug!(" Setting Up Interrupt Descriptor Table... ");
|
||||
interrupts::init_idt();
|
||||
println_log!("[Success]");
|
||||
debugln!("[Success]");
|
||||
|
||||
debugln!(" Initialising Memory Subsystem... ");
|
||||
let physical_memory_offset = VirtAddr::new(*mapping::PHYSICAL_MEMORY_OFFSET);
|
||||
init_page_table(physical_memory_offset);
|
||||
FoundryOSFrameAllocator::init(memory_map);
|
||||
let available_bytes = FRAME_ALLOCATOR.get().unwrap().lock().available_memory();
|
||||
debugln!(" => Available Memory: {}", MemoryUnits::from_bytes(available_bytes as usize));
|
||||
|
||||
debugln!("[Success]");
|
||||
|
||||
debugln!(" Initialising Heap... ");
|
||||
if unsafe { init_heap() }.is_err() {
|
||||
return Err("Failed to initialise heap: error");
|
||||
}
|
||||
debugln!(" [Success]");
|
||||
|
||||
// debug!(" Enabling PICs... ");
|
||||
// interrupts::enable_pic();
|
||||
// debugln!("[Success]");
|
||||
|
||||
debug!(" Disabling PICs... ");
|
||||
interrupts::disable_pic();
|
||||
debugln!("[Success]");
|
||||
|
||||
debug!(" Initialising APIC... ");
|
||||
enable_apic();
|
||||
debugln!("[Success]");
|
||||
|
||||
debug!(" Enabling Interrupts... ");
|
||||
x86_64::instructions::interrupts::enable();
|
||||
debugln!("[Success]");
|
||||
|
||||
debug!(" Setting up stack unwinder, panic handler... ");
|
||||
// Setup stack traces and proper panic handler. TODO: Handle panics
|
||||
// differently if not initialised.
|
||||
let eh_frame_ptr = ELF
|
||||
.get_section_addr(".eh_frame_hdr")
|
||||
.expect("Could not get `.eh_frame_hdr` address.");
|
||||
|
||||
let _eh_info =
|
||||
unsafe { unwind::eh_info::EhInfo::from_hdr_ptr(eh_frame_ptr) };
|
||||
debugln!("[Success]");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+21
-4
@@ -1,12 +1,29 @@
|
||||
#![no_std]
|
||||
#![no_main]
|
||||
|
||||
use foundry_os::boot;
|
||||
extern crate alloc;
|
||||
use foundry_os::arch::x86_64::drivers::ascii::screensize_chars;
|
||||
use foundry_os::arch::x86_64::drivers::framebuffer::display::screensize_px;
|
||||
use foundry_os::arch::x86_64::processing::async_io::task::{Executor, Task};
|
||||
use foundry_os::util::shell::shell;
|
||||
use foundry_os::{println, println_log};
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
extern "C" fn kmain() -> ! {
|
||||
_ = boot();
|
||||
println_log!(" [ Initialising Kernel Systems ] ");
|
||||
if let Err(err) = foundry_os::boot() {
|
||||
panic!("{}", err);
|
||||
}
|
||||
|
||||
#[allow(clippy::empty_loop)]
|
||||
loop {}
|
||||
println_log!(" [ Kernel Initialised Successfully ] ");
|
||||
|
||||
// println!("TESTING :: Allocation");
|
||||
// let somevec = vec![0; 1_000_000];
|
||||
// println!("{:?}", somevec);
|
||||
// println!("{}", somevec.len());
|
||||
// println!("PASSED!");
|
||||
|
||||
let mut executor = Executor::new();
|
||||
executor.spawn(Task::new(shell()));
|
||||
executor.run()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
// //! Stack-unwinding code for the Kernel. This is a modified version of https://github.com/nbdd0121/unwinding/blob/trunk/src/panic_handler.rs
|
||||
// //! which does not support environment variables for obvious reasons, however we
|
||||
// //! may implement a cmdline similar to Linux in the near future.
|
||||
|
||||
// #![expect(
|
||||
// clippy::empty_loop,
|
||||
// reason = "We don't yet have working power management. This is OK for now."
|
||||
// )]
|
||||
// use crate::prelude::*;
|
||||
// use alloc::boxed::Box;
|
||||
// use core::any::Any;
|
||||
// use core::cell::Cell;
|
||||
// use core::ffi::c_void;
|
||||
// use core::panic::{Location, PanicInfo};
|
||||
// use unwinding::abi::*;
|
||||
// use unwinding::panic::begin_panic;
|
||||
|
||||
// #[thread_local]
|
||||
// static PANIC_COUNT: Cell<usize> = Cell::new(0);
|
||||
|
||||
// #[link(name = "c")]
|
||||
// unsafe extern "C" {}
|
||||
|
||||
// fn stack_trace() {
|
||||
// struct CallbackData {
|
||||
// counter: usize,
|
||||
// }
|
||||
|
||||
// extern "C" fn callback(
|
||||
// unwind_ctx: &UnwindContext<'_>,
|
||||
// arg: *mut c_void,
|
||||
// ) -> UnwindReasonCode {
|
||||
// let data = unsafe { &mut *(arg as *mut CallbackData) };
|
||||
// data.counter += 1;
|
||||
// eprintln!(
|
||||
// "{:4}:{:#19x} - <unknown>",
|
||||
// data.counter,
|
||||
// _Unwind_GetIP(unwind_ctx)
|
||||
// );
|
||||
// UnwindReasonCode::NO_REASON
|
||||
// }
|
||||
// let mut data = CallbackData { counter: 0 };
|
||||
// _Unwind_Backtrace(callback, &mut data as *mut _ as _);
|
||||
// }
|
||||
|
||||
// fn do_panic(msg: Box<dyn Any + Send>) -> ! {
|
||||
// if PANIC_COUNT.get() >= 1 {
|
||||
// stack_trace();
|
||||
// eprintln!("Thread panicked while processing panic. aborting.");
|
||||
// loop {}
|
||||
// }
|
||||
|
||||
// PANIC_COUNT.set(1);
|
||||
// stack_trace();
|
||||
|
||||
// let code = begin_panic(Box::new(msg));
|
||||
// eprintln!("Failed to initiate panic: error {}", code.0);
|
||||
|
||||
// loop {}
|
||||
// }
|
||||
|
||||
// #[panic_handler]
|
||||
// fn panic(info: &PanicInfo<'_>) -> ! {
|
||||
// eprintln!("{}", info);
|
||||
|
||||
// struct NoPayload;
|
||||
// do_panic(Box::new(NoPayload))
|
||||
// }
|
||||
|
||||
// #[track_caller]
|
||||
// #[expect(unused, reason = "May still be used in the future.")]
|
||||
// pub fn panic_any<M: 'static + Any + Send>(msg: M) -> ! {
|
||||
// eprintln!("Panicked at {}", Location::caller());
|
||||
// do_panic(Box::new(msg))
|
||||
// }
|
||||
@@ -1,11 +1,11 @@
|
||||
#![allow(unused)]
|
||||
use libm::include_font;
|
||||
|
||||
pub const FONT_SPLEEN_8X16: Font =
|
||||
Font::new(include_font!("../../resources/font/spleen-8x16.psf"));
|
||||
Font::new(include_font!("../../../resources/font/spleen-8x16.psf"));
|
||||
|
||||
pub const FONT_CP850_8X16: Font =
|
||||
Font::new(include_font!("../../resources/font/cp850-8x16.psf"));
|
||||
Font::new(include_font!("../../../resources/font/cp850-8x16.psf"));
|
||||
|
||||
// pub struct Font(pub [[u8; 16]; 512]);
|
||||
|
||||
pub struct Font {
|
||||
width: usize,
|
||||
@@ -39,8 +39,10 @@ impl Font {
|
||||
pub const fn height(&self) -> usize {
|
||||
self.height
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn default() -> &'static Self {
|
||||
&FONT_SPLEEN_8X16
|
||||
impl Default for Font {
|
||||
fn default() -> Self {
|
||||
FONT_CP850_8X16
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
pub mod font;
|
||||
@@ -0,0 +1,22 @@
|
||||
use alloc::string::String;
|
||||
use alloc::vec::Vec;
|
||||
|
||||
pub mod frame;
|
||||
pub mod render;
|
||||
pub mod window;
|
||||
|
||||
pub trait Application {
|
||||
type Output;
|
||||
|
||||
fn run(
|
||||
&mut self,
|
||||
args: Vec<String>,
|
||||
) -> impl Future<Output = Result<Self::Output, Error>> + Send;
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
UnknownCommand(String),
|
||||
ApplicationFailed(String),
|
||||
KernelError(String),
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
use super::{render::RenderError, window::Window};
|
||||
use crate::arch::x86_64::drivers::framebuffer::colour::Colour;
|
||||
use crate::std::maths::geometry::Vec2;
|
||||
use alloc::{vec, vec::Vec};
|
||||
|
||||
pub struct Frame<'f> {
|
||||
data: Vec<Vec<Colour>>,
|
||||
window: &'f Window,
|
||||
}
|
||||
|
||||
impl<'a> Frame<'a> {
|
||||
pub fn new(window: &'a Window) -> Self {
|
||||
Self {
|
||||
data: vec![
|
||||
vec![Colour::Black; window.dimensions().x()];
|
||||
window.dimensions().y()
|
||||
],
|
||||
window,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn render(&self) -> Result<(), RenderError> {
|
||||
let data: Vec<&[Colour]> =
|
||||
self.data.iter().map(|v| v.as_slice()).collect::<Vec<_>>();
|
||||
self.window
|
||||
.render(data.as_slice())
|
||||
.map_err(|_| RenderError::Generic)
|
||||
}
|
||||
|
||||
pub fn write_pixel(
|
||||
&mut self,
|
||||
x: usize,
|
||||
y: usize,
|
||||
color: Colour,
|
||||
) -> Result<(), RenderError> {
|
||||
if x >= self.window.dimensions().x()
|
||||
|| y >= self.window.dimensions().y()
|
||||
{
|
||||
return Err(RenderError::Generic);
|
||||
}
|
||||
self.data[y][x] = color;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub const fn dimensions(&self) -> Vec2<usize> {
|
||||
self.window.dimensions()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
use crate::arch::x86_64::drivers::framebuffer::colour::Colour;
|
||||
use core::fmt::Display;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum RenderError {
|
||||
Generic,
|
||||
}
|
||||
|
||||
impl Display for RenderError {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
match self {
|
||||
Self::Generic => write!(f, "Generic render error"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl core::error::Error for RenderError {}
|
||||
|
||||
pub struct ColouredChar {
|
||||
ch: u8,
|
||||
colour: Colour,
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
use super::render::RenderError;
|
||||
use crate::arch::x86_64::drivers::framebuffer::colour::Colour;
|
||||
use crate::arch::x86_64::drivers::framebuffer::display::FRAMEBUFFER_WRITER;
|
||||
use crate::std::maths::geometry::Vec2;
|
||||
use alloc::string::String;
|
||||
|
||||
pub struct Window {
|
||||
dimensions: Vec2<usize>,
|
||||
position: Vec2<usize>,
|
||||
bordered: bool,
|
||||
opened: bool,
|
||||
title: String,
|
||||
}
|
||||
|
||||
impl Window {
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
dimensions: Vec2::new(0, 0),
|
||||
position: Vec2::new(0, 0),
|
||||
bordered: true,
|
||||
opened: false,
|
||||
title: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn render(&self, _data: &[&[Colour]]) -> Result<(), RenderError> {
|
||||
// TODO: error handling!! the kernel should return an error in some
|
||||
// cases
|
||||
if let Some(fb) = FRAMEBUFFER_WRITER.lock().as_mut() {
|
||||
fb.render_frame(_data);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub const fn is_bordered(&self) -> bool {
|
||||
self.bordered
|
||||
}
|
||||
|
||||
pub const fn is_open(&self) -> bool {
|
||||
self.opened
|
||||
}
|
||||
|
||||
pub const fn open(&mut self) {
|
||||
self.opened = true;
|
||||
}
|
||||
|
||||
pub const fn close(&mut self) {
|
||||
self.opened = false;
|
||||
}
|
||||
|
||||
// some basic getters and setters for utility.
|
||||
pub fn title(&'static self) -> &'static str {
|
||||
self.title.as_str()
|
||||
}
|
||||
|
||||
pub const fn dimensions(&self) -> Vec2<usize> {
|
||||
self.dimensions
|
||||
}
|
||||
|
||||
pub const fn position(&self) -> Vec2<usize> {
|
||||
self.position
|
||||
}
|
||||
|
||||
pub fn set_title(&mut self, title: String) {
|
||||
self.title = title;
|
||||
}
|
||||
|
||||
pub fn move_window(&mut self, offset: Vec2<usize>) {
|
||||
self.position += offset;
|
||||
}
|
||||
|
||||
pub const fn set_position(&mut self, position: Vec2<usize>) {
|
||||
self.position = position;
|
||||
}
|
||||
|
||||
pub const fn set_dimensions(&mut self, dimensions: Vec2<usize>) {
|
||||
self.dimensions = dimensions;
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Window {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Window {
|
||||
fn drop(&mut self) {
|
||||
if self.opened {
|
||||
self.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
use super::{
|
||||
application::{frame::Frame, render::RenderError},
|
||||
maths::geometry::Vec2,
|
||||
};
|
||||
use crate::arch::x86_64::drivers::framebuffer::colour::Colour;
|
||||
use crate::resources::font::Font;
|
||||
|
||||
pub struct Writer<'a> {
|
||||
font: &'a Font,
|
||||
}
|
||||
|
||||
impl<'a> Writer<'a> {
|
||||
pub const fn new(font: &'a Font) -> Self {
|
||||
Self { font }
|
||||
}
|
||||
|
||||
pub const fn set_font(&mut self, font: &'a Font) {
|
||||
self.font = font;
|
||||
}
|
||||
|
||||
pub const fn font_size(&self) -> Vec2<usize> {
|
||||
Vec2::new(self.font.width(), self.font.height())
|
||||
}
|
||||
|
||||
pub fn render_glyph(
|
||||
&self,
|
||||
frame: &mut Frame,
|
||||
pos: Vec2<usize>,
|
||||
c: u8,
|
||||
scale: usize,
|
||||
) -> Result<(), RenderError> {
|
||||
// get a reference to the character glyph from the font.
|
||||
let data: &[u8] = self.font.glyph_for(c as u16);
|
||||
|
||||
if pos.x() + self.font.width() * scale > frame.dimensions().x()
|
||||
|| pos.y() + self.font.height() * scale > frame.dimensions().y()
|
||||
{
|
||||
return Err(RenderError::Generic);
|
||||
}
|
||||
|
||||
for (row, line) in data.iter().enumerate().take(self.font.height()) {
|
||||
for col in 0..self.font.width() {
|
||||
let pixel_x: usize = pos.x() + col * scale;
|
||||
let pixel_y: usize = pos.y() + row * scale;
|
||||
|
||||
if line & (0x80 >> col) != 0 {
|
||||
for i in 0..scale {
|
||||
for j in 0..scale {
|
||||
frame.write_pixel(
|
||||
pixel_x + i,
|
||||
pixel_y + j,
|
||||
Colour::White,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
use core::fmt;
|
||||
use x86_64::instructions::interrupts;
|
||||
use crate::prelude::{_print_log, _serial_write};
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! debugln {
|
||||
() => ($crate::print_log!("\n"));
|
||||
($($arg:tt)*) => ($crate::debug!("{}\n", format_args!($($arg)*)));
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! debug {
|
||||
($($arg:tt)*) => ($crate::prelude::_debug(format_args!($($arg)*)));
|
||||
}
|
||||
|
||||
pub fn _debug(args: fmt::Arguments) {
|
||||
interrupts::without_interrupts(|| {
|
||||
_print_log(args);
|
||||
_serial_write(args);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
//! Basic ELF parsing functionality using the `elf` crate.
|
||||
//!
|
||||
//! This may be extended in the future to support loading programs, however we
|
||||
//! currently use this for getting the sizes of sections in our kernel ELF at
|
||||
//! runtime.
|
||||
//!
|
||||
//! This is used for implementing stacktraces in std::unwind.
|
||||
//!
|
||||
//! # TODO
|
||||
//!
|
||||
//! * Add support for loading binary programs (this should probably be written
|
||||
//! in a different module)
|
||||
|
||||
use alloc::format;
|
||||
use elf::{
|
||||
ElfBytes, ParseError,
|
||||
endian::LittleEndian,
|
||||
parse::{ParseAt, ParsingTable},
|
||||
section::{SectionHeader, SectionHeaderTable},
|
||||
string_table::StringTable,
|
||||
};
|
||||
use limine::request::KernelFileRequest;
|
||||
|
||||
use crate::prelude::*;
|
||||
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
/// The length of the ELF header in bytes.
|
||||
pub const ELF_HEADER_LEN: usize = 64;
|
||||
|
||||
/// Information about our own ELF file to make ELF parsing easier, such as the
|
||||
/// length of the file and a pointer to the contents.
|
||||
#[used]
|
||||
pub static KERNEL_FILE_REQUEST: KernelFileRequest = KernelFileRequest::new();
|
||||
|
||||
/// A list of errors that may occur when parsing ELF files.
|
||||
#[derive(Debug)]
|
||||
pub enum ElfError {
|
||||
/// Returned if a section did not exist in [ElfReader::get_section_size].
|
||||
SectionNotExists,
|
||||
/// Parse errors returned by the `elf` crate.
|
||||
OtherParseError(elf::ParseError),
|
||||
}
|
||||
|
||||
impl From<elf::ParseError> for ElfError {
|
||||
fn from(err: elf::ParseError) -> Self {
|
||||
Self::OtherParseError(err)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ElfReader {
|
||||
/// Structure returned by the `elf` crate having parsed the ELF header.
|
||||
elf: ElfBytes<'static, LittleEndian>,
|
||||
}
|
||||
|
||||
impl ElfReader {
|
||||
/// Parses the ELF file for the kernel, this uses data from Limine's Kernel
|
||||
/// File Request to get a slice over the whole executable file.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// Assumes a properly formed ELF file, and that Limine returns a correct
|
||||
/// pointer to the start of the file as well as a valid length in bytes.
|
||||
///
|
||||
/// Both of these should be satisfied, but this function is marked unsafe
|
||||
/// just in case, because we are derefererencing arbitrary pointers.
|
||||
pub unsafe fn new() -> Result<Self, ElfError> {
|
||||
let response = KERNEL_FILE_REQUEST
|
||||
.get_response()
|
||||
.expect("Didn't get the kernel file from Limine. That's odd.");
|
||||
|
||||
// We fetch these from Limine and use them to parse our own ELF file.
|
||||
let file = response.file();
|
||||
let file_start_ptr = file.addr();
|
||||
let file_size = file.size() as usize;
|
||||
|
||||
// Safety: This slice should contain the whole bytes of the ELF file.
|
||||
let elf_hdr_slice =
|
||||
unsafe { core::slice::from_raw_parts(file_start_ptr, file_size) };
|
||||
|
||||
let elf: ElfBytes<'static, LittleEndian> =
|
||||
elf::ElfBytes::minimal_parse(elf_hdr_slice)?;
|
||||
|
||||
Ok(Self { elf })
|
||||
}
|
||||
|
||||
/// Gets the section size of `section_name` in bytes.
|
||||
pub fn get_section_size(
|
||||
&self,
|
||||
section_name: &'static str,
|
||||
) -> Result<u64, ElfError> {
|
||||
Ok(self.get_section_header(section_name)?.sh_size)
|
||||
}
|
||||
|
||||
/// Gets the start address of the section `section_name` in memory.
|
||||
pub fn get_section_addr(
|
||||
&self,
|
||||
section_name: &'static str,
|
||||
) -> Result<*const u8, ElfError> {
|
||||
Ok(self.get_section_header(section_name)?.sh_addr as *const u8)
|
||||
}
|
||||
|
||||
/// Gets the section header of `section_name`.
|
||||
pub fn get_section_header(
|
||||
&self,
|
||||
section_name: &'static str,
|
||||
) -> Result<SectionHeader, ElfError> {
|
||||
let section_hdr = self
|
||||
.elf
|
||||
.section_header_by_name(section_name)
|
||||
.map_err(|_e| ElfError::SectionNotExists)?;
|
||||
|
||||
section_hdr.ok_or(ElfError::SectionNotExists)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
pub use crate::arch::x86_64::drivers::{
|
||||
ascii::{_print, _print_err, _print_log},
|
||||
serial::_serial_write,
|
||||
};
|
||||
|
||||
pub mod stdin;
|
||||
@@ -0,0 +1,75 @@
|
||||
use crate::arch::x86_64::drivers::{
|
||||
ascii::WRITER,
|
||||
keyboard::{KeyStroke, get_keystroke_async, get_keystroke_optional},
|
||||
};
|
||||
use alloc::string::String;
|
||||
|
||||
/// Reads a line of input from standard input asynchronously, returning a
|
||||
/// `String` containing the input line. Does not include the newline
|
||||
/// character at the end of the line.
|
||||
///
|
||||
/// If the user presses the abort key (usually Ctrl+C), the returned string
|
||||
/// will be empty.
|
||||
pub async fn read_line() -> String {
|
||||
let mut writer = WRITER.lock();
|
||||
|
||||
let mut buff = String::new();
|
||||
loop {
|
||||
match get_keystroke_async().await {
|
||||
KeyStroke::Char(c) => match c {
|
||||
'\n' => {
|
||||
writer.write_glyph(c as u8);
|
||||
return buff;
|
||||
}
|
||||
'\r' => {
|
||||
writer.write_glyph(c as u8);
|
||||
return buff;
|
||||
}
|
||||
'\x08' => {
|
||||
if !buff.is_empty() {
|
||||
buff.pop();
|
||||
writer.backspace();
|
||||
}
|
||||
}
|
||||
|
||||
c => {
|
||||
writer.write_glyph(c as u8);
|
||||
buff.push(c)
|
||||
}
|
||||
},
|
||||
KeyStroke::Enter => {
|
||||
writer.write_glyph(b'\n');
|
||||
return buff;
|
||||
}
|
||||
KeyStroke::Backspace => {
|
||||
if !buff.is_empty() {
|
||||
buff.pop();
|
||||
writer.backspace();
|
||||
}
|
||||
}
|
||||
_ => continue,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads a character from standard input and blocks the current task until
|
||||
/// a character is available.
|
||||
///
|
||||
/// # Note
|
||||
///
|
||||
/// This function is not yet implemented.
|
||||
pub async fn async_keystroke() -> KeyStroke {
|
||||
get_keystroke_async().await
|
||||
}
|
||||
|
||||
/// Attempt to read a character from standard input without blocking the
|
||||
/// current task.
|
||||
///
|
||||
/// If no character is available, returns `None`.
|
||||
///
|
||||
/// # Note
|
||||
///
|
||||
/// This function is not yet implemented.
|
||||
pub fn keystroke() -> Option<KeyStroke> {
|
||||
get_keystroke_optional()
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
use core::ops::{AddAssign, DivAssign, MulAssign, SubAssign};
|
||||
|
||||
pub trait Coordinate:
|
||||
Copy + Clone + PartialEq + AddAssign + MulAssign + SubAssign + DivAssign
|
||||
{
|
||||
}
|
||||
|
||||
impl Coordinate for usize {}
|
||||
impl Coordinate for isize {}
|
||||
impl Coordinate for u8 {}
|
||||
impl Coordinate for i8 {}
|
||||
impl Coordinate for u16 {}
|
||||
impl Coordinate for i16 {}
|
||||
impl Coordinate for u32 {}
|
||||
impl Coordinate for i32 {}
|
||||
impl Coordinate for u64 {}
|
||||
impl Coordinate for i64 {}
|
||||
impl Coordinate for u128 {}
|
||||
impl Coordinate for i128 {}
|
||||
impl Coordinate for f32 {}
|
||||
impl Coordinate for f64 {}
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Debug)]
|
||||
pub struct Vec2<T: Coordinate> {
|
||||
x: T,
|
||||
y: T,
|
||||
}
|
||||
|
||||
impl<T: Coordinate> Vec2<T> {
|
||||
pub const fn new(x: T, y: T) -> Self {
|
||||
Self { x, y }
|
||||
}
|
||||
|
||||
pub fn into<S: Coordinate + From<T>>(&self) -> Vec2<S> {
|
||||
Vec2::new(self.x.into(), self.y.into())
|
||||
}
|
||||
|
||||
pub const fn x(&self) -> T {
|
||||
self.x
|
||||
}
|
||||
|
||||
pub const fn y(&self) -> T {
|
||||
self.y
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Coordinate> AddAssign for Vec2<T> {
|
||||
fn add_assign(&mut self, rhs: Self) {
|
||||
self.x += rhs.x;
|
||||
self.y += rhs.y;
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Coordinate> SubAssign for Vec2<T> {
|
||||
fn sub_assign(&mut self, rhs: Self) {
|
||||
self.x -= rhs.x;
|
||||
self.y -= rhs.y;
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Coordinate> MulAssign<T> for Vec2<T> {
|
||||
fn mul_assign(&mut self, rhs: T) {
|
||||
self.x *= rhs;
|
||||
self.y *= rhs;
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Coordinate> DivAssign<T> for Vec2<T> {
|
||||
fn div_assign(&mut self, rhs: T) {
|
||||
self.x /= rhs;
|
||||
self.y /= rhs;
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Coordinate> From<Vec2<T>> for (T, T) {
|
||||
fn from(value: Vec2<T>) -> Self {
|
||||
(value.x, value.y)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
pub mod geometry;
|
||||
@@ -0,0 +1,7 @@
|
||||
pub mod application;
|
||||
pub mod ascii;
|
||||
pub mod elf;
|
||||
pub mod io;
|
||||
pub mod maths;
|
||||
pub mod unwind;
|
||||
pub mod debug;
|
||||
@@ -0,0 +1,135 @@
|
||||
//! Contains a [EhInfo] struct that contains the parsed DWARF exception header
|
||||
//! data from the ELF .eh_frame and .eh_frame_hdr sections.
|
||||
|
||||
use alloc::{boxed::Box, slice};
|
||||
use gimli::{
|
||||
BaseAddresses, EhFrame, EhFrameHdr, EhHdrTable, EndianSlice, LittleEndian,
|
||||
ParsedEhFrameHdr,
|
||||
};
|
||||
use spin::Lazy;
|
||||
|
||||
use crate::{println_log, std::elf::ElfReader};
|
||||
|
||||
/// Contains useful data parsed from the ELF file in question. In the kernel
|
||||
/// this will be our own process.
|
||||
///
|
||||
/// We use this to implement stack traces and potential unwinding.
|
||||
///
|
||||
/// # Sources
|
||||
///
|
||||
/// This code is reproduced from [lesenchal.fr](https://lesenechal.fr/en/linux/unwinding-the-stack-the-hard-way#h5.1-parsing-eh_frame-and-eh_frame_hdr-with-gimli)
|
||||
/// and will later be extended as required.
|
||||
pub struct EhInfo {
|
||||
/// A set of base addresses used for relative addressing.
|
||||
base_addrs: BaseAddresses,
|
||||
/// The parsed `.eh_frame_hdr` section.
|
||||
hdr: &'static ParsedEhFrameHdr<EndianSlice<'static, LittleEndian>>,
|
||||
/// The lookup table in the parsed `.eh_frame_hdr` section.
|
||||
/// This is a binary search table, it is optional but should be present as
|
||||
/// we are linking with LLD(?) \[needs citation].
|
||||
hdr_table: EhHdrTable<'static, EndianSlice<'static, LittleEndian>>,
|
||||
/// The parsed `.eh_frame` containing the CFIs (call frame information).
|
||||
eh_frame: EhFrame<EndianSlice<'static, LittleEndian>>,
|
||||
}
|
||||
|
||||
/// Stores the [ElfReader] struct for this ELF file.
|
||||
pub static ELF: Lazy<ElfReader> =
|
||||
Lazy::new(|| unsafe { ElfReader::new().unwrap() });
|
||||
|
||||
impl EhInfo {
|
||||
/// Gets the `.eh_frame_hdr` size in bytes.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// If we can't get the size of `.eh_frame_hdr`.
|
||||
pub fn eh_frame_hdr_size() -> usize {
|
||||
ELF.get_section_size(".eh_frame_hdr")
|
||||
.expect("Cannot get size of `.eh_frame_hdr`.") as usize
|
||||
}
|
||||
|
||||
/// Gets the `.eh_frame` size in bytes.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// If we can't get the size of `.eh_frame`.
|
||||
pub fn eh_frame_size() -> usize {
|
||||
ELF.get_section_size(".eh_frame")
|
||||
.expect("Cannot get size of `.eh_frame`.") as usize
|
||||
}
|
||||
|
||||
/// Constructs a [EhInfo] from the base address. This is defined for a
|
||||
/// symbol in the linker script so we can initialise stack traces and -- in
|
||||
/// the future -- unwinding.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// Assumes the `.eh_frame_hdr` pointer to be valid, as well as the sizes of
|
||||
/// the containing sections. These sizes are computed using [ElfReader].
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This function panics if Gimli throws parsing errors -- for example due
|
||||
/// to a malformed or corrupted binary, or because this is called in
|
||||
/// release-mode, or on a stripped binary.
|
||||
///
|
||||
/// # TODOs
|
||||
///
|
||||
/// * Support external System.map files which list symbols and contain
|
||||
/// debugging information.
|
||||
pub unsafe fn from_hdr_ptr(eh_frame_hdr: *const u8) -> Self {
|
||||
let mut base_addrs = BaseAddresses::default();
|
||||
// We add the `.eh_frame_hdr` pointer to the set of base addresses which
|
||||
// are used by Gimli for later parsing. This may be used to compute a
|
||||
// pointer to `.eh_frame`.
|
||||
base_addrs = base_addrs.set_eh_frame_hdr(eh_frame_hdr as u64);
|
||||
|
||||
// Leaking the Box gives us a reference with `'static` lifetime to use
|
||||
// in Self.
|
||||
let hdr = Box::leak(Box::new(
|
||||
// We need to construct a slice as input for `EhFrameHdr::new`.
|
||||
// This is sound if data pointer and length are known to be
|
||||
// correct.
|
||||
EhFrameHdr::new(
|
||||
unsafe {
|
||||
core::slice::from_raw_parts(
|
||||
eh_frame_hdr,
|
||||
Self::eh_frame_hdr_size(),
|
||||
)
|
||||
},
|
||||
LittleEndian,
|
||||
) // Parse the header using the base address we provided (virtual
|
||||
// memory). Address size is how many bytes make an
|
||||
// address (64 bits).
|
||||
.parse(&base_addrs, 8)
|
||||
.expect(
|
||||
"Could not parse `.eh_frame_hdr`. The ELF must be malformed.",
|
||||
),
|
||||
));
|
||||
|
||||
// Create a pointer to the `.eh_frame` ready to parse it.
|
||||
let eh_frame = match hdr.eh_frame_ptr() {
|
||||
gimli::Pointer::Direct(addr) => addr as *mut u8,
|
||||
_ => unimplemented!(),
|
||||
};
|
||||
|
||||
// Add the `.eh_frame` address for addresses relative to this section.
|
||||
base_addrs = base_addrs.set_eh_frame(eh_frame as u64);
|
||||
|
||||
// Finally parse the `.eh_frame` section of our ELF.
|
||||
let eh_frame = EhFrame::new(
|
||||
unsafe {
|
||||
core::slice::from_raw_parts(eh_frame, Self::eh_frame_size())
|
||||
},
|
||||
LittleEndian,
|
||||
);
|
||||
|
||||
Self {
|
||||
base_addrs,
|
||||
hdr,
|
||||
hdr_table: hdr.table().expect(
|
||||
"The CFI binary search table was not present in this binary, oh dear.",
|
||||
),
|
||||
eh_frame,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
pub mod eh_info;
|
||||
@@ -0,0 +1,248 @@
|
||||
use crate::arch::x86_64::drivers::keyboard::{KeyStroke, get_keystroke_async};
|
||||
use crate::resources::font::Font;
|
||||
use crate::serial_print;
|
||||
use crate::serial_println;
|
||||
use crate::std::application::{
|
||||
Application, Error, frame::Frame, render::RenderError, window::Window,
|
||||
};
|
||||
use crate::std::ascii::Writer;
|
||||
use crate::std::maths::geometry::Vec2;
|
||||
use alloc::string::{String, ToString};
|
||||
use alloc::vec::Vec;
|
||||
|
||||
pub struct Editor {
|
||||
cursor_line: usize,
|
||||
cursor_col: usize,
|
||||
|
||||
mode: Mode,
|
||||
buffer: String,
|
||||
window: Window,
|
||||
}
|
||||
|
||||
impl Default for Editor {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Editor {
|
||||
const PADDING: usize = 8;
|
||||
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
cursor_line: 0,
|
||||
cursor_col: 0,
|
||||
|
||||
mode: Mode::Nor,
|
||||
buffer: String::new(),
|
||||
window: Window::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn render(&'a self) -> Result<Frame<'a>, RenderError> {
|
||||
let mut frame = Frame::new(&self.window);
|
||||
let font = Font::default();
|
||||
let writer = Writer::new(&font);
|
||||
|
||||
let (width, height) = writer.font_size().into();
|
||||
|
||||
let mut col = 0;
|
||||
let mut line = 0;
|
||||
let mut scale = 1;
|
||||
|
||||
for ch in self.buffer.chars() {
|
||||
if ch == '\n' {
|
||||
line += scale;
|
||||
col = 0;
|
||||
scale = 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if width * (col + 1) > frame.dimensions().x() - 2 * Self::PADDING {
|
||||
line += scale;
|
||||
col = 0;
|
||||
}
|
||||
|
||||
writer.render_glyph(
|
||||
&mut frame,
|
||||
Vec2::new(
|
||||
col * width + Self::PADDING,
|
||||
line * height + Self::PADDING,
|
||||
),
|
||||
ch as u8,
|
||||
scale,
|
||||
)?;
|
||||
col += scale;
|
||||
}
|
||||
|
||||
writer
|
||||
.render_glyph(
|
||||
&mut frame,
|
||||
Vec2::new(
|
||||
self.cursor_col * width + Self::PADDING,
|
||||
self.cursor_line * height + Self::PADDING,
|
||||
),
|
||||
b'_',
|
||||
scale,
|
||||
)
|
||||
.expect("TODO: panic message");
|
||||
|
||||
Ok(frame)
|
||||
}
|
||||
|
||||
#[allow(unused_variables, dead_code, clippy::needless_pass_by_ref_mut)]
|
||||
fn get_lines(&self) -> Vec<&str> {
|
||||
self.buffer.split('\n').collect::<Vec<&str>>()
|
||||
}
|
||||
|
||||
#[allow(unused_variables, dead_code, clippy::needless_pass_by_ref_mut)]
|
||||
fn move_cursor(&mut self, x: i32, y: i32) {
|
||||
self.cursor_line = self
|
||||
.cursor_line
|
||||
.checked_add_signed(y as isize)
|
||||
.unwrap_or(self.cursor_line);
|
||||
self.cursor_col = self
|
||||
.cursor_col
|
||||
.checked_add_signed(x as isize)
|
||||
.unwrap_or(self.cursor_col);
|
||||
}
|
||||
|
||||
#[allow(unused_variables, dead_code, clippy::needless_pass_by_ref_mut)]
|
||||
fn delete_char(&mut self) {
|
||||
let i = self.get_char_idx();
|
||||
self.buffer.remove(i);
|
||||
}
|
||||
|
||||
#[allow(unused_variables, dead_code, clippy::needless_pass_by_ref_mut)]
|
||||
fn insert_char(&mut self, c: char) {
|
||||
let i = self.get_char_idx();
|
||||
self.buffer.insert(i, c);
|
||||
}
|
||||
|
||||
#[allow(unused_variables, dead_code, clippy::needless_pass_by_ref_mut)]
|
||||
fn splitline(&mut self) {
|
||||
let i = self.get_char_idx();
|
||||
self.buffer.insert(i, '\n');
|
||||
}
|
||||
|
||||
fn get_char_idx(&self) -> usize {
|
||||
let frame = Frame::new(&self.window);
|
||||
let font = Font::default();
|
||||
let writer = Writer::new(&font);
|
||||
let (width, _height) = writer.font_size().into();
|
||||
|
||||
let mut col = 0;
|
||||
let mut line = 0;
|
||||
let mut scale = 1;
|
||||
|
||||
for (i, ch) in self.buffer.chars().enumerate() {
|
||||
if ch == '\n' {
|
||||
line += scale;
|
||||
col = 0;
|
||||
scale = 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if width * (col + 1) > frame.dimensions().x() - 2 * Self::PADDING {
|
||||
line += scale;
|
||||
col = 0;
|
||||
}
|
||||
|
||||
if col == self.cursor_col && line == self.cursor_line {
|
||||
return i;
|
||||
}
|
||||
|
||||
col += scale;
|
||||
}
|
||||
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
impl Application for Editor {
|
||||
type Output = ();
|
||||
async fn run(
|
||||
&mut self,
|
||||
_args: Vec<alloc::string::String>,
|
||||
) -> Result<Self::Output, Error> {
|
||||
self.window.set_dimensions(Vec2::new(1280, 800));
|
||||
self.window.set_position(Vec2::new(0, 0));
|
||||
self.window.open();
|
||||
|
||||
self.buffer = "Hello world, this is a test init. idk test \n ewntuiewi gjk gfdfg gndf ngdfgnmdfg ndfgmndfg gdfndfnkg njkdgjkndfjnkg ngnjfgnfgnfg fgn fn gfj gnfg jnfgjfngjk fgnjfgnjk jnkdgjnkdfg gfnd njkgdfgjn d fjnkgjkndfgjkndfgjn gndfjnk njkgdfng jnkfgdjknd jnfkgnjk".to_string();
|
||||
|
||||
loop {
|
||||
if let Err(_err) = self.render().and_then(|frame| frame.render()) {
|
||||
// TODO: Handle error
|
||||
return Err(Error::ApplicationFailed(
|
||||
"Rendering failed".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let keystroke = get_keystroke_async().await;
|
||||
|
||||
match self.mode {
|
||||
Mode::Nor => match keystroke {
|
||||
KeyStroke::Char('i') => self.mode = Mode::Ins,
|
||||
KeyStroke::Char('`') => return Ok(()),
|
||||
_ => {}
|
||||
},
|
||||
Mode::Ins => {
|
||||
match keystroke {
|
||||
KeyStroke::Char(c) => {
|
||||
match c {
|
||||
// escape
|
||||
'\x1B' => self.mode = Mode::Nor,
|
||||
// delete
|
||||
'\x7F' => self.delete_char(),
|
||||
// backspace
|
||||
'\x08' => {
|
||||
self.move_cursor(-1, 0);
|
||||
self.delete_char();
|
||||
}
|
||||
// enter
|
||||
'\n' => self.splitline(),
|
||||
_ => {
|
||||
self.insert_char(c);
|
||||
self.move_cursor(1, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
KeyStroke::Left => {
|
||||
serial_println!("Left\n");
|
||||
self.move_cursor(-1, 0);
|
||||
}
|
||||
KeyStroke::Right => {
|
||||
serial_println!("Right\n");
|
||||
self.move_cursor(1, 0);
|
||||
}
|
||||
KeyStroke::Up => {
|
||||
serial_println!("Up\n");
|
||||
self.move_cursor(0, -1);
|
||||
}
|
||||
KeyStroke::Down => {
|
||||
serial_println!("Down\n");
|
||||
self.move_cursor(0, 1);
|
||||
}
|
||||
KeyStroke::None => {}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub enum Mode {
|
||||
Nor,
|
||||
Ins,
|
||||
}
|
||||
|
||||
impl core::fmt::Display for Mode {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
match self {
|
||||
Self::Nor => write!(f, "Normal"),
|
||||
Self::Ins => write!(f, "Insert"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
pub mod editor;
|
||||
pub mod shell;
|
||||
@@ -0,0 +1,49 @@
|
||||
// use x86_64::registers::rflags::read;
|
||||
|
||||
use crate::arch::x86_64::drivers::ascii::clear_screen;
|
||||
use crate::prelude::*;
|
||||
use crate::std::application::Application;
|
||||
use crate::std::io::stdin::read_line;
|
||||
use crate::util::editor::Editor;
|
||||
use alloc::vec::Vec;
|
||||
|
||||
static FETCH: &str = "
|
||||
$$$$$$$$\\ $$\\
|
||||
$$ _____| $$ |
|
||||
$$ | $$$$$$\\ $$\\ $$\\ $$$$$$$\\ $$$$$$$ | $$$$$$\\ $$\\ $$\\
|
||||
$$$$$\\ $$ __$$\\ $$ | $$ |$$ __$$\\ $$ __$$ |$$ __$$\\ $$ | $$ |
|
||||
$$ __|$$ / $$ |$$ | $$ |$$ | $$ |$$ / $$ |$$ | \\__|$$ | $$ |
|
||||
$$ | $$ | $$ |$$ | $$ |$$ | $$ |$$ | $$ |$$ | $$ | $$ |
|
||||
$$ | \\$$$$$$ |\\$$$$$$ |$$ | $$ |\\$$$$$$$ |$$ | \\$$$$$$$ |
|
||||
\\__| \\______/ \\______/ \\__| \\__| \\_______|\\__| \\____$$ |
|
||||
$$$$$$\\ $$$$$$\\ $$\\ $$\\ $$\\ $$\\ $$ |
|
||||
$$ __$$\\ $$ __$$\\ $$ | $$ |$$$$ | \\$$$$$$ |
|
||||
$$ / $$ |$$ / \\__| $$ | $$ |\\_$$ | \\______/
|
||||
$$ | $$ |\\$$$$$$\\ \\$$\\ $$ | $$ |
|
||||
$$ | $$ | \\____$$\\ \\$$\\$$ / $$ |
|
||||
$$ | $$ |$$\\ $$ | \\$$$ / $$ |
|
||||
$$$$$$ |\\$$$$$$ | \\$ / $$$$$$\\
|
||||
\\______/ \\______/ \\_/ \\______|
|
||||
";
|
||||
|
||||
pub async fn shell() {
|
||||
println!("{}", FETCH);
|
||||
|
||||
loop {
|
||||
print!(" Shell> ");
|
||||
let line = read_line().await;
|
||||
match line.as_str() {
|
||||
"fetch" => {
|
||||
println!("{}", FETCH);
|
||||
}
|
||||
"editor" => {
|
||||
let mut editor = Editor::new();
|
||||
editor.run(Vec::new()).await.unwrap();
|
||||
}
|
||||
"clear" => clear_screen(),
|
||||
_ => {
|
||||
println!("Unknown command: {}", line);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+53
-38
@@ -1,3 +1,4 @@
|
||||
#![allow(dead_code)]
|
||||
#![feature(proc_macro_span)]
|
||||
#![warn(
|
||||
clippy::correctness,
|
||||
@@ -10,9 +11,6 @@
|
||||
rustdoc::missing_panics_doc
|
||||
)]
|
||||
|
||||
use std::fs::File;
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
|
||||
use proc_macro::{Span, TokenStream};
|
||||
use quote::quote;
|
||||
use std::path::PathBuf;
|
||||
@@ -36,17 +34,18 @@ pub fn include_font(item: TokenStream) -> TokenStream {
|
||||
let source_filepath: PathBuf = source_file.path();
|
||||
let file_path = format!(
|
||||
"{}/{}",
|
||||
source_filepath.parent().unwrap_or_else(|| panic!("Expected to find the calling source file in a folder like src! Got: {}", source_filepath.display())).display(),
|
||||
source_filepath.parent()
|
||||
.unwrap_or_else(|| panic!("Expected to find the calling source file in a folder like src! Got: {}", source_filepath.display())).display(),
|
||||
filename.value()
|
||||
);
|
||||
|
||||
let font_bytes = match load_file(file_path) {
|
||||
let font_bytes = match std::fs::read(file_path) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(why) => panic!("{}", why),
|
||||
};
|
||||
|
||||
let font_data = match Font::new(font_bytes) {
|
||||
Ok(font) => font.0,
|
||||
let font_data = match FontBuilder::load(font_bytes) {
|
||||
Ok(font) => font.data,
|
||||
Err(why) => panic!("{}", why),
|
||||
};
|
||||
|
||||
@@ -62,18 +61,48 @@ pub fn include_font(item: TokenStream) -> TokenStream {
|
||||
|
||||
struct Font([[u8; 16]; 512]);
|
||||
|
||||
impl Font {
|
||||
const MAGIC: u16 = 0x3604;
|
||||
struct FontData {
|
||||
width: u8,
|
||||
height: u8,
|
||||
length: u16,
|
||||
pub data: [[u8; 16]; 512],
|
||||
}
|
||||
enum FontBuilder {
|
||||
Psf1(FontData),
|
||||
Psf2(FontData),
|
||||
}
|
||||
|
||||
pub fn new(data: [u8; (32 + 2) * 512 + 4]) -> Result<Self, &'static str> {
|
||||
let magic: u16 = (data[0] as u16) << 8 | data[1] as u16;
|
||||
impl FontBuilder {
|
||||
const PSF1_MAGIC: u16 = 0x3604;
|
||||
const PSF2_MAGIC: u32 = 0x72b54a86;
|
||||
|
||||
fn revision(data: &[u8]) -> u8 {
|
||||
if (data[0] as u16) << 8 | data[1] as u16 == Self::PSF1_MAGIC {
|
||||
1
|
||||
} else if (data[0] as u32) << 24
|
||||
| (data[1] as u32) << 16
|
||||
| (data[2] as u32) << 8
|
||||
| data[3] as u32
|
||||
== Self::PSF2_MAGIC
|
||||
{
|
||||
2
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
pub fn load(data: Vec<u8>) -> Result<FontData, &'static str> {
|
||||
match Self::revision(&data[0..4]) {
|
||||
1 => Self::parse_psf1(&data),
|
||||
2 => Self::parse_psf2(&data),
|
||||
_ => panic!("invalid font revision result"),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_psf1(data: &[u8]) -> Result<FontData, &'static str> {
|
||||
let mode = data[2];
|
||||
let size = data[3];
|
||||
|
||||
if magic != Self::MAGIC {
|
||||
return Err("Magic value is invalid!");
|
||||
}
|
||||
|
||||
let has_512_glyphs = (mode & 0x01) != 0;
|
||||
let mut glyphs = [[0; 16]; 512];
|
||||
let glyph_count = if has_512_glyphs { 512 } else { 256 };
|
||||
@@ -86,29 +115,15 @@ impl Font {
|
||||
glyphs[i] = buff;
|
||||
}
|
||||
|
||||
Ok(Self(glyphs))
|
||||
}
|
||||
}
|
||||
|
||||
type FileContents = [u8; (32 + 2) * 512 + 4];
|
||||
fn load_file(filename: String) -> Result<FileContents, std::io::Error> {
|
||||
let mut buf = [0; (32 + 2) * 512 + 4];
|
||||
let mut f = File::open(filename).unwrap();
|
||||
f.seek(SeekFrom::Start(0)).unwrap();
|
||||
|
||||
loop {
|
||||
match f.read(&mut buf) {
|
||||
Ok(read) => {
|
||||
if read == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(why) => {
|
||||
eprintln!("Failed to read PS1 font file: {}", why);
|
||||
return Err(why);
|
||||
}
|
||||
}
|
||||
Ok(FontData {
|
||||
width: 8,
|
||||
height: size,
|
||||
length: glyph_count,
|
||||
data: glyphs,
|
||||
})
|
||||
}
|
||||
|
||||
Ok(buf)
|
||||
const fn parse_psf2(_data: &[u8]) -> Result<FontData, &'static str> {
|
||||
Err("PSF2 support is not implemented yet!")
|
||||
}
|
||||
}
|
||||
|
||||
+3
-4
@@ -1,5 +1,4 @@
|
||||
max_width = 85
|
||||
format_code_in_doc_comments = true
|
||||
comment_width = 80
|
||||
wrap_comments = true
|
||||
inline_attribute_width = 80
|
||||
max_width = 80
|
||||
comment_width = 80
|
||||
format_code_in_doc_comments = true
|
||||
|
||||
@@ -94,6 +94,15 @@ check_test_res() {
|
||||
|
||||
trap 'check_test_res "tests completed"' ERR
|
||||
|
||||
|
||||
# NOTE(ali): For some reason the values in `boot_flags` were causing issues
|
||||
# on WSL, so they've been eradicated.
|
||||
systemInfo=$(uname -r)
|
||||
if [[ $systemInfo == *"WSL"* ]]; then
|
||||
echo "Running on WSL2"
|
||||
boot_flags=""
|
||||
fi
|
||||
|
||||
cd "$project_root"
|
||||
qemu-system-x86_64 -M q35 \
|
||||
-cdrom "$build_dir/image.iso" \
|
||||
|
||||
Reference in New Issue
Block a user