Compare commits
11 Commits
f502104a6e
..
dev
| Author | SHA1 | Date | |
|---|---|---|---|
| ecdc76b068 | |||
| 8ee4af1a48 | |||
| 03c07cb5c4 | |||
| ef70bcf51e | |||
| 2fb1741100 | |||
| af995d1d76 | |||
| 014ec5310c | |||
| d53661b9a0 | |||
| 8704b5d249 | |||
| 2186b829aa | |||
| e8237f4610 |
Generated
+1
@@ -6,6 +6,7 @@
|
|||||||
<sourceFolder url="file://$MODULE_DIR$/lib_example/src" isTestSource="false" />
|
<sourceFolder url="file://$MODULE_DIR$/lib_example/src" isTestSource="false" />
|
||||||
<sourceFolder url="file://$MODULE_DIR$/libk/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$/libm/src" isTestSource="false" />
|
||||||
|
<sourceFolder url="file://$MODULE_DIR$/kernel_fonts/src" isTestSource="false" />
|
||||||
<excludeFolder url="file://$MODULE_DIR$/target" />
|
<excludeFolder url="file://$MODULE_DIR$/target" />
|
||||||
</content>
|
</content>
|
||||||
<orderEntry type="inheritedJdk" />
|
<orderEntry type="inheritedJdk" />
|
||||||
|
|||||||
Generated
+5
@@ -0,0 +1,5 @@
|
|||||||
|
<component name="ProjectCodeStyleConfiguration">
|
||||||
|
<state>
|
||||||
|
<option name="PREFERRED_PROJECT_CODE_STYLE" value="Default" />
|
||||||
|
</state>
|
||||||
|
</component>
|
||||||
Vendored
+2
-1
@@ -5,5 +5,6 @@
|
|||||||
"editor.defaultFormatter": "rust-lang.rust-analyzer",
|
"editor.defaultFormatter": "rust-lang.rust-analyzer",
|
||||||
"editor.formatOnSave": true
|
"editor.formatOnSave": true
|
||||||
},
|
},
|
||||||
"rust-analyzer.check.command": "clippy"
|
"rust-analyzer.check.command": "clippy",
|
||||||
|
"rust-analyzer.cargo.buildScripts.enable": true
|
||||||
}
|
}
|
||||||
Generated
+14
@@ -99,6 +99,12 @@ dependencies = [
|
|||||||
"syn",
|
"syn",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "elf"
|
||||||
|
version = "0.7.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4445909572dbd556c457c849c4ca58623d84b27c8fff1e74b0b4227d8b90d17b"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "fnv"
|
name = "fnv"
|
||||||
version = "1.0.7"
|
version = "1.0.7"
|
||||||
@@ -111,7 +117,9 @@ version = "0.1.0"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"cc",
|
"cc",
|
||||||
"crossbeam",
|
"crossbeam",
|
||||||
|
"elf",
|
||||||
"futures-util",
|
"futures-util",
|
||||||
|
"gimli",
|
||||||
"libm",
|
"libm",
|
||||||
"limine",
|
"limine",
|
||||||
"linked_list_allocator",
|
"linked_list_allocator",
|
||||||
@@ -145,6 +153,12 @@ dependencies = [
|
|||||||
"pin-utils",
|
"pin-utils",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "gimli"
|
||||||
|
version = "0.31.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ident_case"
|
name = "ident_case"
|
||||||
version = "1.0.1"
|
version = "1.0.1"
|
||||||
|
|||||||
@@ -19,6 +19,8 @@ futures-util = { version = "0.3.31", default-features = false, features = [
|
|||||||
"alloc",
|
"alloc",
|
||||||
] }
|
] }
|
||||||
linked_list_allocator = { version = "0.10.5", features = ["use_spin"] }
|
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]
|
[build-dependencies]
|
||||||
cc = "1.2.14"
|
cc = "1.2.14"
|
||||||
|
|||||||
+1
-2
@@ -62,9 +62,8 @@ SECTIONS
|
|||||||
*(COMMON)
|
*(COMMON)
|
||||||
} :data
|
} :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/ : {
|
/DISCARD/ : {
|
||||||
*(.eh_frame*)
|
|
||||||
*(.note .note.*)
|
*(.note .note.*)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,14 @@
|
|||||||
|
#![expect(unused)]
|
||||||
|
|
||||||
use core::arch::x86_64::__cpuid;
|
use core::arch::x86_64::__cpuid;
|
||||||
|
|
||||||
use crate::arch::x86_64::memory::memory_map::PHYSICAL_MEMORY_OFFSET;
|
use crate::arch::x86_64::memory::mapping::PHYSICAL_MEMORY_OFFSET;
|
||||||
use crate::serial_print;
|
use crate::{debugln, serial_print, serial_println};
|
||||||
use x86_64::{
|
use x86_64::{
|
||||||
PhysAddr, VirtAddr,
|
PhysAddr, VirtAddr,
|
||||||
structures::paging::{Mapper, Page, PageTableFlags, PhysFrame, Size4KiB},
|
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::cpu::msr::*;
|
||||||
use crate::arch::x86_64::memory::{FRAME_ALLOCATOR, OFFSET_PAGE_TABLE};
|
use crate::arch::x86_64::memory::{FRAME_ALLOCATOR, OFFSET_PAGE_TABLE};
|
||||||
|
|
||||||
@@ -26,9 +28,11 @@ const CPUID_FEAT_EDX_APIC: u64 = 1 << 9; // the cpuid instruction will return th
|
|||||||
|
|
||||||
fn set_apic_base_enable(apic: PhysAddr) {
|
fn set_apic_base_enable(apic: PhysAddr) {
|
||||||
let rax = (apic.as_u64() & 0xfffff0000) | IA32_APIC_BASE_MSR_ENABLE;
|
let rax = (apic.as_u64() & 0xfffff0000) | IA32_APIC_BASE_MSR_ENABLE;
|
||||||
|
debugln!("apic {:?}", PhysAddr::new(rax));
|
||||||
cpu_set_msr(IA32_APIC_BASE_MSR, rax);
|
cpu_set_msr(IA32_APIC_BASE_MSR, rax);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
fn set_apic_base_disable(apic: PhysAddr) {
|
fn set_apic_base_disable(apic: PhysAddr) {
|
||||||
let rax = (apic.as_u64() & 0xfffff0000) & IA32_APIC_BASE_MSR_DISABLE;
|
let rax = (apic.as_u64() & 0xfffff0000) & IA32_APIC_BASE_MSR_DISABLE;
|
||||||
cpu_set_msr(IA32_APIC_BASE_MSR, rax);
|
cpu_set_msr(IA32_APIC_BASE_MSR, rax);
|
||||||
@@ -37,22 +41,29 @@ fn set_apic_base_disable(apic: PhysAddr) {
|
|||||||
fn get_apic_base() -> PhysAddr {
|
fn get_apic_base() -> PhysAddr {
|
||||||
let mut value: u64 = 0;
|
let mut value: u64 = 0;
|
||||||
cpu_get_msr(IA32_APIC_BASE_MSR, &mut value);
|
cpu_get_msr(IA32_APIC_BASE_MSR, &mut value);
|
||||||
|
|
||||||
|
debugln!("apic base {:#x}", value);
|
||||||
|
|
||||||
PhysAddr::new(value & 0xfffff0000)
|
PhysAddr::new(value & 0xfffff0000)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn write_apic_register(apic_base: &VirtAddr, reg: u8, value: u32) {
|
fn write_apic_register(apic_base: &PhysAddr, reg: u64, value: u32) {
|
||||||
let apic_base = apic_base.as_u64();
|
let apic_base = apic_base.as_u64();
|
||||||
let reg_addr = (apic_base & 0xFFFFF0000) + reg as u64;
|
let reg_addr = (apic_base & 0xFFFFF0000) + reg;
|
||||||
unsafe { *(reg_addr as *mut u32) = value };
|
|
||||||
|
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: &VirtAddr, reg: u8) -> u32 {
|
fn read_apic_register(apic_base: &PhysAddr, reg: u64) -> u32 {
|
||||||
let apic_base = apic_base.as_u64();
|
let apic_base = apic_base.as_u64();
|
||||||
|
let reg_addr = (apic_base & 0xFFFFF0000) + reg;
|
||||||
serial_print!("got apic base");
|
let virt_addr = unsafe { phys_to_virt(PhysAddr::new(reg_addr)) };
|
||||||
|
unsafe { *(virt_addr.as_u64() as *const u32) }
|
||||||
let reg_addr = (apic_base & 0xFFFFF0000) + reg as u64;
|
|
||||||
unsafe { *(reg_addr as *const u32) }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn check_apic() -> bool {
|
pub fn check_apic() -> bool {
|
||||||
@@ -68,35 +79,22 @@ unsafe fn phys_to_virt(phys: PhysAddr) -> VirtAddr {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn enable_apic() {
|
pub fn enable_apic() {
|
||||||
let mut mapper = OFFSET_PAGE_TABLE.get().unwrap().lock();
|
let apic_base_physical_addr = get_apic_base();
|
||||||
let mut frame_allocator = FRAME_ALLOCATOR.get().unwrap().lock();
|
set_apic_base_enable(apic_base_physical_addr);
|
||||||
|
|
||||||
let apic_phys_addr = get_apic_base();
|
debugln!("{:?}", apic_base_physical_addr);
|
||||||
set_apic_base_enable(apic_phys_addr);
|
enable_timer();
|
||||||
// map virt address of apic
|
|
||||||
|
|
||||||
let apic_virt = unsafe { phys_to_virt(apic_phys_addr) };
|
write_apic_register(
|
||||||
let page: Page<Size4KiB> = Page::containing_address(apic_virt);
|
&apic_base_physical_addr,
|
||||||
let frame: PhysFrame<Size4KiB> = PhysFrame::containing_address(apic_phys_addr);
|
0xF0,
|
||||||
let flags: PageTableFlags = PageTableFlags::PRESENT | PageTableFlags::WRITABLE;
|
read_apic_register(&apic_base_physical_addr, 0xF0) | 0x1FF
|
||||||
|
);
|
||||||
|
|
||||||
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 memory
|
|
||||||
|
|
||||||
let reg = read_apic_register(&apic_virt, 0xF0);
|
|
||||||
|
|
||||||
serial_print!("ok2");
|
|
||||||
|
|
||||||
write_apic_register(&apic_virt, 0xF0, reg | 0x100);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct Apic {}
|
pub fn enable_timer() {
|
||||||
|
let apic_base = get_apic_base();
|
||||||
pub enum ApicVector {}
|
let current = read_apic_register(&apic_base, 0x320);
|
||||||
|
write_apic_register(&get_apic_base(), 0x320, (current & 0xFFFFFF00) | 0x20);
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
#![expect(unused)]
|
||||||
use core::arch::x86_64::__cpuid;
|
use core::arch::x86_64::__cpuid;
|
||||||
use spin::Lazy;
|
use spin::Lazy;
|
||||||
use x86_64::registers::model_specific::Msr;
|
use x86_64::registers::model_specific::Msr;
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
#![allow(clippy::missing_safety_doc)]
|
||||||
|
|
||||||
use x86_64::instructions::port::Port;
|
use x86_64::instructions::port::Port;
|
||||||
|
|
||||||
const CMD_INIT: u8 = 0x11;
|
const CMD_INIT: u8 = 0x11;
|
||||||
|
|||||||
@@ -2,14 +2,17 @@ use core::fmt;
|
|||||||
use spin::{Lazy, Mutex};
|
use spin::{Lazy, Mutex};
|
||||||
use x86_64::instructions::interrupts;
|
use x86_64::instructions::interrupts;
|
||||||
|
|
||||||
use crate::arch::x86_64::drivers::framebuffer::{colour::Colour, display::FRAMEBUFFER_WRITER};
|
use crate::arch::x86_64::drivers::framebuffer::{
|
||||||
|
colour::Colour, display::FRAMEBUFFER_WRITER,
|
||||||
|
};
|
||||||
|
|
||||||
use crate::resources::font::{FONT_SPLEEN_8X16, Font};
|
use crate::resources::font::{FONT_SPLEEN_8X16, Font};
|
||||||
|
|
||||||
static FONT_WIDTH: u32 = 8;
|
static FONT_WIDTH: u32 = 8;
|
||||||
static FONT_HEIGHT: u32 = 16;
|
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) {
|
pub fn screensize_chars() -> (u32, u32) {
|
||||||
let writer = WRITER.lock();
|
let writer = WRITER.lock();
|
||||||
@@ -71,21 +74,31 @@ impl Writer {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get the character data from the font array. -- each byte is a row of pixels
|
// Get the character data from the font array. -- each byte is a row of
|
||||||
|
// pixels
|
||||||
let data: &[u8] = self.font.glyph_for(c as u16);
|
let data: &[u8] = self.font.glyph_for(c as u16);
|
||||||
|
|
||||||
if let Some(writer) = FRAMEBUFFER_WRITER.lock().as_mut() {
|
if let Some(writer) = FRAMEBUFFER_WRITER.lock().as_mut() {
|
||||||
for (row, line) in data.iter().enumerate().take(16) {
|
for (row, line) in data.iter().enumerate().take(16) {
|
||||||
for col in 0..8 {
|
for col in 0..8 {
|
||||||
let pixel_x: u32 = self.text_col * FONT_WIDTH + col;
|
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 {
|
if line & (0x80 >> col) != 0 {
|
||||||
// Write the foreground color
|
// Write the foreground color
|
||||||
writer.write_pixel(pixel_x as usize, pixel_y as usize, self.fg_color);
|
writer.write_pixel(
|
||||||
|
pixel_x as usize,
|
||||||
|
pixel_y as usize,
|
||||||
|
self.fg_color,
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
// Write the background color
|
// Write the background color
|
||||||
writer.write_pixel(pixel_x as usize, pixel_y as usize, self.bg_color);
|
writer.write_pixel(
|
||||||
|
pixel_x as usize,
|
||||||
|
pixel_y as usize,
|
||||||
|
self.bg_color,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -117,8 +130,8 @@ impl Writer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Handles the backspace character. TODO: Implement VT-100 style terminal control
|
/// Handles the backspace character. TODO: Implement VT-100 style terminal
|
||||||
/// codes alongside a shell. Not simple.
|
/// control codes alongside a shell. Not simple.
|
||||||
pub fn backspace(&mut self) {
|
pub fn backspace(&mut self) {
|
||||||
if self.text_col > 0 {
|
if self.text_col > 0 {
|
||||||
self.text_col -= 1;
|
self.text_col -= 1;
|
||||||
@@ -224,12 +237,12 @@ macro_rules! print {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[macro_export]
|
#[macro_export]
|
||||||
macro_rules! printlnerr {
|
macro_rules! eprintln {
|
||||||
() => ($crate::printerr!("\n"));
|
() => ($crate::printerr!("\n"));
|
||||||
($($arg:tt)*) => ($crate::printerr!("{}\n", format_args!($($arg)*)));
|
($($arg:tt)*) => ($crate::eprint!("{}\n", format_args!($($arg)*)));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[macro_export]
|
#[macro_export]
|
||||||
macro_rules! printerr {
|
macro_rules! eprint {
|
||||||
($($arg:tt)*) => ($crate::prelude::_print_err(format_args!($($arg)*)));
|
($($arg:tt)*) => ($crate::prelude::_print_err(format_args!($($arg)*)));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,9 +19,14 @@ impl From<Colour> for u32 {
|
|||||||
fn from(val: Colour) -> Self {
|
fn from(val: Colour) -> Self {
|
||||||
match val {
|
match val {
|
||||||
Colour::ARGB(a, r, g, b) => {
|
Colour::ARGB(a, r, g, b) => {
|
||||||
(a as u32) << 24 | (r as u32) << 16 | (g as u32) << 8 | (b as u32)
|
(a as u32) << 24
|
||||||
|
| (r as u32) << 16
|
||||||
|
| (g as u32) << 8
|
||||||
|
| (b as u32)
|
||||||
|
}
|
||||||
|
Colour::RGB(r, g, b) => {
|
||||||
|
((r as u32) << 16) | (g as u32) << 8 | (b as u32)
|
||||||
}
|
}
|
||||||
Colour::RGB(r, g, b) => ((r as u32) << 16) | (g as u32) << 8 | (b as u32),
|
|
||||||
Colour::HexARGB(hex) => hex,
|
Colour::HexARGB(hex) => hex,
|
||||||
Colour::Black => 0xFF000000,
|
Colour::Black => 0xFF000000,
|
||||||
Colour::Blue => 0xFF0000FF,
|
Colour::Blue => 0xFF0000FF,
|
||||||
@@ -38,7 +43,9 @@ impl From<Colour> for u32 {
|
|||||||
impl core::fmt::Display for Colour {
|
impl core::fmt::Display for Colour {
|
||||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||||
match self {
|
match self {
|
||||||
Self::ARGB(r, g, b, a) => write!(f, "RGBA(#{:x}{:x}{:x}{:x})", 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::HexARGB(hex) => write!(f, "Hex(#{:x})", hex),
|
||||||
Self::Black => write!(f, "Black"),
|
Self::Black => write!(f, "Black"),
|
||||||
|
|||||||
@@ -10,17 +10,19 @@ use core::panic;
|
|||||||
use limine::framebuffer::Framebuffer;
|
use limine::framebuffer::Framebuffer;
|
||||||
use spin::{Lazy, Mutex};
|
use spin::{Lazy, Mutex};
|
||||||
|
|
||||||
pub static FRAMEBUFFER_WRITER: Lazy<Mutex<Option<FramebufferWriter>>> = Lazy::new(|| {
|
pub static FRAMEBUFFER_WRITER: Lazy<Mutex<Option<FramebufferWriter>>> =
|
||||||
Mutex::new(FRAMEBUFFER_REQUEST.get_response().map_or_else(
|
Lazy::new(|| {
|
||||||
|| {
|
Mutex::new(FRAMEBUFFER_REQUEST.get_response().map_or_else(
|
||||||
panic!("Framebuffer request failed");
|
|| {
|
||||||
},
|
panic!("Framebuffer request failed");
|
||||||
|framebuffer_response| {
|
},
|
||||||
let framebuffer = framebuffer_response.framebuffers().next().unwrap();
|
|framebuffer_response| {
|
||||||
Some(FramebufferWriter::new(framebuffer))
|
let framebuffer =
|
||||||
},
|
framebuffer_response.framebuffers().next().unwrap();
|
||||||
))
|
Some(FramebufferWriter::new(framebuffer))
|
||||||
});
|
},
|
||||||
|
))
|
||||||
|
});
|
||||||
|
|
||||||
/// The updated writer stores necessary fields from the [Framebuffer].
|
/// The updated writer stores necessary fields from the [Framebuffer].
|
||||||
/// This ensures that the contained types are Send, as Framebuffer was
|
/// This ensures that the contained types are Send, as Framebuffer was
|
||||||
@@ -28,7 +30,8 @@ pub static FRAMEBUFFER_WRITER: Lazy<Mutex<Option<FramebufferWriter>>> = Lazy::ne
|
|||||||
///
|
///
|
||||||
/// It also avoids the requirement for lifetimes.
|
/// It also avoids the requirement for lifetimes.
|
||||||
///
|
///
|
||||||
/// Note this does not implement Writer as these functions only handle drawing pixels.
|
/// Note this does not implement Writer as these functions only handle drawing
|
||||||
|
/// pixels.
|
||||||
pub struct FramebufferWriter {
|
pub struct FramebufferWriter {
|
||||||
pitch: u64,
|
pitch: u64,
|
||||||
bpp: u16,
|
bpp: u16,
|
||||||
|
|||||||
@@ -6,20 +6,24 @@ use core::{
|
|||||||
use crate::println;
|
use crate::println;
|
||||||
use crossbeam::queue::ArrayQueue;
|
use crossbeam::queue::ArrayQueue;
|
||||||
use futures_util::{Stream, StreamExt, task::AtomicWaker};
|
use futures_util::{Stream, StreamExt, task::AtomicWaker};
|
||||||
use pc_keyboard::{DecodedKey, HandleControl, KeyCode, Keyboard, ScancodeSet1, layouts::Uk105Key};
|
use pc_keyboard::{
|
||||||
|
DecodedKey, HandleControl, KeyCode, Keyboard, ScancodeSet1,
|
||||||
|
layouts::Uk105Key,
|
||||||
|
};
|
||||||
use spin::{Lazy, Mutex, Once};
|
use spin::{Lazy, Mutex, Once};
|
||||||
|
|
||||||
static KBD_QUEUE: Once<ArrayQueue<u8>> = Once::new();
|
static KBD_QUEUE: Once<ArrayQueue<u8>> = Once::new();
|
||||||
static WAKER: AtomicWaker = AtomicWaker::new();
|
static WAKER: AtomicWaker = AtomicWaker::new();
|
||||||
|
|
||||||
pub static KEYBOARD: Lazy<Mutex<Keyboard<Uk105Key, ScancodeSet1>>> = Lazy::new(|| {
|
pub static KEYBOARD: Lazy<Mutex<Keyboard<Uk105Key, ScancodeSet1>>> =
|
||||||
Mutex::new(Keyboard::new(
|
Lazy::new(|| {
|
||||||
ScancodeSet1::new(),
|
Mutex::new(Keyboard::new(
|
||||||
// TODO: Expose an API to change the default KB layout.
|
ScancodeSet1::new(),
|
||||||
Uk105Key,
|
// TODO: Expose an API to change the default KB layout.
|
||||||
HandleControl::Ignore,
|
Uk105Key,
|
||||||
))
|
HandleControl::Ignore,
|
||||||
});
|
))
|
||||||
|
});
|
||||||
pub static SCANCODE_STREAM: Lazy<Mutex<ScancodeStream>> =
|
pub static SCANCODE_STREAM: Lazy<Mutex<ScancodeStream>> =
|
||||||
Lazy::new(|| Mutex::new(ScancodeStream::new()));
|
Lazy::new(|| Mutex::new(ScancodeStream::new()));
|
||||||
|
|
||||||
@@ -59,7 +63,10 @@ impl Default for ScancodeStream {
|
|||||||
impl Stream for ScancodeStream {
|
impl Stream for ScancodeStream {
|
||||||
type Item = u8;
|
type Item = u8;
|
||||||
|
|
||||||
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
fn poll_next(
|
||||||
|
self: Pin<&mut Self>,
|
||||||
|
cx: &mut Context<'_>,
|
||||||
|
) -> Poll<Option<Self::Item>> {
|
||||||
let queue = KBD_QUEUE.get().unwrap();
|
let queue = KBD_QUEUE.get().unwrap();
|
||||||
|
|
||||||
if let Some(scancode) = queue.pop() {
|
if let Some(scancode) = queue.pop() {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::serial_print;
|
use crate::{debug, serial_print};
|
||||||
use pic8259::ChainedPics;
|
use pic8259::ChainedPics;
|
||||||
use x86_64::registers::control::Cr2;
|
use x86_64::registers::control::Cr2;
|
||||||
use x86_64::structures::idt::{InterruptDescriptorTable, InterruptStackFrame, PageFaultErrorCode};
|
use x86_64::structures::idt::{InterruptDescriptorTable, InterruptStackFrame, PageFaultErrorCode};
|
||||||
@@ -117,6 +117,7 @@ extern "x86-interrupt" fn keyboard_interrupt_handler(_stack_frame: InterruptStac
|
|||||||
}
|
}
|
||||||
|
|
||||||
extern "x86-interrupt" fn timer_interrupt_handler(_stack_frame: InterruptStackFrame) {
|
extern "x86-interrupt" fn timer_interrupt_handler(_stack_frame: InterruptStackFrame) {
|
||||||
|
debug!("Timer Interrupt");
|
||||||
unsafe {
|
unsafe {
|
||||||
PICS.lock()
|
PICS.lock()
|
||||||
.notify_end_of_interrupt(InterruptIndex::Timer.as_u8());
|
.notify_end_of_interrupt(InterruptIndex::Timer.as_u8());
|
||||||
@@ -137,7 +138,8 @@ extern "x86-interrupt" fn page_fault_handler(
|
|||||||
|
|
||||||
let frame = f.allocate_frame().unwrap();
|
let frame = f.allocate_frame().unwrap();
|
||||||
let flags = PageTableFlags::PRESENT | PageTableFlags::WRITABLE;
|
let flags = PageTableFlags::PRESENT | PageTableFlags::WRITABLE;
|
||||||
let page: Page<Size4KiB> = Page::containing_address(Cr2::read().unwrap());
|
let page: Page<Size4KiB> =
|
||||||
|
Page::containing_address(Cr2::read().unwrap());
|
||||||
|
|
||||||
unsafe {
|
unsafe {
|
||||||
let mut mapper = OFFSET_PAGE_TABLE.get().unwrap().lock();
|
let mut mapper = OFFSET_PAGE_TABLE.get().unwrap().lock();
|
||||||
|
|||||||
@@ -1,21 +1,45 @@
|
|||||||
|
use crate::{debugln, serial_print};
|
||||||
use core::alloc::{GlobalAlloc, Layout};
|
use core::alloc::{GlobalAlloc, Layout};
|
||||||
use core::ptr;
|
use core::ptr;
|
||||||
use spin::{Mutex, MutexGuard};
|
use spin::{Mutex, MutexGuard};
|
||||||
use x86_64::structures::paging::{Size4KiB, mapper::MapToError};
|
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.
|
/// We are currently using a linked list heap allocator which uses our underlying page allocator.
|
||||||
#[global_allocator]
|
#[global_allocator]
|
||||||
/// This is now Rust's global allocator, so we can use stuff requiring heap allocations.
|
/// This is now Rust's global allocator, so we can use stuff requiring heap allocations.
|
||||||
static ALLOCATOR: Locked<FoundryAllocator> = Locked::new(FoundryAllocator::new());
|
static ALLOCATOR: Locked<FoundryAllocator> = Locked::new(FoundryAllocator::new());
|
||||||
|
|
||||||
pub const HEAP_START: usize = 0x4444_4444_0000;
|
|
||||||
pub const HEAP_SIZE: usize = 1024 * 1024 * 1024;
|
|
||||||
|
|
||||||
/// Sets up the heap using the backing page frame allocator.
|
/// 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>> {
|
pub unsafe fn init_heap() -> Result<(), MapToError<Size4KiB>> {
|
||||||
unsafe {
|
unsafe {
|
||||||
// code to allocate frames is now done in the page fault interrupt handler!
|
// code to allocate frames is now done in the page fault interrupt handler!
|
||||||
ALLOCATOR.lock().init(HEAP_START, HEAP_SIZE);
|
ALLOCATOR.lock().init(HEAP_VIRTUAL_SPACE, HEAP_SIZE);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -36,7 +60,7 @@ impl<T> Locked<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const BLOCK_SIZES: &[usize] = &[8, 16, 32, 64, 128, 256, 512, 1024, 2048];
|
const BLOCK_SIZES: &[usize] = &[8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096];
|
||||||
|
|
||||||
struct ListNode {
|
struct ListNode {
|
||||||
next: Option<&'static mut ListNode>,
|
next: Option<&'static mut ListNode>,
|
||||||
@@ -61,7 +85,15 @@ impl FoundryAllocator {
|
|||||||
fallback: Locked::new(FoundryFallbackAllocator::new()),
|
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) {
|
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 {
|
unsafe {
|
||||||
self.fallback.lock().init(heap_start, heap_size);
|
self.fallback.lock().init(heap_start, heap_size);
|
||||||
}
|
}
|
||||||
@@ -86,7 +118,9 @@ unsafe impl GlobalAlloc for Locked<FoundryAllocator> {
|
|||||||
match allocator.list_heads[index].take() {
|
match allocator.list_heads[index].take() {
|
||||||
Some(node) => {
|
Some(node) => {
|
||||||
allocator.list_heads[index] = node.next.take();
|
allocator.list_heads[index] = node.next.take();
|
||||||
node as *mut ListNode as *mut u8
|
let ptr = node as *mut ListNode as *mut u8;
|
||||||
|
ensure_mapped(VirtAddr::new(ptr as u64));
|
||||||
|
ptr
|
||||||
}
|
}
|
||||||
None => {
|
None => {
|
||||||
// no block exists in list => allocate new block
|
// no block exists in list => allocate new block
|
||||||
@@ -157,6 +191,11 @@ impl FoundryFallbackAllocator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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) {
|
pub unsafe fn init(&mut self, heap_start: usize, heap_size: usize) {
|
||||||
unsafe { self.add_region(heap_start, heap_size) };
|
unsafe { self.add_region(heap_start, heap_size) };
|
||||||
}
|
}
|
||||||
@@ -165,6 +204,10 @@ impl FoundryFallbackAllocator {
|
|||||||
unsafe {
|
unsafe {
|
||||||
let mut node = FallbackListNode::new(size);
|
let mut node = FallbackListNode::new(size);
|
||||||
node.next = self.head.next.take();
|
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;
|
let node_ptr = addr as *mut FallbackListNode;
|
||||||
node_ptr.write(node);
|
node_ptr.write(node);
|
||||||
self.head.next = Some(&mut *node_ptr);
|
self.head.next = Some(&mut *node_ptr);
|
||||||
@@ -238,7 +281,9 @@ unsafe impl GlobalAlloc for Locked<FoundryFallbackAllocator> {
|
|||||||
if excess_size > 0 {
|
if excess_size > 0 {
|
||||||
unsafe { allocator.add_region(alloc_end, excess_size) };
|
unsafe { allocator.add_region(alloc_end, excess_size) };
|
||||||
}
|
}
|
||||||
alloc_start as *mut u8
|
let ptr = alloc_start as *mut u8;
|
||||||
|
ensure_mapped(VirtAddr::new(ptr as u64));
|
||||||
|
ptr
|
||||||
} else {
|
} else {
|
||||||
ptr::null_mut()
|
ptr::null_mut()
|
||||||
}
|
}
|
||||||
@@ -246,10 +291,16 @@ unsafe impl GlobalAlloc for Locked<FoundryFallbackAllocator> {
|
|||||||
|
|
||||||
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
|
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
|
||||||
let mut allocator = self.lock();
|
let mut allocator = self.lock();
|
||||||
|
|
||||||
// perform layout adjustments
|
// perform layout adjustments
|
||||||
let (size, _) = FoundryFallbackAllocator::size_align(layout);
|
let (size, _) = FoundryFallbackAllocator::size_align(layout);
|
||||||
|
|
||||||
unsafe { allocator.add_region(ptr as usize, size) }
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,2 +1,3 @@
|
|||||||
pub mod heap_alloc;
|
pub mod heap_alloc;
|
||||||
|
pub(crate) mod page_alloc;
|
||||||
pub mod stack_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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,46 +1,69 @@
|
|||||||
use x86_64::structures::paging::{mapper, FrameAllocator, Mapper, Page, Size4KiB};
|
use crate::arch::x86_64::memory::STACK_VIRTUAL_SPACE;
|
||||||
use x86_64::VirtAddr;
|
use x86_64::VirtAddr;
|
||||||
|
use x86_64::structures::paging::{
|
||||||
|
FrameAllocator, Mapper, Page, Size4KiB, mapper,
|
||||||
|
};
|
||||||
|
|
||||||
fn reserve_stack_memory(size_in_pages: u64) -> Page {
|
fn reserve_stack_memory(size_in_pages: u64) -> Page {
|
||||||
use core::sync::atomic::{AtomicU64, Ordering};
|
use core::sync::atomic::{AtomicU64, Ordering};
|
||||||
static STACK_ALLOC_NEXT: AtomicU64 = AtomicU64::new(0x_5555_5555_0000);
|
static STACK_ALLOC_NEXT: AtomicU64 =
|
||||||
let start_addr = VirtAddr::new(STACK_ALLOC_NEXT.fetch_add(
|
AtomicU64::new(STACK_VIRTUAL_SPACE as u64);
|
||||||
size_in_pages * Page::<Size4KiB>::SIZE,
|
let start_addr =
|
||||||
Ordering::Relaxed,
|
VirtAddr::new(STACK_ALLOC_NEXT.fetch_add(
|
||||||
));
|
size_in_pages * Page::<Size4KiB>::SIZE,
|
||||||
|
Ordering::Relaxed,
|
||||||
|
));
|
||||||
Page::from_start_address(start_addr)
|
Page::from_start_address(start_addr)
|
||||||
.expect("`STACK_ALLOC_NEXT` not page aligned")
|
.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(
|
pub unsafe fn alloc_stack(
|
||||||
size_in_pages: u64,
|
size_in_pages: u64,
|
||||||
mapper: &mut impl Mapper<Size4KiB>,
|
mapper: &mut impl Mapper<Size4KiB>,
|
||||||
frame_allocator: &mut impl FrameAllocator<Size4KiB>,
|
frame_allocator: &mut impl FrameAllocator<Size4KiB>,
|
||||||
) -> Result<StackBounds, mapper::MapToError<Size4KiB>> { unsafe {
|
) -> Result<StackBounds, mapper::MapToError<Size4KiB>> {
|
||||||
use x86_64::structures::paging::PageTableFlags as Flags;
|
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(),
|
||||||
let guard_page = reserve_stack_memory(size_in_pages + 1);
|
end: stack_end.start_address(),
|
||||||
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)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||||
pub struct StackBounds {
|
pub struct StackBounds {
|
||||||
@@ -60,4 +83,4 @@ impl StackBounds {
|
|||||||
pub const fn end(&self) -> VirtAddr {
|
pub const fn end(&self) -> VirtAddr {
|
||||||
self.end
|
self.end
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-1
@@ -16,7 +16,8 @@ static HIGHER_HALF_DIRECT_MAP_REQUEST: HhdmRequest = HhdmRequest::new();
|
|||||||
|
|
||||||
#[used]
|
#[used]
|
||||||
#[unsafe(link_section = ".requests")]
|
#[unsafe(link_section = ".requests")]
|
||||||
static KERNEL_ADDRESS_REQUEST: KernelAddressRequest = KernelAddressRequest::new();
|
pub static KERNEL_ADDRESS_REQUEST: KernelAddressRequest =
|
||||||
|
KernelAddressRequest::new();
|
||||||
|
|
||||||
/// ```rs
|
/// ```rs
|
||||||
/// let virt_addr = phys_addr + offset;
|
/// let virt_addr = phys_addr + offset;
|
||||||
@@ -1,15 +1,20 @@
|
|||||||
pub mod allocation;
|
pub mod allocation;
|
||||||
pub mod memory_map;
|
pub mod mapping;
|
||||||
|
pub mod units;
|
||||||
|
|
||||||
// use lib_alloc::allocator::FoundryAllocator;
|
use allocation::page_alloc::FoundryOSFrameAllocator;
|
||||||
use limine::{memory_map::EntryType, response::MemoryMapResponse};
|
|
||||||
use spin::{Mutex, Once};
|
use spin::{Mutex, Once};
|
||||||
|
use units::MemoryUnits::*;
|
||||||
use x86_64::{
|
use x86_64::{
|
||||||
PhysAddr, VirtAddr,
|
VirtAddr,
|
||||||
registers::control::Cr3,
|
registers::control::Cr3,
|
||||||
structures::paging::{FrameAllocator, OffsetPageTable, PageTable, PhysFrame, Size4KiB},
|
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 FRAME_ALLOCATOR: Once<Mutex<FoundryOSFrameAllocator>> = Once::new();
|
||||||
pub static OFFSET_PAGE_TABLE: Once<Mutex<OffsetPageTable>> = Once::new();
|
pub static OFFSET_PAGE_TABLE: Once<Mutex<OffsetPageTable>> = Once::new();
|
||||||
/// Returns a mutable reference to the current level 4 page table.
|
/// Returns a mutable reference to the current level 4 page table.
|
||||||
@@ -19,7 +24,9 @@ pub static OFFSET_PAGE_TABLE: Once<Mutex<OffsetPageTable>> = Once::new();
|
|||||||
/// The caller must ensure that the level 4 page table is not modified
|
/// The caller must ensure that the level 4 page table is not modified
|
||||||
/// simultaneously. The caller must also ensure that the physical memory offset
|
/// simultaneously. The caller must also ensure that the physical memory offset
|
||||||
/// is correct, to ensure that the correct virtual address is constructed.
|
/// is correct, to ensure that the correct virtual address is constructed.
|
||||||
unsafe fn active_l4_table(physical_memory_offset: VirtAddr) -> &'static mut PageTable {
|
unsafe fn active_l4_table(
|
||||||
|
physical_memory_offset: VirtAddr,
|
||||||
|
) -> &'static mut PageTable {
|
||||||
let (level_4_frame, _) = Cr3::read();
|
let (level_4_frame, _) = Cr3::read();
|
||||||
|
|
||||||
let phys_addr = level_4_frame.start_address();
|
let phys_addr = level_4_frame.start_address();
|
||||||
@@ -48,61 +55,8 @@ unsafe fn active_l4_table(physical_memory_offset: VirtAddr) -> &'static mut Page
|
|||||||
pub fn init_page_table(physical_memory_offset: VirtAddr) {
|
pub fn init_page_table(physical_memory_offset: VirtAddr) {
|
||||||
unsafe {
|
unsafe {
|
||||||
let l4_table = active_l4_table(physical_memory_offset);
|
let l4_table = active_l4_table(physical_memory_offset);
|
||||||
let offset_table = OffsetPageTable::new(l4_table, physical_memory_offset);
|
let offset_table =
|
||||||
|
OffsetPageTable::new(l4_table, physical_memory_offset);
|
||||||
OFFSET_PAGE_TABLE.call_once(|| Mutex::new(offset_table));
|
OFFSET_PAGE_TABLE.call_once(|| Mutex::new(offset_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 unsafe fn init(memory_map: &'static MemoryMapResponse) { unsafe {
|
|
||||||
FRAME_ALLOCATOR.call_once(|| Mutex::new(Self {
|
|
||||||
memory_map,
|
|
||||||
next: 0,
|
|
||||||
}));
|
|
||||||
}}
|
|
||||||
|
|
||||||
pub fn count_usable_frames(&self) -> u32 {
|
|
||||||
self.usable_frames().count() as u32
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 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 pagemap.
|
|
||||||
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())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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,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),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,7 +2,6 @@
|
|||||||
//!
|
//!
|
||||||
//! Written by @zxq5 for the most part with code from
|
//! Written by @zxq5 for the most part with code from
|
||||||
//! [here](https://github.com/phil-opp/blog_os/).
|
//! [here](https://github.com/phil-opp/blog_os/).
|
||||||
//!
|
|
||||||
|
|
||||||
use alloc::boxed::Box;
|
use alloc::boxed::Box;
|
||||||
use alloc::collections::BTreeMap;
|
use alloc::collections::BTreeMap;
|
||||||
@@ -81,9 +80,9 @@ impl Executor {
|
|||||||
Some(task) => task,
|
Some(task) => task,
|
||||||
None => continue, // task no longer exists
|
None => continue, // task no longer exists
|
||||||
};
|
};
|
||||||
let waker = waker_cache
|
let waker = waker_cache.entry(task_id).or_insert_with(|| {
|
||||||
.entry(task_id)
|
TaskWaker::new_waker(task_id, task_queue.clone())
|
||||||
.or_insert_with(|| TaskWaker::new_waker(task_id, task_queue.clone()));
|
});
|
||||||
let mut context = Context::from_waker(waker);
|
let mut context = Context::from_waker(waker);
|
||||||
match task.poll(&mut context) {
|
match task.poll(&mut context) {
|
||||||
Poll::Ready(()) => {
|
Poll::Ready(()) => {
|
||||||
@@ -129,7 +128,10 @@ impl TaskWaker {
|
|||||||
self.task_queue.push(self.task_id).expect("task_queue full");
|
self.task_queue.push(self.task_id).expect("task_queue full");
|
||||||
}
|
}
|
||||||
|
|
||||||
fn new_waker(task_id: TaskId, task_queue: Arc<ArrayQueue<TaskId>>) -> Waker {
|
fn new_waker(
|
||||||
|
task_id: TaskId,
|
||||||
|
task_queue: Arc<ArrayQueue<TaskId>>,
|
||||||
|
) -> Waker {
|
||||||
Waker::from(Arc::new(Self {
|
Waker::from(Arc::new(Self {
|
||||||
task_id,
|
task_id,
|
||||||
task_queue,
|
task_queue,
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
#![expect(unused)]
|
||||||
pub mod async_io;
|
pub mod async_io;
|
||||||
pub mod threading;
|
|
||||||
mod taskrunner;
|
mod taskrunner;
|
||||||
|
pub mod threading;
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ pub struct Task {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Task {
|
impl Task {
|
||||||
pub fn new() {}
|
// pub const fn new() {}
|
||||||
|
|
||||||
pub fn run() {}
|
pub const fn run() {}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use x86_64::VirtAddr;
|
|
||||||
use crate::arch::x86_64::memory::allocation::stack_alloc::StackBounds;
|
use crate::arch::x86_64::memory::allocation::stack_alloc::StackBounds;
|
||||||
|
use x86_64::VirtAddr;
|
||||||
|
|
||||||
mod switch;
|
mod switch;
|
||||||
|
|
||||||
@@ -10,8 +10,6 @@ pub struct Thread {
|
|||||||
stack_bounds: Option<StackBounds>,
|
stack_bounds: Option<StackBounds>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||||
pub struct ThreadId(u64);
|
pub struct ThreadId(u64);
|
||||||
|
|
||||||
|
|||||||
+68
-38
@@ -12,35 +12,45 @@
|
|||||||
)]
|
)]
|
||||||
|
|
||||||
extern crate alloc;
|
extern crate alloc;
|
||||||
use crate::{
|
use crate::{arch::x86_64::memory::init_page_table, prelude::*};
|
||||||
arch::x86_64::memory::init_page_table,
|
|
||||||
prelude::*,
|
|
||||||
};
|
|
||||||
use arch::x86_64::memory::allocation::heap_alloc::init_heap;
|
use arch::x86_64::memory::allocation::heap_alloc::init_heap;
|
||||||
use arch::x86_64::memory::memory_map;
|
use arch::x86_64::memory::mapping;
|
||||||
use core::arch::asm;
|
use core::arch::asm;
|
||||||
use limine::BaseRevision;
|
use limine::BaseRevision;
|
||||||
|
use std::unwind;
|
||||||
|
use std::unwind::eh_info::ELF;
|
||||||
use x86_64::VirtAddr;
|
use x86_64::VirtAddr;
|
||||||
use crate::arch::x86_64::memory::FoundryOSFrameAllocator;
|
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 arch;
|
||||||
|
mod panic;
|
||||||
pub mod resources;
|
pub mod resources;
|
||||||
#[allow(unused)] // We aren't using much of this right now.
|
#[allow(unused)] // We aren't using much of this right now.
|
||||||
pub mod std;
|
pub mod std;
|
||||||
pub mod util;
|
pub mod util;
|
||||||
|
|
||||||
pub mod prelude {
|
pub mod prelude {
|
||||||
pub use crate::std::io::{_print, _print_log, _serial_write};
|
|
||||||
pub use crate::{
|
pub use crate::{
|
||||||
print, print_log, printerr, println, println_log, printlnerr, serial_print, serial_println,
|
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.
|
/// Sets the base revision to the latest revision supported by the crate.
|
||||||
/// See specification for further info.
|
/// See specification for further info.
|
||||||
/// Be sure to mark all limine requests with #[used], otherwise they may be removed by the compiler.
|
/// Be sure to mark all limine requests with #[used], otherwise they may be
|
||||||
|
/// removed by the compiler.
|
||||||
#[used]
|
#[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")]
|
#[unsafe(link_section = ".requests")]
|
||||||
static BASE_REVISION: BaseRevision = BaseRevision::new();
|
static BASE_REVISION: BaseRevision = BaseRevision::new();
|
||||||
|
|
||||||
@@ -62,58 +72,78 @@ pub fn hcf() -> ! {
|
|||||||
|
|
||||||
pub fn boot() -> Result<(), &'static str> {
|
pub fn boot() -> Result<(), &'static str> {
|
||||||
if !BASE_REVISION.is_supported() {
|
if !BASE_REVISION.is_supported() {
|
||||||
return Err("base revision not supported");
|
return Err("Base revision not supported");
|
||||||
}
|
}
|
||||||
|
|
||||||
use arch::x86_64::{gdt, interrupts};
|
use arch::x86_64::{gdt, interrupts};
|
||||||
|
|
||||||
let memory_map = memory_map::get_memory_map();
|
let memory_map = mapping::get_memory_map();
|
||||||
|
|
||||||
print_log!(" Initialising Serial... ");
|
print_log!(" Initialising Serial... ");
|
||||||
if arch::x86_64::drivers::serial::init().is_err() {
|
let res = arch::x86_64::drivers::serial::init();
|
||||||
println_log!("[Not Detected]")
|
serial_print!(" Initialising Serial... ");
|
||||||
|
if res.is_err() {
|
||||||
|
debugln!("[Not Detected]")
|
||||||
} else {
|
} else {
|
||||||
println_log!("[Success]");
|
debugln!("[Success]");
|
||||||
}
|
}
|
||||||
|
|
||||||
print_log!(" Setting Up Global Descriptor Table... ");
|
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();
|
gdt::init();
|
||||||
println_log!("[Success]");
|
debugln!("[Success]");
|
||||||
|
|
||||||
print_log!(" Setting Up Interrupt Descriptor Table... ");
|
debug!(" Setting Up Interrupt Descriptor Table... ");
|
||||||
interrupts::init_idt();
|
interrupts::init_idt();
|
||||||
println_log!("[Success]");
|
debugln!("[Success]");
|
||||||
|
|
||||||
print_log!(" Initialising Memory Subsystem... ");
|
debugln!(" Initialising Memory Subsystem... ");
|
||||||
let physical_memory_offset = VirtAddr::new(*memory_map::PHYSICAL_MEMORY_OFFSET);
|
let physical_memory_offset = VirtAddr::new(*mapping::PHYSICAL_MEMORY_OFFSET);
|
||||||
init_page_table(physical_memory_offset);
|
init_page_table(physical_memory_offset);
|
||||||
println_log!("[Success]");
|
FoundryOSFrameAllocator::init(memory_map);
|
||||||
|
let available_bytes = FRAME_ALLOCATOR.get().unwrap().lock().available_memory();
|
||||||
|
debugln!(" => Available Memory: {}", MemoryUnits::from_bytes(available_bytes as usize));
|
||||||
|
|
||||||
print_log!(" Setting Up Page Table... ");
|
debugln!("[Success]");
|
||||||
unsafe { FoundryOSFrameAllocator::init(memory_map) };
|
|
||||||
println_log!("[Success]");
|
|
||||||
|
|
||||||
print_log!(" Initialising Heap... ");
|
debugln!(" Initialising Heap... ");
|
||||||
if unsafe { init_heap() }.is_err() {
|
if unsafe { init_heap() }.is_err() {
|
||||||
return Err("Failed to initialise heap: error");
|
return Err("Failed to initialise heap: error");
|
||||||
}
|
}
|
||||||
println_log!("[Success]");
|
debugln!(" [Success]");
|
||||||
|
|
||||||
print_log!(" Enabling PICs... ");
|
// debug!(" Enabling PICs... ");
|
||||||
interrupts::enable_pic();
|
// interrupts::enable_pic();
|
||||||
println_log!("[Success]");
|
// debugln!("[Success]");
|
||||||
|
|
||||||
// print_log!(" Disabling PICs... ");
|
debug!(" Disabling PICs... ");
|
||||||
// interrupts::disable_pic();
|
interrupts::disable_pic();
|
||||||
// println_log!("[Success]");
|
debugln!("[Success]");
|
||||||
|
|
||||||
// print_log!(" Initialising APIC");
|
debug!(" Initialising APIC... ");
|
||||||
// enable_apic();
|
enable_apic();
|
||||||
// println_log!("[Success]");
|
debugln!("[Success]");
|
||||||
|
|
||||||
print_log!(" Enabling Interrupts... ");
|
debug!(" Enabling Interrupts... ");
|
||||||
x86_64::instructions::interrupts::enable();
|
x86_64::instructions::interrupts::enable();
|
||||||
println_log!("[Success]");
|
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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-8
@@ -15,14 +15,8 @@ extern "C" fn kmain() -> ! {
|
|||||||
panic!("{}", err);
|
panic!("{}", err);
|
||||||
}
|
}
|
||||||
|
|
||||||
println_log!("[ Kernel Initialised Successfully ] ");
|
println_log!(" [ Kernel Initialised Successfully ] ");
|
||||||
|
|
||||||
let dimensions = screensize_chars();
|
|
||||||
let dimensions2 = screensize_px();
|
|
||||||
|
|
||||||
println!("Dimensions: {}x{} (px)", dimensions2.0, dimensions2.1);
|
|
||||||
println!("Dimensions: {}x{} (chars)", dimensions.0, dimensions.1);
|
|
||||||
|
|
||||||
// println!("TESTING :: Allocation");
|
// println!("TESTING :: Allocation");
|
||||||
// let somevec = vec![0; 1_000_000];
|
// let somevec = vec![0; 1_000_000];
|
||||||
// println!("{:?}", somevec);
|
// println!("{:?}", somevec);
|
||||||
|
|||||||
@@ -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,8 +1,8 @@
|
|||||||
use libm::include_font;
|
use libm::include_font;
|
||||||
pub static FONT_SPLEEN_8X16: 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 static FONT_CP850_8X16: Font =
|
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(pub [[u8; 16]; 512]);
|
||||||
@@ -39,8 +39,10 @@ impl Font {
|
|||||||
pub const fn height(&self) -> usize {
|
pub const fn height(&self) -> usize {
|
||||||
self.height
|
self.height
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn default() -> &'static Self {
|
impl Default for Font {
|
||||||
&FONT_CP850_8X16
|
fn default() -> Self {
|
||||||
|
FONT_CP850_8X16
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,7 +8,10 @@ pub mod window;
|
|||||||
pub trait Application {
|
pub trait Application {
|
||||||
type Output;
|
type Output;
|
||||||
|
|
||||||
fn run(&mut self, args: Vec<String>) -> impl Future<Output = Result<Self::Output, Error>> + Send;
|
fn run(
|
||||||
|
&mut self,
|
||||||
|
args: Vec<String>,
|
||||||
|
) -> impl Future<Output = Result<Self::Output, Error>> + Send;
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
|
|||||||
@@ -11,20 +11,31 @@ pub struct Frame<'f> {
|
|||||||
impl<'a> Frame<'a> {
|
impl<'a> Frame<'a> {
|
||||||
pub fn new(window: &'a Window) -> Self {
|
pub fn new(window: &'a Window) -> Self {
|
||||||
Self {
|
Self {
|
||||||
data: vec![vec![Colour::Black; window.dimensions().x()]; window.dimensions().y()],
|
data: vec![
|
||||||
|
vec![Colour::Black; window.dimensions().x()];
|
||||||
|
window.dimensions().y()
|
||||||
|
],
|
||||||
window,
|
window,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn render(&self) -> Result<(), RenderError> {
|
pub fn render(&self) -> Result<(), RenderError> {
|
||||||
let data: Vec<&[Colour]> = self.data.iter().map(|v| v.as_slice()).collect::<Vec<_>>();
|
let data: Vec<&[Colour]> =
|
||||||
|
self.data.iter().map(|v| v.as_slice()).collect::<Vec<_>>();
|
||||||
self.window
|
self.window
|
||||||
.render(data.as_slice())
|
.render(data.as_slice())
|
||||||
.map_err(|_| RenderError::Generic)
|
.map_err(|_| RenderError::Generic)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn write_pixel(&mut self, x: usize, y: usize, color: Colour) -> Result<(), RenderError> {
|
pub fn write_pixel(
|
||||||
if x >= self.window.dimensions().x() || y >= self.window.dimensions().y() {
|
&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);
|
return Err(RenderError::Generic);
|
||||||
}
|
}
|
||||||
self.data[y][x] = color;
|
self.data[y][x] = color;
|
||||||
|
|||||||
@@ -24,7 +24,8 @@ impl Window {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn render(&self, _data: &[&[Colour]]) -> Result<(), RenderError> {
|
pub fn render(&self, _data: &[&[Colour]]) -> Result<(), RenderError> {
|
||||||
// TODO: error handling!! the kernel should return an error in some cases
|
// TODO: error handling!! the kernel should return an error in some
|
||||||
|
// cases
|
||||||
if let Some(fb) = FRAMEBUFFER_WRITER.lock().as_mut() {
|
if let Some(fb) = FRAMEBUFFER_WRITER.lock().as_mut() {
|
||||||
fb.render_frame(_data);
|
fb.render_frame(_data);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -46,7 +46,11 @@ impl<'a> Writer<'a> {
|
|||||||
if line & (0x80 >> col) != 0 {
|
if line & (0x80 >> col) != 0 {
|
||||||
for i in 0..scale {
|
for i in 0..scale {
|
||||||
for j in 0..scale {
|
for j in 0..scale {
|
||||||
frame.write_pixel(pixel_x + i, pixel_y + j, Colour::White)?;
|
frame.write_pixel(
|
||||||
|
pixel_x + i,
|
||||||
|
pixel_y + j,
|
||||||
|
Colour::White,
|
||||||
|
)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,83 +0,0 @@
|
|||||||
pub use crate::arch::x86_64::drivers::{
|
|
||||||
ascii::{_print, _print_err, _print_log},
|
|
||||||
serial::_serial_write,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub mod stdin {
|
|
||||||
use crate::arch::x86_64::drivers::{
|
|
||||||
ascii::WRITER,
|
|
||||||
keyboard::{
|
|
||||||
get_keystroke_async, get_keystroke_optional, KeyStroke,
|
|
||||||
}
|
|
||||||
};
|
|
||||||
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.
|
|
||||||
///
|
|
||||||
/// This function is currently unimplemented.
|
|
||||||
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,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()
|
||||||
|
}
|
||||||
@@ -1,4 +1,7 @@
|
|||||||
pub mod application;
|
pub mod application;
|
||||||
pub mod ascii;
|
pub mod ascii;
|
||||||
|
pub mod elf;
|
||||||
pub mod io;
|
pub mod io;
|
||||||
pub mod maths;
|
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;
|
||||||
+20
-11
@@ -1,15 +1,14 @@
|
|||||||
use crate::serial_print;
|
|
||||||
use crate::arch::x86_64::drivers::keyboard::{KeyStroke, get_keystroke_async};
|
use crate::arch::x86_64::drivers::keyboard::{KeyStroke, get_keystroke_async};
|
||||||
use crate::resources::font::Font;
|
use crate::resources::font::Font;
|
||||||
use crate::std::application::frame::Frame;
|
use crate::serial_print;
|
||||||
use crate::std::application::render::RenderError;
|
use crate::serial_println;
|
||||||
use crate::std::application::window::Window;
|
use crate::std::application::{
|
||||||
use crate::std::application::{Application, Error};
|
Application, Error, frame::Frame, render::RenderError, window::Window,
|
||||||
|
};
|
||||||
use crate::std::ascii::Writer;
|
use crate::std::ascii::Writer;
|
||||||
use crate::std::maths::geometry::Vec2;
|
use crate::std::maths::geometry::Vec2;
|
||||||
use alloc::string::{String, ToString};
|
use alloc::string::{String, ToString};
|
||||||
use alloc::vec::Vec;
|
use alloc::vec::Vec;
|
||||||
use crate::serial_println;
|
|
||||||
|
|
||||||
pub struct Editor {
|
pub struct Editor {
|
||||||
cursor_line: usize,
|
cursor_line: usize,
|
||||||
@@ -42,7 +41,8 @@ impl<'a> Editor {
|
|||||||
|
|
||||||
fn render(&'a self) -> Result<Frame<'a>, RenderError> {
|
fn render(&'a self) -> Result<Frame<'a>, RenderError> {
|
||||||
let mut frame = Frame::new(&self.window);
|
let mut frame = Frame::new(&self.window);
|
||||||
let writer = Writer::new(Font::default());
|
let font = Font::default();
|
||||||
|
let writer = Writer::new(&font);
|
||||||
|
|
||||||
let (width, height) = writer.font_size().into();
|
let (width, height) = writer.font_size().into();
|
||||||
|
|
||||||
@@ -65,7 +65,10 @@ impl<'a> Editor {
|
|||||||
|
|
||||||
writer.render_glyph(
|
writer.render_glyph(
|
||||||
&mut frame,
|
&mut frame,
|
||||||
Vec2::new(col * width + Self::PADDING, line * height + Self::PADDING),
|
Vec2::new(
|
||||||
|
col * width + Self::PADDING,
|
||||||
|
line * height + Self::PADDING,
|
||||||
|
),
|
||||||
ch as u8,
|
ch as u8,
|
||||||
scale,
|
scale,
|
||||||
)?;
|
)?;
|
||||||
@@ -124,7 +127,8 @@ impl<'a> Editor {
|
|||||||
|
|
||||||
fn get_char_idx(&self) -> usize {
|
fn get_char_idx(&self) -> usize {
|
||||||
let frame = Frame::new(&self.window);
|
let frame = Frame::new(&self.window);
|
||||||
let writer = Writer::new(Font::default());
|
let font = Font::default();
|
||||||
|
let writer = Writer::new(&font);
|
||||||
let (width, _height) = writer.font_size().into();
|
let (width, _height) = writer.font_size().into();
|
||||||
|
|
||||||
let mut col = 0;
|
let mut col = 0;
|
||||||
@@ -157,7 +161,10 @@ impl<'a> Editor {
|
|||||||
|
|
||||||
impl Application for Editor {
|
impl Application for Editor {
|
||||||
type Output = ();
|
type Output = ();
|
||||||
async fn run(&mut self, _args: Vec<alloc::string::String>) -> Result<Self::Output, Error> {
|
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_dimensions(Vec2::new(1280, 800));
|
||||||
self.window.set_position(Vec2::new(0, 0));
|
self.window.set_position(Vec2::new(0, 0));
|
||||||
self.window.open();
|
self.window.open();
|
||||||
@@ -167,7 +174,9 @@ impl Application for Editor {
|
|||||||
loop {
|
loop {
|
||||||
if let Err(_err) = self.render().and_then(|frame| frame.render()) {
|
if let Err(_err) = self.render().and_then(|frame| frame.render()) {
|
||||||
// TODO: Handle error
|
// TODO: Handle error
|
||||||
return Err(Error::ApplicationFailed("Rendering failed".to_string()));
|
return Err(Error::ApplicationFailed(
|
||||||
|
"Rendering failed".to_string(),
|
||||||
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let keystroke = get_keystroke_async().await;
|
let keystroke = get_keystroke_async().await;
|
||||||
|
|||||||
+39
-50
@@ -1,3 +1,4 @@
|
|||||||
|
#![allow(dead_code)]
|
||||||
#![feature(proc_macro_span)]
|
#![feature(proc_macro_span)]
|
||||||
#![warn(
|
#![warn(
|
||||||
clippy::correctness,
|
clippy::correctness,
|
||||||
@@ -10,9 +11,6 @@
|
|||||||
rustdoc::missing_panics_doc
|
rustdoc::missing_panics_doc
|
||||||
)]
|
)]
|
||||||
|
|
||||||
use std::fs::File;
|
|
||||||
use std::io::{Read, Seek, SeekFrom};
|
|
||||||
|
|
||||||
use proc_macro::{Span, TokenStream};
|
use proc_macro::{Span, TokenStream};
|
||||||
use quote::quote;
|
use quote::quote;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
@@ -36,17 +34,18 @@ pub fn include_font(item: TokenStream) -> TokenStream {
|
|||||||
let source_filepath: PathBuf = source_file.path();
|
let source_filepath: PathBuf = source_file.path();
|
||||||
let file_path = format!(
|
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()
|
filename.value()
|
||||||
);
|
);
|
||||||
|
|
||||||
let font_bytes = match load_file(file_path) {
|
let font_bytes = match std::fs::read(file_path) {
|
||||||
Ok(bytes) => bytes,
|
Ok(bytes) => bytes,
|
||||||
Err(why) => panic!("{}", why),
|
Err(why) => panic!("{}", why),
|
||||||
};
|
};
|
||||||
|
|
||||||
let font_data = match Font::new(font_bytes) {
|
let font_data = match FontBuilder::load(font_bytes) {
|
||||||
Ok(font) => font.0,
|
Ok(font) => font.data,
|
||||||
Err(why) => panic!("{}", why),
|
Err(why) => panic!("{}", why),
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -66,40 +65,44 @@ struct FontData {
|
|||||||
width: u8,
|
width: u8,
|
||||||
height: u8,
|
height: u8,
|
||||||
length: u16,
|
length: u16,
|
||||||
data: Vec<Glyph>,
|
pub data: [[u8; 16]; 512],
|
||||||
unicode_table: [[u8; 2]; 512],
|
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Glyph {
|
|
||||||
bytes: Vec<u8>,
|
|
||||||
}
|
|
||||||
|
|
||||||
enum FontBuilder {
|
enum FontBuilder {
|
||||||
Psf1,
|
Psf1(FontData),
|
||||||
Psf2,
|
Psf2(FontData),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl FontBuilder {
|
impl FontBuilder {
|
||||||
const PSF1_MAGIC: u16 = 0x3604;
|
const PSF1_MAGIC: u16 = 0x3604;
|
||||||
const PSF2_MAGIC: u32 = 0x72b54a86;
|
const PSF2_MAGIC: u32 = 0x72b54a86;
|
||||||
|
|
||||||
pub fn load() -> Option<Self> {
|
fn revision(data: &[u8]) -> u8 {
|
||||||
None
|
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
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
impl Font {
|
pub fn load(data: Vec<u8>) -> Result<FontData, &'static str> {
|
||||||
const MAGIC: u16 = 0x3604;
|
match Self::revision(&data[0..4]) {
|
||||||
|
1 => Self::parse_psf1(&data),
|
||||||
|
2 => Self::parse_psf2(&data),
|
||||||
|
_ => panic!("invalid font revision result"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn new(data: [u8; (32 + 2) * 512 + 4]) -> Result<Self, &'static str> {
|
fn parse_psf1(data: &[u8]) -> Result<FontData, &'static str> {
|
||||||
let magic: u16 = (data[0] as u16) << 8 | data[1] as u16;
|
|
||||||
let mode = data[2];
|
let mode = data[2];
|
||||||
let size = data[3];
|
let size = data[3];
|
||||||
|
|
||||||
if magic != Self::MAGIC {
|
|
||||||
return Err("Magic value is invalid!");
|
|
||||||
}
|
|
||||||
|
|
||||||
let has_512_glyphs = (mode & 0x01) != 0;
|
let has_512_glyphs = (mode & 0x01) != 0;
|
||||||
let mut glyphs = [[0; 16]; 512];
|
let mut glyphs = [[0; 16]; 512];
|
||||||
let glyph_count = if has_512_glyphs { 512 } else { 256 };
|
let glyph_count = if has_512_glyphs { 512 } else { 256 };
|
||||||
@@ -112,29 +115,15 @@ impl Font {
|
|||||||
glyphs[i] = buff;
|
glyphs[i] = buff;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(Self(glyphs))
|
Ok(FontData {
|
||||||
}
|
width: 8,
|
||||||
}
|
height: size,
|
||||||
|
length: glyph_count,
|
||||||
type FileContents = [u8; (32 + 2) * 512 + 4];
|
data: glyphs,
|
||||||
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(buf)
|
const fn parse_psf2(_data: &[u8]) -> Result<FontData, &'static str> {
|
||||||
|
Err("PSF2 support is not implemented yet!")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
wrap_comments = true
|
||||||
|
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
|
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"
|
cd "$project_root"
|
||||||
qemu-system-x86_64 -M q35 \
|
qemu-system-x86_64 -M q35 \
|
||||||
-cdrom "$build_dir/image.iso" \
|
-cdrom "$build_dir/image.iso" \
|
||||||
|
|||||||
Reference in New Issue
Block a user