Compare commits

...

4 Commits
main ... main

22 changed files with 517 additions and 323 deletions

View File

@ -40,7 +40,7 @@ typedef void (*interrupt_entry)();
*/ */
#define interrupt_entry_gen(interrupt) \ #define interrupt_entry_gen(interrupt) \
extern void interrupt_entry_##interrupt() extern void interrupt_entry_##interrupt()
#define interrupt_entry_sym(interrupt) \ #define interrupt_entry(interrupt) \
interrupt_entry_##interrupt interrupt_entry_##interrupt
/** /**
@ -78,12 +78,14 @@ typedef void (*interrupt_request)(u64 rip, u64 rsp, u64 errcode);
#define NMI #define NMI
#define BP #define BP
#define OF #define OF
#define BOUND
interrupt_entry_gen(UNSUPPORTED); interrupt_entry_gen(UNSUPPORTED);
interrupt_entry_gen(DE); // irq0 interrupt_entry_gen(DE); // irq0
interrupt_entry_gen(NMI); // irq2 interrupt_entry_gen(NMI); // irq2
interrupt_entry_gen(BP); // irq3 interrupt_entry_gen(BP); // irq3
interrupt_entry_gen(OF); // ira4 interrupt_entry_gen(OF); // irq4
interrupt_entry_gen(BOUND); // irq5
#endif #endif

View File

@ -3,7 +3,6 @@
#include <types.h> #include <types.h>
// 使用UNIX时间戳
/** /**
* @name system_time_get * @name system_time_get
* *
@ -17,8 +16,6 @@
*/ */
usize system_time_get(); usize system_time_get();
// 如果硬件支持更高的计时精度,
// 此函数提供从系统unix时间开始到现在的纳秒为单位的时间
/** /**
* @name system_time_ns_get * @name system_time_ns_get
* *

View File

@ -152,7 +152,9 @@ bool tty_is_enabled(tty *ttyx);
bool tty_enable(tty *ttyx); bool tty_enable(tty *ttyx);
void tty_disable(tty *ttyx); void tty_disable(tty *ttyx);
#define TTY_FONT_SCALE 2 #ifndef TTY_FONT_SCALE
#define TTY_FONT_SCALE 1
#endif
typedef struct __tty_font_t typedef struct __tty_font_t
{ {

View File

@ -27,6 +27,9 @@ DEFINES = ARCH="${ARCH}" ASM="${ASM}" ASMFLAGS="${ASMFLAGS}" SOURCE="${SOURCE}"
ifdef release ifdef release
DEFINES := ${DEFINES} release=1 DEFINES := ${DEFINES} release=1
endif endif
ifdef ttyfont_scale
DEFINES := ${DEFINES} ttyfont_scale=${ttyfont_scale}
endif
################################ ################################
# rust语言环境变量 # rust语言环境变量

View File

@ -12,6 +12,9 @@ CCFLAGS = -m64 -mcmodel=large -I ../../include \
ifdef release ifdef release
CCFLAGS := ${CCFLAGS} -O2 CCFLAGS := ${CCFLAGS} -O2
endif endif
ifdef ttyfont_scale
CCFLAGS := ${CCFLAGS} -DTTY_FONT_SCALE=${ttyfont_scale}
endif
C_SRCS = main.c tty.c font.c memm.c memm_${ARCH}.c raw.c time.c syscall_${ARCH}.c interrupt_${ARCH}.c C_SRCS = main.c tty.c font.c memm.c memm_${ARCH}.c raw.c time.c syscall_${ARCH}.c interrupt_${ARCH}.c
C_OBJS = ${C_SRCS:.c=.c.o} C_OBJS = ${C_SRCS:.c=.c.o}

View File

@ -1,4 +1,13 @@
use crate::{kernel::tty::tty::Tty, message}; use crate::{
kernel::{
klog::LoggerLevel,
memm::utils::AddressUtils,
tty::tty::{Color, FmtMeta, Tty},
},
log, message,
};
use super::proc::RegisterTexture;
extern "C" { extern "C" {
pub fn interrupt_open(); pub fn interrupt_open();
@ -9,13 +18,13 @@ extern "C" {
} }
#[no_mangle] #[no_mangle]
unsafe extern "C" fn interrupt_req_UNSUPPORTED(rip: u64, rsp: u64, errcode: u64) -> ! { unsafe extern "C" fn interrupt_req_UNSUPPORTED(rip: u64, rsp: u64, _errcode: u64) -> ! {
interrupt_rust_enter(); interrupt_rust_enter();
let tty = Tty::from_id(0).unwrap(); let tty = Tty::from_id(0).unwrap();
tty.enable(); tty.enable();
tty.print(message!( tty.print(log!(
"{Panic}: Kernel hit an {Unsupported} interrupt on rip=0x{} and rsp=0x{}.\n", LoggerLevel::Fatal,
FmtMeta::Color(Color::RED), "Kernel hit an {Unsupported} interrupt on rip=0x{} and rsp=0x{}.\n",
FmtMeta::Color(Color::YELLOW), FmtMeta::Color(Color::YELLOW),
FmtMeta::Pointer(rip as usize), FmtMeta::Pointer(rip as usize),
FmtMeta::Pointer(rsp as usize) FmtMeta::Pointer(rsp as usize)
@ -24,25 +33,156 @@ unsafe extern "C" fn interrupt_req_UNSUPPORTED(rip: u64, rsp: u64, errcode: u64)
} }
#[no_mangle] #[no_mangle]
unsafe extern "C" fn interrupt_req_DE(rip: u64, rsp: u64, errcode: u64) { unsafe extern "C" fn interrupt_req_DE(rip: u64, rsp: u64, _errcode: u64) {
interrupt_rust_enter(); interrupt_rust_enter();
let tty = Tty::from_id(0).unwrap(); if rip.is_kernel_space() {
tty.enable(); let tty = Tty::from_id(0).unwrap();
tty.print(message!( tty.enable();
"{Warning}: Kernel hit {Divid Error} on rip=0x{} and rsp=0x{}.\n", tty.print(log!(
FmtMeta::Color(Color::PURPLE), LoggerLevel::Fatal,
FmtMeta::Color(Color::YELLOW), "Kernel hit {Divid Error} on rip=0x{} and rsp=0x{}.\n",
FmtMeta::Pointer(rip as usize), FmtMeta::Color(Color::YELLOW),
FmtMeta::Pointer(rsp as usize) FmtMeta::Pointer(rip as usize),
)); FmtMeta::Pointer(rsp as usize)
interrupt_rust_leave(); ));
loop {}
} else if rip.is_user_space() {
// TODO 处理后返回
interrupt_rust_leave();
}
}
// #[no_mangle]
// unsafe extern "C" fn interrupt_req_NMI(rip: u64, rsp: u64, errcode: u64) {}
#[no_mangle]
unsafe extern "C" fn interrupt_req_BP(rip: u64, _rsp: u64, errcode: u64) {
interrupt_rust_enter();
if rip.is_kernel_space() {
let register_texture = errcode as *const RegisterTexture;
let register_texture = &*register_texture;
let tty = Tty::from_id(0).unwrap();
tty.enable();
tty.print(log!(
LoggerLevel::Debug,
"Kernel hit breakpoint {0x{}}.\n",
FmtMeta::Pointer(rip as usize),
FmtMeta::Color(Color::GREEN)
));
tty.print(message!(
"\trax\t{}\n",
FmtMeta::Pointer(register_texture.rax as usize)
));
tty.print(message!(
"\trbx\t{}\n",
FmtMeta::Pointer(register_texture.rbx as usize)
));
tty.print(message!(
"\trcx\t{}\n",
FmtMeta::Pointer(register_texture.rcx as usize)
));
tty.print(message!(
"\trdx\t{}\n",
FmtMeta::Pointer(register_texture.rdx as usize)
));
tty.print(message!(
"\trsi\t{}\n",
FmtMeta::Pointer(register_texture.rsi as usize)
));
tty.print(message!(
"\trdi\t{}\n",
FmtMeta::Pointer(register_texture.rdi as usize)
));
tty.print(message!(
"\trbp\t{}\n",
FmtMeta::Pointer(register_texture.rbp as usize)
));
tty.print(message!(
"\trsp\t{}\n",
FmtMeta::Pointer(register_texture.rsp as usize)
));
tty.print(message!(
"\tr8\t{}\n",
FmtMeta::Pointer(register_texture.r8 as usize)
));
tty.print(message!(
"\tr9\t{}\n",
FmtMeta::Pointer(register_texture.r9 as usize)
));
tty.print(message!(
"\tr10\t{}\n",
FmtMeta::Pointer(register_texture.r10 as usize)
));
tty.print(message!(
"\tr11\t{}\n",
FmtMeta::Pointer(register_texture.r11 as usize)
));
tty.print(message!(
"\tr12\t{}\n",
FmtMeta::Pointer(register_texture.r12 as usize)
));
tty.print(message!(
"\tr13\t{}\n",
FmtMeta::Pointer(register_texture.r13 as usize)
));
tty.print(message!(
"\tr14\t{}\n",
FmtMeta::Pointer(register_texture.r14 as usize)
));
tty.print(message!(
"\tr15\t{}\n",
FmtMeta::Pointer(register_texture.r15 as usize)
));
tty.print(message!(
"\trip\t{}\n",
FmtMeta::Pointer(register_texture.rip as usize)
));
tty.print(message!(
"\trflags\t{}\n",
FmtMeta::Pointer(register_texture.rflags as usize)
));
loop {}
} else if rip.is_user_space() {
// TODO 处理后返回
interrupt_rust_leave();
}
} }
#[no_mangle] #[no_mangle]
unsafe extern "C" fn interrupt_req_NMI(rip: u64, rsp: u64, errcode: u64) {} unsafe extern "C" fn interrupt_req_OF(rip: u64, rsp: u64, _errcode: u64) {
interrupt_rust_enter();
if rip.is_kernel_space() {
let tty = Tty::from_id(0).unwrap();
tty.enable();
tty.print(log!(
LoggerLevel::Fatal,
"Kernel hit {Overflow Error} on rip=0x{} and rsp=0x{}.\n",
FmtMeta::Color(Color::YELLOW),
FmtMeta::Pointer(rip as usize),
FmtMeta::Pointer(rsp as usize)
));
loop {}
} else if rip.is_user_space() {
// TODO 处理后返回
interrupt_rust_leave();
}
}
#[no_mangle] #[no_mangle]
unsafe extern "C" fn interrupt_req_BP(rip: u64, rsp: u64, errcode: u64) {} unsafe extern "C" fn interrupt_req_BOUND(rip: u64, rsp: u64, _errcode: u64) {
interrupt_rust_enter();
#[no_mangle] if rip.is_kernel_space() {
unsafe extern "C" fn interrupt_req_OF(rip: u64, rsp: u64, errcode: u64) {} let tty = Tty::from_id(0).unwrap();
tty.enable();
tty.print(log!(
LoggerLevel::Fatal,
"Kernel hit {Bound Error} on rip=0x{} and rsp=0x{}.\n",
FmtMeta::Color(Color::YELLOW),
FmtMeta::Pointer(rip as usize),
FmtMeta::Pointer(rsp as usize)
));
loop {}
} else if rsp.is_user_space() {
interrupt_rust_leave();
}
}

View File

@ -107,3 +107,15 @@ interrupt_entry_OF:
interrupt_entry_leave interrupt_entry_leave
iretq iretq
global interrupt_entry_BOUND
extern interrupt_req_BOUND
interrupt_entry_BOUND:
interrupt_entry_enter
mov rdi, [rsp + 128]
mov rsi, [rsp + 152]
call interrupt_req_BOUND
interrupt_entry_leave
iretq

View File

@ -6,22 +6,25 @@
void interrupt_init() void interrupt_init()
{ {
gate_descriptor_t gate; gate_descriptor_t gate;
trap_gate_generate(gate, interrupt_entry_sym(UNSUPPORTED));
// 用UNSUPPORTED中断处理程序填充所有中断向量
trap_gate_generate(gate, interrupt_entry(UNSUPPORTED));
for (usize i = 4; i < 256; i++) for (usize i = 4; i < 256; i++)
{ {
interrupt_register_gate(gate, i); interrupt_register_gate(gate, i);
} }
trap_gate_generate(gate, interrupt_entry_sym(DE)); trap_gate_generate(gate, interrupt_entry(DE));
interrupt_register_gate(gate, 0); interrupt_register_gate(gate, 0);
trap_gate_generate(gate, interrupt_entry_sym(UNSUPPORTED)); trap_gate_generate(gate, interrupt_entry(UNSUPPORTED)); // Debug Exception (#DB) nosupport
interrupt_register_gate(gate, 1); interrupt_register_gate(gate, 1);
trap_gate_generate(gate, interrupt_entry_sym(NMI)); trap_gate_generate(gate, interrupt_entry(NMI));
interrupt_register_gate(gate, 2); interrupt_register_gate(gate, 2);
trap_gate_generate(gate, interrupt_entry_sym(BP)); trap_gate_generate(gate, interrupt_entry(BP));
interrupt_register_gate(gate, 3); interrupt_register_gate(gate, 3);
trap_gate_generate(gate, interrupt_entry_sym(OF)); trap_gate_generate(gate, interrupt_entry(OF));
interrupt_register_gate(gate, 4); interrupt_register_gate(gate, 4);
trap_gate_generate(gate, interrupt_entry(BOUND));
interrupt_open(); interrupt_open();
} }

View File

@ -1,32 +1,30 @@
#[repr(C)] #[repr(C)]
#[derive(Debug)]
pub struct RegisterTexture { pub struct RegisterTexture {
es: u16, pub es: u16,
ds: u16, pub ds: u16,
reserved: u32, pub reserved: u32,
r15: u64, pub r15: u64,
r14: u64, pub r14: u64,
r13: u64, pub r13: u64,
r12: u64, pub r12: u64,
r11: u64, pub r11: u64,
r10: u64, pub r10: u64,
r9: u64, pub r9: u64,
r8: u64, pub r8: u64,
rdi: u64, pub rdi: u64,
rsi: u64, pub rsi: u64,
rdx: u64, pub rdx: u64,
rbx: u64, pub rbx: u64,
rcx: u64, pub rcx: u64,
rax: u64, pub rax: u64,
rbp: u64, pub rbp: u64,
rip: u64, pub rip: u64,
cs: u64, pub cs: u64,
rflags: u64, pub rflags: u64,
rsp: u64, pub rsp: u64,
ss: u64, pub ss: u64,
} }
#[derive(Debug)]
pub struct ProcessTexture { pub struct ProcessTexture {
register: RegisterTexture, register: RegisterTexture,
} }

View File

@ -1,7 +1,5 @@
use core::{cmp::Ordering, ops::Sub, time::Duration}; use core::{cmp::Ordering, ops::Sub, time::Duration};
use alloc::{format, string::ToString};
extern "C" { extern "C" {
fn system_time_get() -> usize; fn system_time_get() -> usize;
fn system_time_ns_get() -> usize; fn system_time_ns_get() -> usize;
@ -10,99 +8,14 @@ extern "C" {
#[derive(Debug)] #[derive(Debug)]
pub struct SystemTimeError(Duration); pub struct SystemTimeError(Duration);
#[derive(Clone, Copy, Hash)] #[derive(Clone, Copy, Hash, Default)]
#[derive(Default)]
pub struct SystemTime { pub struct SystemTime {
/// ms
unix_time: usize, unix_time: usize,
/// ns
ns_time: usize, ns_time: usize,
} }
impl ToString for SystemTime {
fn to_string(&self) -> alloc::string::String {
let second_dur = 1000usize;
let minute_dur = second_dur * 60;
let hour_dur = minute_dur * 60;
let day_dur = hour_dur * 24;
let year_dur = day_dur * 365;
let four_year_dur = day_dur * (365 * 4 + 1);
let year = 1970
+ self.unix_time / four_year_dur * 4
+ if self.unix_time % four_year_dur < day_dur * 59 {
0
} else {
(self.unix_time % four_year_dur - day_dur) / year_dur
};
let rest = self.unix_time % four_year_dur;
let mut leap = false;
let rest = if rest < day_dur * 59 {
rest
} else {
if rest < 60 {
leap = true;
}
rest - day_dur
};
let month = rest % year_dur;
let mut day = 0;
let month = if month < 31 * day_dur {
day = month;
1
} else if month < (31 + 28) * day_dur {
day = month - 31 * day_dur;
2
} else if month < (31 + 28 + 31) * day_dur {
day = month - (31 + 28) * day_dur;
3
} else if month < (31 + 28 + 31 + 30) * day_dur {
day = month - (31 + 28 + 31) * day_dur;
4
} else if month < (31 + 28 + 31 + 30 + 31) * day_dur {
day = month - (31 + 28 + 31 + 30) * day_dur;
5
} else if month < (31 + 28 + 31 + 30 + 31 + 30) * day_dur {
day = month - (31 + 28 + 31 + 30 + 31) * day_dur;
6
} else if month < (31 + 28 + 31 + 30 + 31 + 30 + 31) * day_dur {
day = month - (31 + 28 + 31 + 30 + 31 + 30) * day_dur;
7
} else if month < (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31) * day_dur {
day = month - (31 + 28 + 31 + 30 + 31 + 30 + 31) * day_dur;
8
} else if month < (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30) * day_dur {
day = month - (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31) * day_dur;
9
} else if month < (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31) * day_dur {
day = month - (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30) * day_dur;
10
} else if month < (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30) * day_dur {
day = month - (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31) * day_dur;
11
} else if month < (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31) * day_dur {
day = month - (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30) * day_dur;
12
} else {
0
};
let mut hour = day % day_dur;
day /= day_dur;
day += 1;
if leap {
day += 1;
}
let mut minute = hour % hour_dur;
hour /= hour_dur;
let mut second = minute % minute_dur;
minute /= minute_dur;
let milisec = second % second_dur;
second /= second_dur;
format!(
"[ {}-{}-{} {}:{}:{}.{} ] ",
year, month, day, hour, minute, second, milisec
)
}
}
impl Eq for SystemTime {} impl Eq for SystemTime {}
impl PartialEq for SystemTime { impl PartialEq for SystemTime {
fn eq(&self, other: &Self) -> bool { fn eq(&self, other: &Self) -> bool {
@ -165,3 +78,80 @@ impl SystemTime {
SystemTime::now() - *self SystemTime::now() - *self
} }
} }
pub struct SystemDate {
pub year: u16,
pub month: u8,
pub day: u8,
pub hour: u8,
pub minute: u8,
pub second: u8,
pub milisecond: u16,
pub nanosecond: u32,
}
impl From<SystemTime> for SystemDate {
fn from(
SystemTime {
mut unix_time,
ns_time,
}: SystemTime,
) -> Self {
let milisecond = (unix_time % 1000) as u16;
unix_time /= 1000;
let second = (unix_time % 60) as u8;
unix_time /= 60;
let minute = (unix_time % 60) as u8;
unix_time /= 60;
let hour = (unix_time % 24) as u8;
unix_time /= 24;
let (year, leap) = {
let mut year = 1970;
let get_days_of_this_year = |y| {
if (y % 4 == 0 && y % 100 != 0) || y % 400 == 0 {
366
} else {
365
}
};
while unix_time > get_days_of_this_year(year) {
unix_time -= get_days_of_this_year(year);
year += 1;
}
(year, (year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
};
let month = {
let mut month = 0;
let dom = [
// days of months
31,
if leap { 29 } else { 28 },
31,
30,
31,
30,
31,
31,
30,
31,
30,
31,
];
while unix_time > dom[month] {
unix_time -= dom[month];
month += 1;
}
month as u8 + 1
};
Self {
year,
month,
day: unix_time as u8 + 1,
hour,
minute,
second,
milisecond,
nanosecond: ns_time as u32,
}
}
}

View File

@ -1,9 +1,4 @@
use crate::libk::alloc::vec::Vec; use crate::kernel::tty::tty::{Color, MessageBuilder};
use super::{
clock::time::SystemTime,
tty::tty::{Color, Message, MessageBuilder},
};
#[derive(PartialEq)] #[derive(PartialEq)]
pub enum LoggerLevel { pub enum LoggerLevel {
@ -15,93 +10,58 @@ pub enum LoggerLevel {
Trace, Trace,
} }
pub struct KernelLogger { impl From<LoggerLevel> for MessageBuilder {
fatal_queue: Vec<(SystemTime, Message)>, fn from(value: LoggerLevel) -> Self {
error_queue: Vec<(SystemTime, Message)>, match value {
warning_queue: Vec<(SystemTime, Message)>, LoggerLevel::Fatal => MessageBuilder::new()
info_queue: Vec<(SystemTime, Message)>, .message("Fatal")
debug_queue: Vec<(SystemTime, Message)>, .foreground_color(Color::RED),
trace_queue: Vec<(SystemTime, Message)>, LoggerLevel::Error => MessageBuilder::new()
} .message("Error")
.foreground_color(Color::ORANGE),
impl KernelLogger { LoggerLevel::Warning => MessageBuilder::new()
pub fn new() -> Self { .message("Warning")
Self { .foreground_color(Color::PURPLE),
fatal_queue: Vec::new(), LoggerLevel::Info => MessageBuilder::new()
error_queue: Vec::new(), .message("Info")
warning_queue: Vec::new(), .foreground_color(Color::GREEN),
info_queue: Vec::new(), LoggerLevel::Debug => MessageBuilder::new()
debug_queue: Vec::new(), .message("Debug")
trace_queue: Vec::new(), .foreground_color(Color::BLUE),
LoggerLevel::Trace => MessageBuilder::new()
.message("Trace")
.foreground_color(Color::YELLOW),
} }
} }
pub fn fatal(&mut self, msg: Message) {
let msg = MessageBuilder::new()
.message("Fatal: ")
.foreground_color(Color::RED)
.append(MessageBuilder::from_message(msg))
.build();
self.fatal_queue.push((SystemTime::now(), msg));
}
pub fn error(&mut self, msg: Message) {
let msg = MessageBuilder::new()
.message("Error: ")
.foreground_color(Color::ORANGE)
.append(MessageBuilder::from_message(msg))
.build();
self.error_queue.push((SystemTime::now(), msg));
}
pub fn warning(&mut self, msg: Message) {
let msg = MessageBuilder::new()
.message("Warning: ")
.foreground_color(Color::PURPLE)
.append(MessageBuilder::from_message(msg))
.build();
self.warning_queue.push((SystemTime::now(), msg));
}
pub fn info(&mut self, msg: Message) {
let msg = MessageBuilder::new()
.message("Info: ")
.foreground_color(Color::GREEN)
.append(MessageBuilder::from_message(msg))
.build();
self.info_queue.push((SystemTime::now(), msg));
}
pub fn debug(&mut self, msg: Message) {
let msg = MessageBuilder::new()
.message("Debug: ")
.foreground_color(Color::WHITE)
.append(MessageBuilder::from_message(msg))
.build();
self.debug_queue.push((SystemTime::now(), msg));
}
pub fn trace(&mut self, msg: Message) {
let msg = MessageBuilder::new()
.message("Trace: ")
.foreground_color(Color::WHITE)
.append(MessageBuilder::from_message(msg))
.build();
self.trace_queue.push((SystemTime::now(), msg));
}
pub fn iter(&self, _level: LoggerLevel) -> LogIterator {
todo!()
}
} }
pub struct LogIterator { #[macro_export]
} macro_rules! log {
( $level : expr, $fmtter : expr ) => {{
impl Iterator for LogIterator { use crate::kernel::tty::tty::(Color, MessageBuilder, FmtMeta);
type Item = Message; MessageBuilder::from_message(
message!("{[{}]} ",
fn next(&mut self) -> Option<Self::Item> { FmtMeta::SystemTime,
todo!() FmtMeta::Color(Color::GRAY)
} ))
.append(MessageBuilder::from($level))
.append(
MessageBuilder::new()
.message(": ")
.message($fmtter)
)
.build()
}};
( $level : expr, $fmtter : expr, $( $e : expr ),* ) => {{
use crate::kernel::tty::tty::{Color, MessageBuilder, FmtMeta};
MessageBuilder::from_message(
message!("{[{}]} ",
FmtMeta::SystemTime,
FmtMeta::Color(Color::GRAY)
))
.append(MessageBuilder::from($level))
.append(MessageBuilder::new().message(": "))
.append(MessageBuilder::from_message(message!($fmtter, $( $e ),*)))
.build()
}};
} }

View File

@ -48,11 +48,11 @@ void kmain(void *mb2_bootinfo)
// 初始化中断管理 // 初始化中断管理
interrupt_init(); interrupt_init();
int i = 1 / 0;
// 初始化系统调用 // 初始化系统调用
syscall_init(); syscall_init();
asm("int3");
// 为rust准备正确对齐的栈 // 为rust准备正确对齐的栈
prepare_stack(); prepare_stack();

View File

@ -81,12 +81,4 @@ void raw_allocator_free(raw_allocator_t *allocator, void *mem)
cell = raw_allocator_next_cell(cell); cell = raw_allocator_next_cell(cell);
} }
allocator->rest_memory += cell->capacity + sizeof(raw_allocator_cell); allocator->rest_memory += cell->capacity + sizeof(raw_allocator_cell);
allocator->free_count++;
if ( // 可用内存不超过当前allocator的 5% 或调用free次数很多时
allocator->size / allocator->rest_memory > 20 ||
allocator->free_count > RAW_ALLOCATOR_FREE_MAX)
{
raw_allocator_cellmerge(allocator);
allocator->free_count = 0;
}
} }

View File

@ -1 +1,2 @@
pub mod memm; pub mod memm;
pub mod utils;

24
src/kernel/memm/utils.rs Normal file
View File

@ -0,0 +1,24 @@
mod x86_64 {
pub trait AddressUtils {
fn is_cannonical(self) -> bool;
fn is_user_space(self) -> bool;
fn is_kernel_space(self) -> bool;
}
impl AddressUtils for u64 {
fn is_cannonical(self) -> bool {
self < 0x0000_8000_0000_0000 || self > 0xffff_7fff_ffff_ffff
}
fn is_user_space(self) -> bool {
self > 0xffff_7fff_ffff_ffff
}
fn is_kernel_space(self) -> bool {
self.is_cannonical() && !self.is_user_space()
}
}
}
#[cfg(target_arch = "x86_64")]
pub use x86_64::*;

View File

@ -12,17 +12,12 @@ macro_rules! message {
use crate::{ use crate::{
kernel::tty::tty::{ kernel::tty::tty::{
MessageBuilder, MessageBuilder,
FmtMeta,
Color,
format_message format_message
}, },
libk::alloc::vec::Vec, libk::alloc::{string::ToString, vec::Vec},
}; };
let mut formatter = $fmtter.chars().collect::<Vec<char>>(); let mut formatter = Vec::from_iter($fmtter.to_string().chars());
let builder = MessageBuilder::new(); let builder = MessageBuilder::new();
$( builder$(.append(format_message(&mut formatter, $e)))*.build()
let builder = builder.append(format_message(&mut formatter, $e));
)*
builder.build()
}}; }};
} }

View File

@ -1,9 +1,12 @@
use core::ptr::null_mut; use core::ptr::null_mut;
use crate::libk::alloc::{ use crate::{
boxed::Box, kernel::clock::time::{SystemDate, SystemTime},
string::{String, ToString}, libk::alloc::{
vec::Vec, boxed::Box,
string::{String, ToString},
vec::Vec,
},
}; };
extern "C" { extern "C" {
@ -119,23 +122,18 @@ impl Tty {
pub fn print(&self, msg: Message) { pub fn print(&self, msg: Message) {
for MessageSection { for MessageSection {
mut msg, msg,
fgcolor, fgcolor,
bgcolor, bgcolor,
} in msg.0.into_iter() } in msg.0.into_iter()
{ {
unsafe { unsafe {
let string = msg.as_bytes_mut() as *mut [u8] as *mut u8;
let string = string.offset(msg.len() as isize);
let swp = *string;
*string = 0;
tty_text_print( tty_text_print(
self.tty_pointer, self.tty_pointer,
msg.as_bytes_mut() as *mut [u8] as *mut u8, msg.to_cstr().get_pointer(),
u32::from(fgcolor), u32::from(fgcolor),
u32::from(bgcolor), u32::from(bgcolor),
); );
*string = swp;
}; };
} }
} }
@ -308,11 +306,13 @@ impl MessageBuilder {
} }
pub enum FmtMeta { pub enum FmtMeta {
Step,
Color(Color), Color(Color),
String(String), String(String),
ToStringable(Box<dyn ToString>), ToStringable(Box<dyn ToString>),
Hex(u8), Hex(u8),
Pointer(usize), Pointer(usize),
SystemTime,
} }
pub fn format_message(fmt: &mut Vec<char>, meta: FmtMeta) -> MessageBuilder { pub fn format_message(fmt: &mut Vec<char>, meta: FmtMeta) -> MessageBuilder {
@ -337,6 +337,7 @@ pub fn format_message(fmt: &mut Vec<char>, meta: FmtMeta) -> MessageBuilder {
}; };
if fmt_start == None || fmt_end == None { if fmt_start == None || fmt_end == None {
msgbuilder.message_mut(&String::from_iter(fmt.iter())); msgbuilder.message_mut(&String::from_iter(fmt.iter()));
msgbuilder
} else { } else {
let fmt_start = fmt_start.unwrap(); let fmt_start = fmt_start.unwrap();
let fmt_end = fmt_end.unwrap(); let fmt_end = fmt_end.unwrap();
@ -347,6 +348,7 @@ pub fn format_message(fmt: &mut Vec<char>, meta: FmtMeta) -> MessageBuilder {
formatter.remove(formatter.len() - 1); formatter.remove(formatter.len() - 1);
formatter.remove(0); formatter.remove(0);
match meta { match meta {
FmtMeta::Step => {}
FmtMeta::Color(color) => { FmtMeta::Color(color) => {
let first = fmt.split_at(fmt_start).0; let first = fmt.split_at(fmt_start).0;
msgbuilder.message_mut(&String::from_iter(first.iter())); msgbuilder.message_mut(&String::from_iter(first.iter()));
@ -376,12 +378,43 @@ pub fn format_message(fmt: &mut Vec<char>, meta: FmtMeta) -> MessageBuilder {
p >>= 4; p >>= 4;
} }
} }
FmtMeta::SystemTime => {
let SystemDate {
year,
month,
day,
hour,
minute,
second,
milisecond,
..
} = SystemDate::from(SystemTime::now());
let put_n_number = |fmt: &mut Vec<char>, mut data, n| {
for _ in 0..n {
fmt.insert(fmt_start, ((data % 10) as u8 + b'0') as char);
data /= 10;
}
};
put_n_number(fmt, milisecond / 10, 2);
fmt.insert(fmt_start, '.');
put_n_number(fmt, second as u16, 2);
fmt.insert(fmt_start, ':');
put_n_number(fmt, minute as u16, 2);
fmt.insert(fmt_start, ':');
put_n_number(fmt, hour as u16, 2);
fmt.insert(fmt_start, ' ');
put_n_number(fmt, day as u16, 2);
fmt.insert(fmt_start, '-');
put_n_number(fmt, month as u16, 2);
fmt.insert(fmt_start, '-');
put_n_number(fmt, year, 4);
}
} }
let mut rests = Vec::new();
while !fmt.is_empty() && fmt[0] != '{' {
rests.push(fmt.remove(0));
}
msgbuilder.message_mut(&String::from_iter(rests.iter()));
msgbuilder
} }
let mut rests = Vec::new();
while !fmt.is_empty() && fmt[0] != '{' {
rests.push(fmt.remove(0));
}
msgbuilder.message_mut(&String::from_iter(rests.iter()));
msgbuilder
} }

View File

@ -1,6 +1,7 @@
#![no_std] #![no_std]
#![feature(strict_provenance)] #![feature(strict_provenance)]
#![feature(layout_for_ptr)] #![feature(layout_for_ptr)]
#![feature(alloc_layout_extra)]
extern crate alloc; extern crate alloc;
@ -8,6 +9,8 @@ use core::panic::PanicInfo;
use kernel::tty::tty::Tty; use kernel::tty::tty::Tty;
use crate::kernel::tty::tty::{Color, FmtMeta};
pub mod kernel; pub mod kernel;
pub mod libk; pub mod libk;

View File

@ -24,18 +24,21 @@ impl String {
self.data.iter() self.data.iter()
} }
pub fn as_bytes(&self) -> &[u8] {
&self.u8data[..]
}
pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
&mut self.u8data[..]
}
pub fn insert(&mut self, index: usize, item: char) { pub fn insert(&mut self, index: usize, item: char) {
self.data.insert(index, item); self.data.insert(index, item);
self.u8data.insert(index, item as u8); self.u8data.insert(index, item as u8);
} }
pub fn remove(&mut self, index: usize) -> char {
self.u8data.remove(index);
self.data.remove(index)
}
pub unsafe fn to_cstr(&self) -> Vec<u8> {
let mut res = self.u8data.clone();
res.push(0);
res
}
} }
impl FromIterator<char> for String { impl FromIterator<char> for String {
@ -54,8 +57,14 @@ impl<'a> FromIterator<&'a char> for String {
} }
} }
impl From<&str> for String {
fn from(value: &str) -> Self {
Self::from_iter(value.chars())
}
}
impl ToString for String { impl ToString for String {
fn to_string(&self) -> String { fn to_string(&self) -> Self {
self.clone() self.clone()
} }
} }
@ -63,15 +72,17 @@ impl ToString for String {
impl Add for String { impl Add for String {
type Output = Self; type Output = Self;
fn add(mut self, rhs: Self) -> Self::Output { fn add(mut self, mut rhs: Self) -> Self::Output {
self.data.append(&mut rhs.chars().map(|c| *c).collect()); self.data.append(&mut rhs.data);
self.u8data.append(&mut rhs.u8data);
self self
} }
} }
impl AddAssign for String { impl AddAssign for String {
fn add_assign(&mut self, rhs: String) { fn add_assign(&mut self, mut rhs: String) {
*self = self.clone() + rhs; self.data.append(&mut rhs.data);
self.u8data.append(&mut rhs.u8data);
} }
} }

View File

@ -1,5 +1,6 @@
use core::{ use core::{
alloc::Layout, alloc::Layout,
mem::size_of,
ops::{Index, IndexMut, Range, RangeFull}, ops::{Index, IndexMut, Range, RangeFull},
ptr::addr_of_mut, ptr::addr_of_mut,
slice, slice,
@ -19,18 +20,24 @@ pub struct Vec<T> {
impl<T: Default> Vec<T> { impl<T: Default> Vec<T> {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
pointer: unsafe { alloc(Layout::array::<T>(4).unwrap()).cast() }, pointer: unsafe {
alloc(Layout::from_size_align_unchecked(4 * size_of::<T>(), 1)).cast()
},
length: 0, length: 0,
capacity: 4, capacity: 4,
} }
} }
unsafe fn extend_capacity(&mut self) { unsafe fn extend_capacity(&mut self) {
let newp: *mut T = alloc(Layout::array::<T>(self.capacity * 2).unwrap()).cast(); let newp: *mut T = alloc(Layout::from_size_align_unchecked(
self.capacity * 2 * size_of::<T>(),
1,
))
.cast();
self.pointer.kcopy_to(newp, self.length); self.pointer.kcopy_to(newp, self.length);
dealloc( dealloc(
self.pointer.cast(), self.pointer.cast(),
Layout::array::<T>(self.capacity).unwrap(), Layout::from_size_align_unchecked(self.capacity * size_of::<T>(), 1),
); );
self.pointer = newp; self.pointer = newp;
self.capacity *= 2; self.capacity *= 2;
@ -51,7 +58,11 @@ impl<T: Default> Vec<T> {
let rearlen = self.length - index; let rearlen = self.length - index;
unsafe { unsafe {
if rearlen != 0 { if rearlen != 0 {
let tmp = alloc(Layout::array::<T>(rearlen).unwrap()).cast(); let tmp = alloc(Layout::from_size_align_unchecked(
rearlen * size_of::<T>(),
1,
))
.cast();
self.pointer.offset(index as isize).kcopy_to(tmp, rearlen); self.pointer.offset(index as isize).kcopy_to(tmp, rearlen);
self.pointer.offset(index as isize).write(item); self.pointer.offset(index as isize).write(item);
self.pointer self.pointer
@ -116,7 +127,7 @@ impl<T: Default> Vec<T> {
t t
} }
pub fn iter(&self) -> VecIterator<T> { pub fn iter<'a, 'b: 'a>(&'a self) -> VecIterator<'b, T> {
VecIterator { VecIterator {
pointer: self.pointer, pointer: self.pointer,
index: 0, index: 0,
@ -124,6 +135,10 @@ impl<T: Default> Vec<T> {
_phantom: &(), _phantom: &(),
} }
} }
pub unsafe fn get_pointer(&self) -> *mut T {
self.pointer
}
} }
impl<T: Default> Default for Vec<T> { impl<T: Default> Default for Vec<T> {
@ -165,7 +180,13 @@ impl<T: Default> IndexMut<RangeFull> for Vec<T> {
impl<T: Default> Clone for Vec<T> { impl<T: Default> Clone for Vec<T> {
fn clone(&self) -> Self { fn clone(&self) -> Self {
let res = Self { let res = Self {
pointer: unsafe { alloc(Layout::array::<T>(self.capacity).unwrap()).cast() }, pointer: unsafe {
alloc(Layout::from_size_align_unchecked(
self.capacity * size_of::<T>(),
1,
))
.cast()
},
length: self.length, length: self.length,
capacity: self.capacity, capacity: self.capacity,
}; };
@ -182,7 +203,7 @@ impl<T> Drop for Vec<T> {
unsafe { unsafe {
dealloc( dealloc(
self.pointer.cast(), self.pointer.cast(),
Layout::array::<T>(self.capacity).unwrap(), Layout::from_size_align_unchecked(self.capacity * size_of::<T>(), 1),
) )
}; };
} }
@ -198,17 +219,33 @@ impl<T: Default> FromIterator<T> for Vec<T> {
} }
} }
impl<'a> FromIterator<&'a char> for Vec<char> {
fn from_iter<U: IntoIterator<Item = &'a char>>(iter: U) -> Self {
let mut res = Vec::new();
for i in iter {
res.push(*i);
}
res
}
}
impl<T: Default> IntoIterator for Vec<T> { impl<T: Default> IntoIterator for Vec<T> {
type Item = T; type Item = T;
type IntoIter = VecIter<T>; type IntoIter = VecIter<T>;
fn into_iter(self) -> Self::IntoIter { fn into_iter(self) -> Self::IntoIter {
/*let pointer = unsafe {
let pointer = alloc(Layout::from_size_align_unchecked(
self.capacity * size_of::<T>(),
1,
));
pointer.copy_from(self.pointer.cast(), self.length);
pointer.cast()
};*/
VecIter { VecIter {
pointer: self.pointer, vec: self,
index: 0, index: 0,
length: self.length,
capacity: self.capacity,
} }
} }
} }
@ -246,22 +283,21 @@ impl<'a, T: 'a> DoubleEndedIterator for VecIterator<'a, T> {
} }
pub struct VecIter<T> { pub struct VecIter<T> {
pointer: *mut T, vec: Vec<T>,
index: usize, index: usize,
length: usize,
capacity: usize,
} }
impl<T: Default> Iterator for VecIter<T> { impl<T: Default> Iterator for VecIter<T> {
type Item = T; type Item = T;
fn next(&mut self) -> Option<Self::Item> { fn next(&mut self) -> Option<Self::Item> {
if self.index == self.length { if self.index == self.vec.length {
None None
} else { } else {
let mut t = T::default(); let mut t = T::default();
let res = unsafe { let res = unsafe {
self.pointer self.vec
.pointer
.offset(self.index as isize) .offset(self.index as isize)
.kcopy_to(addr_of_mut!(t), 1); .kcopy_to(addr_of_mut!(t), 1);
Some(t) Some(t)
@ -271,14 +307,3 @@ impl<T: Default> Iterator for VecIter<T> {
} }
} }
} }
impl<T> Drop for VecIter<T> {
fn drop(&mut self) {
unsafe {
dealloc(
self.pointer.cast(),
Layout::array::<T>(self.capacity).unwrap(),
)
};
}
}

View File

@ -1,4 +1,4 @@
use core::mem::{size_of, transmute}; use core::mem::size_of;
extern "C" { extern "C" {
pub fn memset(des: *const u8, src: u8, len: usize); pub fn memset(des: *const u8, src: u8, len: usize);
@ -14,16 +14,16 @@ pub trait PtrOptions<T> {
impl<T> PtrOptions<T> for *mut T { impl<T> PtrOptions<T> for *mut T {
unsafe fn kcopy_from(self, src: *const T, count: usize) { unsafe fn kcopy_from(self, src: *const T, count: usize) {
memcpy( memcpy(
transmute(self.cast_const()), self.cast_const() as *const u8,
transmute(src), src.cast(),
count * size_of::<T>(), count * size_of::<T>(),
); );
} }
unsafe fn kcopy_to(self, des: *const T, count: usize) { unsafe fn kcopy_to(self, des: *const T, count: usize) {
memcpy( memcpy(
transmute(des), des.cast(),
transmute(self.cast_const()), self.cast_const() as *const u8,
count * size_of::<T>(), count * size_of::<T>(),
); );
} }

View File

@ -378,7 +378,7 @@
// 0 // 0
00000000, 00000000,
00000000, 00000000,
00111100, /// 00011000, ///
00100100, 00100100,
01000010, 01000010,
01000010, 01000010,
@ -387,7 +387,7 @@
01000010, 01000010,
01000010, 01000010,
00100100, 00100100,
00111100, // 00011000, //
00000000, 00000000,
00000000, 00000000,
00000000, 00000000,